Q:

Thread doesn't close on exiting tk window

I have an application written in Python, using Tkinter. One of the features allows a serial port to be opened, after which any messages received over the serial port are displayed in a text window. This works fine. The problem comes when I close the window, which doesn't kill the thread monitoring the serial port. It then has to be killed manually (alternatively, unplugging the USB-serial cable causes an exception which kills the process).
I assume I'm missing something simple here, but I would have thought closing the application would close all associated threads. I can't seem to find anything about this in the documentation, but I'm probably looking in the wrong place?
Code for the serial thread in case it's relevant:
class SerialThread(threading.Thread):

    def __init__(self, queue, sp):
        threading.Thread.__init__(self)
        self.queue = queue
        self.ser_handle = sp;

    def run(self):
        while True:
            if self.ser_handle.inWaiting():
                text = self.ser_handle.readline(self.ser_handle.inWaiting())
                self.queue.put(text)
            time.sleep(0.2) 

A:

You must have a way to ask the thread for stop, you can accomplish that using: threading.Event.
class SerialThread(threading.Thread):

    def __init__(self, queue, sp):
        threading.Thread.__init__(self)
        self.queue = queue
        self.event = threading.Event() # An event object.
        self.ser_handle = sp;

    def stop(self):
        self.event.set()

    def run(self):
        while not self.event.isSet():
            if self.ser_handle.inWaiting():
                text = self.ser_handle.readline(self.ser_handle.inWaiting())
                self.queue.put(text)
            time.sleep(0.2) 

Then in the on close event of your window, call your_thread.stop()

