我一直在为一个我正在处理的申请头疼了一段时间。在花了好几个小时试图调试一个接口锁定而其他什么都不能发生的问题之后,我发现这是一个可怕的While循环。请参阅下面的示例并运行它。当你通过点击按钮启动while循环时,你不能在屏幕上做任何其他事情。在这种情况下,它只是一个简单的警报按钮,需要按下。在
from Tkinter import *
import tkMessageBox
root = Tk()
root.geometry("450x250+300+300")
root.title("Raspberry PI Test")
def myloop():
count = 0
while (count < 500):
print 'The count is:', count
count = count + 1
print "Good bye!"
def mymessage():
tkMessageBox.showinfo(title="Alert", message="Hello World!")
buttonLoop = Button(root, text="Start Loop", command=myloop)
buttonLoop.place(x=5, y=15)
buttonMessage = Button(root, text="Start Loop", command=mymessage)
buttonMessage.place(x=85, y=15)
root.mainloop()
我怎样才能有一个循环需要运行,直到计数完成,并且仍然能够在我的应用程序中执行其他任务?我还应该注意到,我用一个线程尝试过同样的事情,这没关系。UI仍在等待While循环结束,然后才能执行任何操作。在
下面是最后的代码,只是为了证明线程是可以工作的。计数同时显示在屏幕上。再次感谢乔兰!在
我对TKinter了解不多,但从我的阅读中可以清楚地看到,为了更新文本框,您需要在while循环中使用一些TKinter方法。TKinter运行在一个事件循环上,因此您必须从代码中发送信号以重新进入TKinter的执行。在
您发现
while
循环阻塞了UI更新的执行,这项工作做得很好。因此,您不需要线程化,只需暂停counting's
执行,让TKinter
更新UI。在这个tutorial提供了一个很好的例子。关键是在第24行,他调用
root.update
,我相信这会破坏你的程序,让TKinter做这件事。在既然我明白了你想要什么(秒表),我建议根。后命令
(以下为原始答案)
用线
^{pr2}$请注意,当你显示信息框时,它将在windows api级别阻塞,因此线程计数将一直等到它关闭。。。为了解决这个问题,我想你可以用多处理来代替线程
相关问题 更多 >
编程相关推荐