Python Tkinter按钮不更改全局变量
我已经开始学习python gui。按钮函数调用不会更新全局变量。目前我在下面的代码中面临问题Python Tkinter按钮不更改全局变量,python,button,tkinter,Python,Button,Tkinter,我已经开始学习python gui。按钮函数调用不会更新全局变量。目前我在下面的代码中面临问题 from tkinter import * root=Tk() root.title("learning") s="" def change() : global str str="program" button1=Button(root,text="Click me", command=cha
from tkinter import *
root=Tk()
root.title("learning")
s=""
def change() :
global str
str="program"
button1=Button(root,text="Click me", command=change).pack()
print(s)
root.mainloop()
str
的值不更新
s=“”
def change():
更改()
印刷品
此处s的值将在程序中打印,而使用tkinter时,该值为空。请尝试以下操作:
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)
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()
尝试这样做:
- 首先单击“打印x”-这将打印一个空白
- 然后单击
-click Me
更改程序x
- 然后再次单击“打印x”-这应该是一个打印程序
button1
是None
,正如您在同一行中使用的.pack
。因此,如果您想在前面的代码中使用按钮1
,请将其用作:
button1 = Button(root, text='Click me', command=change)
button1.pack()
试试这个:
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)
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()
单击按钮时,会立即调用函数change(),因此,打印函数应该放在change()中。
str
是python中的一个关键字。关键字不能用作变量名。将其更改为其他更改变量名并不能解决问题。值仍然没有更改a=“hi”def check():全局a=“hello”check()打印(a)hello在此处打印,但使用tkinter按钮该值不更新。添加了一个非常详细的答案,请告诉我使用按钮的函数调用没有更新全局变量,而直接调用函数更新它。为什么会这样?我必须在代码的后面部分使用这个变量。我的目的是使用变量,不仅仅是打印它,还可以解释为什么该值在函数中是正确的,而不是在函数外