Reputation: 33
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?
Upvotes: 1
Views: 8736
Reputation: 15226
Your use of global is a bit off. You do not need to define global all over the place. Lets break it down a little.
You don't need to define global namespace in the global namespace.
from tkinter import *
window = Tk()
myvar = "data" # this variable is already in the global namespace
This tells the function to check global namespace when its interacts with the variable myvar
.
def changeVariable():
global myvar
myvar = "different data"
This print statement works because it checks the global variable namespace after it has check the other namespaces without finding the variable myvar
.
def printVariable():
print(myvar)
button1 = Button(window, command = changeVariable)
button1.pack()
button2 = Button(window, command = printVariable)
button2.pack()
window.mainloop()
So if we put this code together we will get the desired result.
from tkinter import *
window = Tk()
variable = "data"
def changeVariable():
global variable
variable = "different data"
def printVariable():
print(variable)
button1 = Button(window, command = changeVariable)
button1.pack()
button2 = Button(window, command = printVariable)
button2.pack()
window.mainloop()
This results in a window that looks like this:
and the result if we press the bottom button first then the top button then the bottom button again we get:
Upvotes: 2