Tkinter Button Not Changing Global Variable
I have started learning python gui.Button function call doesn't update the global variable. Currently I am facing problem in below code. from tkinter import * root=Tk() root.titl
Solution 1:
Try this:
from tkinter import *
root=Tk()
root.title("learning")
x=""
def change() :
global x
x="program"
print(x)
def prt():
global x
print(x)
Button(root,text="Click me", command=change).pack()
Button(root,text="Print x", command=prt).pack()
root.mainloop()
print(x)
Try to do this:
- Click 'Print x' first - This should print an empty space
- Then click on
Click Me
-x
changes to program - And then again click on 'Print x' - this should print program
Another error - button1
is None
as you have used .pack
on the same line. So if you want to use button1
in your code ahead, use it as:
button1 = Button(root, text='Click me', command=change)
button1.pack()
Solution 2:
Try this:
from tkinter import *
def change():
global str
str="program"
print(str) # print function should be placed here
root=Tk()
root.title("learning")
root.geometry("300x300")
str=""
button1=Button(root,text="Click me", command=change).pack()
root.mainloop()
when the button is clicked, immediately the function change() will be called so, the print function should be placed in change()
Post a Comment for "Tkinter Button Not Changing Global Variable"