title: python Tkinter- Close thread on window close(x)
body: <p>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</p>
  <p><code>self.thread.is_alive()</code></p>
  <p>what command is used to kill the thread?</p>
  <pre class="lang-py prettyprint-override"><code>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(&quot;myapp&quot;)
          master.protocol(&quot;WM_DELETE_WINDOW&quot;, self.on_closing)
  
      def createWidgets(self):
          self.btn = tk.Button(self)
          self.btn[&quot;text&quot;] = &quot;Start..&quot;
          self.btn.pack()
          self.btn[&quot;command&quot;] = self.startProcess
  
      def startProcess(self):
         self.thread = threading.Thread(target=self.helloWorld, args=(&quot;Hello World&quot;,))
         self.thread.start()
  
      def helloWorld(self, txt):
         for x in range(5):
            print (txt)
            time.sleep(5)
  
  
      def on_closing(self):
          if messagebox.askokcancel(&quot;myapp&quot;, &quot;Do you want to quit?&quot;):
              if self.thread.is_alive():
                  self.thread.stop()
              self.master.destroy()
  
  def main():
      root = tk.Tk()
      app = Application(master=root)
      app.mainloop()
  
  
  if __name__ == &quot;__main__&quot;:
      main()
  </code></pre>