【问题标题】:Stopping a python thread from a tkinter gui从 tkinter gui 停止 python 线程
【发布时间】:2014-02-23 03:34:02
【问题描述】:

我正在尝试创建一个简单的 Python GUI(使用 Tkinter),带有开始按钮、在线程中运行 while 循环,以及用于停止 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()

知道如何解决这个问题吗?我确信这是微不足道的,并且必须完成数千次,但我自己找不到解决方案。

谢谢 大卫

【问题讨论】:

    标签: python multithreading tkinter


    【解决方案1】:

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

    def startCallBack():        
        myJob.start()
    

    【讨论】:

      猜你喜欢
      • 2015-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多