从tkinter gui停止python线程

2024-03-28 23:50:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个简单的pythongui(使用Tkinter),在线程中运行while循环,并使用stop按钮停止while循环。在

我有问题的停止按钮,它不会停止任何东西和冻结的图形用户界面一旦开始按钮被点击。在

参见以下代码:

import threading
import Tkinter

class MyJob(threading.Thread):

    def __init__(self):
        super(MyJob, self).__init__()
        self._stop = threading.Event()

    def stop(self):
        self._stop.set()    

    def run(self):
        while not self._stop.isSet():
            print "-"

if __name__ == "__main__":

    top = Tkinter.Tk()

    myJob = MyJob()

    def startCallBack():        
        myJob.run()

    start_button = Tkinter.Button(top,text="start", command=startCallBack)
    start_button.pack()

    def stopCallBack():
        myJob.stop()

    stop_button = Tkinter.Button(top,text="stop", command=stopCallBack)
    stop_button.pack()

    top.mainloop()

你知道怎么解决这个问题吗?我相信这是微不足道的,肯定已经做了数千次,但我自己找不到解决办法。在

谢谢 大卫


Tags: runimportselfinittkintertopdefbutton
1条回答
网友
1楼 · 发布于 2024-03-28 23:50:27

代码直接调用run方法。它将调用主线程中的方法。要在单独的线程中运行它,您应该使用^{} method。在

def startCallBack():        
    myJob.start()

相关问题 更多 >