The code the problem is part of is fairly big so I'm drafting a fingerpainting version here.
import tkinter
variable = "data"
def changeVariable():
variable = "different data"
def printVariable():
print(variable)
window = tkinter.Tk
button1 = tkinter.Button(window, command=changeVariable)
button1.pack()
button2 = tkinter.Button(window, command=printVariable)
button2.pack()
So in this example, I press the first button to change 'variable', then the second button to print it. But "data" is printed instead of "different data". I searched around a bit and decided to use global before defining the variable in both the main code and in the functions, so the code looked like this.
import tkinter
global variable
variable = "data"
def changeVariable():
global variable
variable = "different data"
def printVariable():
global variable
print(variable)
window = tkinter.Tk()
button1 = tkinter.Button(window, command=changeVariable)
button1.pack()
button2 = tkinter.Button(window, command=printVariable)
button2.pack()
window.mainloop()
But now it says 'name 'variable' is not defined'.
Essentially, how can I get the variable 'variable' to change with a button in tkinter? Was I wrong to think of using global?


global variable.window = tkinter.Tk()and addwindow.mainloop()at the end.globaldirective is used inside a function to tell the function to look up the name in the global namespace. It doesn't make sense to use it in the global namespace itself. But really, it's a good idea to avoid using modifiable globals because they break program modularity. The neat way to do this is to define your GUI as a class, and then you can use instance attributes to save state data. BTW, it's a common practice to doimport tkinter as tk. Then you can do stuff likebutton = tk.Button(window).