I made a simple code and my question is if is there a way to avoid globals in tkinter in this kind of scenario:
root = Tk()
root.title('Main')
root.minsize(400, 450)
toggle = True
def change_now():
global toggle
root.config(bg='blue') if toggle else root.config(bg='black')
toggle = not toggle
my_button = Button(root, text='Click me!', command=change_now)
my_button.pack()
root.mainloop()
I know the best option is an object-oriented approach, but that means refactoring the entire code, is there a quick solution in this example? I know using global variables is bad practice.
CodePudding user response:
In this specific case, there is a way: use tkinter variables, instead of globals
from tkinter import Tk, Button, BooleanVar
root = Tk()
root.title('Main')
root.minsize(400, 450)
toggle_tkinter = BooleanVar(value=True)
def change_now():
root.config(bg='blue') if toggle_tkinter.get() else root.config(bg='black')
toggle_tkinter.set(not toggle_tkinter.get())
my_button = Button(root, text='Click me!', command=change_now)
my_button.pack()
root.mainloop()
Though, I have personally found a case where globals make a decent design choice (sticking under the assumption that OOP is not viable): imagine that you have a 30 variables that you need to pass on to a checking function that validates the input and then uses only a subset of these variables (or a mixture of them), depending on the user input. In this case, instead of passing all 30 variables to your checker function and then your checker function passing whatever is needed onwards, I've opted to set them all as globals - that way they can be extracted and managed much more easily; see here (the repo contains relevant READMEs and a paper describe the infrastructure) for such a use case if interested.
CodePudding user response:
You can remove the need to manage a global variable by using the background color as the Boolean. Set it to black if it’s currently blue, and blue if it’s black.
def chande_now():
color = “black” if root.cget(“bg”) == “blue” else “blue”
root.configure(bg=color)