I'm doing a large project at the moment to help me learn my first programming language (Python) and I've run into some unknown territory. I am aware that it's generally bad to use global variables and there are better solutions, but I can't figure it out for my situation.
I've made the code below as a simple example of what I want to achieve. What's the best way to do this instead of using the global variable?
Also, are there any general errors I've made in my code below?
Thanks in advance
from tkinter import *
root = Tk()
display_number = 5
class NumberBox():
def __init__(self):
global display_number
self.number_label = Label(root, text=display_number)
self.number_label.pack()
self.engine()
def engine(self):
self.number_label.config(text=display_number)
root.after(10, self.engine)
def change_number(operation):
global display_number
if operation == "add":
display_number += 1
if operation == "subtract":
display_number -= 1
Button(root, text="Add Class", command=lambda: NumberBox()).pack()
Button(root, text="Number UP", command=lambda: change_number("add")).pack()
Button(root, text="Number DOWN", command=lambda: change_number("subtract")).pack()
for _ in range(5):
NumberBox()
root.mainloop()