[Python] python Tkinter- Close thread on window close(x)

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    How do I kill an already running thread when tkinter root window is closed. I am able to detect events but if the user has not started any thread I run into an error while closing the window. Also when closing if I am able to detect thread is running with function

    self.thread.is_alive()

    what command is used to kill the thread?

    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()

    Continue reading...

Compartilhe esta Página