4

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()
Art
  • 2,836
  • 4
  • 17
  • 34
Aprilian8
  • 370
  • 1
  • 5
  • 14
  • `I run into error while closing window` what error? – user1767754 Nov 29 '17 at 04:54
  • AttributeError: Application instance has no attribute 'thread' – Aprilian8 Nov 29 '17 at 05:13
  • Ok, you are trying to kill a thread, which you shouldn't be doing, you should handle that properly. Furthermore there is no `stop` method, the only stop method is `_stop()` which will still not help you in you case. Read this: https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python – user1767754 Nov 29 '17 at 05:30
  • inside ther;eadbyou should use `if stop: return` and on closing `stop = True` and yuo could wait till it ends `self.thread.join()` – furas Nov 29 '17 at 05:52
  • Probably not _the_ problem, but _a_ problem is that you're calling `self.thread.start()` before you define `self.thread`. – Bryan Oakley Nov 29 '17 at 13:03
  • @Bryan Oakley. Thats just some extra line. typo. I will edit that. – Aprilian8 Nov 30 '17 at 05:22

0 Answers0