![](/img/trans.png)
[英]How to Display and Update a Message or Label containg results using TopLevel Tkinter inside a for loop at every iteration in Python?
[英]How to update a Label inside while loop in tkinter?
我正在尝试在while循环内的tkinter中更新窗口的标签,但文本没有更新。以下是代码。
from Tkinter import *
window=Tk();
text1=StringVar();
text1.set("Waiting for Button Press...");
def main():
while True:
if condition:'''The condition is GPIO READ statement but for simplicity I have used condition'''
text1.set("IN Button Pressed.Loading Camera.");
window.update()
lbl=Label(window,text=text1.get());
lbl.pack();
window.after(5000,main);
window.mainloop();
要动态更新标签的文本,可以使用lbl["text"]
我无法完全遵循您的代码(因为我对此还不是太新...),但是我认为您可以使用此代码并以这种方式重新编写代码。
from Tkinter import *
window=Tk()
text1 = "Waiting for Button Press..."
lbl=Label(window,text=text1)
lbl.pack()
def main():
while True:
if condition:'''The condition is GPIO READ statement but for simplicity I have used condition'''
lbl["text"] = "IN Button Pressed.Loading Camera."
window.after(5000,main)
window.mainloop()
不确定是否需要window.update()
正如我在评论中说的那样,像您尝试那样使用while
循环会干扰Tkinter自己的mainloop()
。 重复执行某些操作而不停止Tkinter GUI的主循环通常是通过使用通用的after()
方法(您似乎已经知道)来完成的。
此外,如果将Label
小部件的textvariable=
(而不是text=
)选项设置为StringVar
,则对Tkinter变量的更改将自动更新Label
的外观。 这是我发现的有关使用Tkinter变量类的一些文档。
以下示例代码显示了如何通过实施以下建议来实现目标:
from random import randint
from Tkinter import *
MS_DELAY = 500 # Milliseconds between updates.
window = Tk()
text1 = StringVar()
def gpio_read():
""" Simulate GPIO READ. """
return randint(0, 3)
def check_condition():
if gpio_read() == 0:
text1.set("IN Button Pressed.Loading Camera.")
else:
text1.set("Waiting for Button Press...")
window.after(MS_DELAY, check_condition) # Schedule next check.
lbl = Label(window, textvariable=text1) # Link to StringVar's value.
lbl.pack()
window.after(MS_DELAY, check_condition) # Schedule first check.
window.mainloop()
您可以执行以下操作:
condition
设置为False
,并且在main
更改为True
。
5秒后,将change_if_condition
方法,检查condition
,如果找到True
,则更改标签textvariable并自动更新标签。
from tkinter import *
def change_if_condition():
if condition:
text1.set("IN Button Pressed.Loading Camera.")
def main():
global condition
condition= True
window.after(5000, change_if_condition)
window = Tk()
text1 = StringVar()
text1.set("Waiting for Button Press...")
lbl = Label(window, textvariable=text1) # use textvariable, so the displayed text is changed when the variable changes
lbl.pack()
condition = False
main()
window.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.