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

半世苍凉 提交于 2019-12-01 17:42:31

If it's a thread, you can use the lower-level thread (or _thread in Python 3) module to kill the thread with an exception by calling thread.exit().

From the documentation:

  • thread.exit(): Raise the SystemExit exception. When not caught, this will cause the thread to exit silently.

A cleaner method (depending on how your processing is set up) would be to signal the thread to stop processing and exit using an instance variable, then calling the join() method from your main thread to wait until the thread exits.

Example:

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!