Python Tkinter:只要线程运行,我如何使我的 GUI 响应? [英] Python Tkinter: How do I make my GUI responsive as long as a thread runs?

查看:51
本文介绍了Python Tkinter:只要线程运行,我如何使我的 GUI 响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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.

Well, if I start my example it works as expected. I click on a button, my_function starts and the GUI is responsive. But I have read that I should avoid the use of update(). So, it would be nice if some one could explain why and how I have to wait for a thread correctly? Step Two is in a thread because it takes a much longer time than Step One and Step Three, otherwise it would block the GUI.

我是 Python 新手,我正在尝试编写我的第一个程序".也许我的想法是错误的,因为我不是很有经验......

I'm new to Python and I trying to write my first "program". Maybe I'm thinking in a wrong way since I'm not very experienced...

问候,大卫.

推荐答案

你需要记住你有一个事件循环在运行,所以你需要做的就是在每次事件循环进行迭代时检查线程.好吧,不是每次,而是定期.

You need to remember that you have an event loop running, so all you need to do is check on the thread each time the event loop makes an iteration. Well, not every time, but periodically.

例如:

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()

这篇关于Python Tkinter:只要线程运行,我如何使我的 GUI 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆