python Tkinter-关闭窗口关闭线程(x)

时间:2017-11-29 04:46:45

标签: python multithreading tkinter

如何在关闭tkinter根窗口时终止已经运行的线程。我能够检测到事件,但如果用户没有启动任何线程,我在关闭窗口时遇到错误。关闭时,如果我能够检测到线程正在运行函数

self.thread.is_alive

用什么命令来杀死线程?

import threading
import tkinter as tk
from tkinter import messagebox
import time


class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()
        self.master.title("myapp")
        master.protocol("WM_DELETE_WINDOW", self.on_closing)

    def createWidgets(self):
        self.btn = tk.Button(self)
        self.btn["text"] = "Start.."
        self.btn.pack()
        self.btn["command"] = self.startProcess

    def startProcess(self):
       self.thread = threading.Thread(target=self.helloWorld, args=("Hello World",))
       self.thread.start()

    def helloWorld(self, txt):
       for x in range(5):
          print (txt)
          time.sleep(5)


    def on_closing(self):
        if messagebox.askokcancel("myapp", "Do you want to quit?"):
            if self.thread.is_alive():
                self.thread.stop()
            self.master.destroy()

def main():
    root = tk.Tk()
    app = Application(master=root)
    app.mainloop()


if __name__ == "__main__":
    main()

0 个答案:

没有答案