Python 和 tkinter:全局变量不起作用?
这是一个使用 tkinter 的简单程序。它基本上应该显示用户在 inp 字段中键入的任何内容,并在单击按钮时将其显示为标签。 在这里,我尝试将 tkinter 值包含为全局变量,然后在 change_label() 中使用它:
from tkinter import *
def change_label():
global new_text
my_label['text'] = new_text
window = Tk()
window.title("My first GUI program")
window.minsize(width=500, height=300)
my_label = Label(text="This is a label.", font=('Arial', 24, 'bold'))
my_label.pack()
button = Button(text="Click me!", command=change_label)
button.pack()
inp = Entry(width=10)
inp.pack()
new_text = inp.get()
window.mainloop()
但是在运行时,单击按钮会导致显示空标签。
但是,如果我在change_label() 中声明new_text,则代码可以正常工作。
from tkinter import *
def change_label():
new_text = inp.get()
my_label['text'] = new_text
window = Tk()
window.title("My first GUI program")
window.minsize(width=500, height=300)
my_label = Label(text="This is a label.", font=('Arial', 24, 'bold'))
my_label.pack()
button = Button(text="Click me!", command=change_label)
button.pack()
inp = Entry(width=10)
inp.pack()
window.mainloop()
为什么第一个代码不起作用而第二个代码却起作用?
This is a simple program using tkinter. It's basically supposed to display whatever the user types in the inp field and display it as a label on clicking a button.
Here I have tried containing the tkinter value as a global variable and then using it in change_label():
from tkinter import *
def change_label():
global new_text
my_label['text'] = new_text
window = Tk()
window.title("My first GUI program")
window.minsize(width=500, height=300)
my_label = Label(text="This is a label.", font=('Arial', 24, 'bold'))
my_label.pack()
button = Button(text="Click me!", command=change_label)
button.pack()
inp = Entry(width=10)
inp.pack()
new_text = inp.get()
window.mainloop()
But on running, clicking the button results in showing an empty label.
However, if I declare new_text inside change_label(), the code works fine.
from tkinter import *
def change_label():
new_text = inp.get()
my_label['text'] = new_text
window = Tk()
window.title("My first GUI program")
window.minsize(width=500, height=300)
my_label = Label(text="This is a label.", font=('Arial', 24, 'bold'))
my_label.pack()
button = Button(text="Click me!", command=change_label)
button.pack()
inp = Entry(width=10)
inp.pack()
window.mainloop()
Why does the first code not work while the second does?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
StringVar
可以帮助您比Global
更有效地管理Label
或Entry
等小部件的值。我在Entry
小部件中添加了textvariable
。另外,重新排列代码以提高可读性第一个代码:
单击前的结果:
单击后的结果:
Used
StringVar
to helps you manage the value of a widget such as aLabel
orEntry
more effectively thanGlobal
. I addedtextvariable
inEntry
widget. Also, rearranged code to read most readabilityThe first code:
Result before clicking:
Result after clicking: