如何从Tkinter窗口立即停止Python进程?

Bra*_*ers 5 python tkinter inject

我有一个Python GUI,用于测试我工作的各个方面.目前我有一个"停止"按钮,可以在每次测试结束时终止进程(可以设置多个测试立即运行).但是,有些测试需要很长时间才能运行,如果我需要停止测试,我希望它立即停止.我的想法是使用

import pdb; pdb.set_trace()
exit
Run Code Online (Sandbox Code Playgroud)

但是我不确定如何将它注入到下一行代码中.这可能吗?

pR0*_*0Ps 5

如果它是一个线程,您可以使用较低级别thread(或_thread在Python 3中)模块通过调用来杀死具有异常的线程thread.exit().

文档:

  • thread.exit():引发SystemExit异常.未捕获时,这将导致线程以静默方式退出.

一个更干净的方法(取决于你的处理设置方式)将指示线程停止处理并使用实例变量退出,然后join()从主线程调用该方法等待线程退出.

例:

class MyThread(threading.Thread):

    def __init__(self):
        super(MyThread, self).__init__()
        self._stop_req = False

    def run(self):
        while not self._stop_req:
            pass
            # processing

        # clean up before exiting

    def stop(self):
        # triggers the threading event
        self._stop_req = True;

def main():
    # set up the processing thread
    processing_thread = MyThread()
    processing_thread.start()

    # do other things

    # stop the thread and wait for it to exit
    processing_thread.stop()
    processing_thread.join()

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)