我试图用启动按钮创建一个简单的Python GUI(带有Tkinter),在线程中运行while循环,并使用stop按钮停止while循环。

我在使用“停止”按钮时遇到了问题,一旦单击“开始”按钮,该按钮就不会停止任何操作并冻结GUI。

请参见下面的代码:

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


任何想法如何解决这个问题?我敢肯定这是微不足道的,必须完成数千次,但我自己找不到解决方案。

谢谢
大卫

最佳答案

该代码直接调用run方法。它将在主线程中调用该方法。要在单独的线程中运行它,应使用threading.Thread.start method

def startCallBack():
    myJob.start()

09-11 18:58