例如:
import threading
import time
import Tkinter
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print "Step Two"
time.sleep(20)
class MyApp(Tkinter.Tk):
def __init__(self):
Tkinter.Tk.__init__(self)
self.my_widgets()
def my_widgets(self):
self.grid()
self.my_button = Tkinter.Button(self, text="Start my function",
command=self.my_function)
self.my_button.grid(row=0, column=0)
def my_function(self):
print "Step One"
mt = MyThread()
mt.start()
while mt.isAlive():
self.update()
print "Step Three"
print "end"
def main():
my_app = MyApp()
my_app.mainloop()
if __name__ == "__main__":
main()
好吧,如果我开始我的示例,它就会按预期工作。我单击一个按钮,my_function 启动并且 GUI 响应。但我读到我应该避免使用 update()。因此,如果有人能够解释为什么以及如何我必须正确等待线程,那就太好了?第二步在一个线程中,因为它比第一步和第三步花费的时间要长得多,否则会阻塞 GUI。
我是 Python 新手,我正在尝试编写我的第一个“程序”。也许我的想法是错误的,因为我经验不足......
问候,
大卫。
您需要记住,您有一个事件循环正在运行,因此您需要做的就是每次事件循环进行迭代时检查线程。嗯,不every时间,但定期。
例如:
def check_thread(self):
# Still alive? Check again in half a second
if self.mt.isAlive():
self.after(500, self.check_thread)
else:
print "Step Three"
def my_function(self):
self.mt = MyThread()
self.mt.start()
self.check_thread()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)