簡體   English   中英

如何從Tkinter窗口立即停止Python進程?

[英]How do I stop a Python process instantly from a Tkinter window?

我有一個Python GUI,可用於測試工作的各個方面。 目前,我有一個“停止”按鈕,可以在每次測試結束時終止該進程(可以設置多個測試同時運行)。 但是,有些測試需要很長時間才能運行,如果我需要停止測試,我希望它立即停止。 我的想法是用

import pdb; pdb.set_trace()
exit

但是我不確定如何將其注入下一行代碼中。 這可能嗎?

如果是線程,則可以使用低級thread (或Python 3中的_thread )模塊通過調用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM