How to avoid global variables in command function call How to avoid global variables in command function call tkinter tkinter

How to avoid global variables in command function call


Normally, if you want a button to toggle a variable between one of N values, you would use a set of radiobuttons. When you use a radiobutton you can associate it with a variable so that whenever you click the button, the variable is automatically selected.

For example:

planet = IntVar()planet.set(0)buttonBlue = Radiobutton(wind, text="Blue Planet", variable=planet, value=1)buttonOrange = Radiobutton(wind, text="Orange Planet", variable=planet, value=0)...def choice (event):#Function binded to can, move the selected planet (blue = 1, prange = 0)    if planet.get() == 0:        moveOrange(event)    else :        moveBlue(event)

If you really want to use a regular button, you can do that with a single callback rather than two, and then use lambda or functools.partial to pass in the new value.

For example:

buttonBlue = Button(wind, text = 'Blue Planet', command = lambda: change(1))buttonOrange = Button(wind, text = 'Blue Planet', command = lambda: change(0))def change(newValue):    global a    a = newValue


Unfortunately, you cannot have a lambda expression with a statement (assignment) in it.But you can easily have just one setter function which returns a closure that you can pass to your Button constructor. Here's an example of creating and using closures:

a = 0def set_a (v):    def closure ():        global a        a = v    return closurecommand = set_a(42)command()print a    # prints 42command = set_a(17)command()print a    # prints 17