Create new Tkinter window with new thread

Viewed 1341

I'm attempting to create a Tkinter GUI that runs the mainloop in its own thread, enabling me to run things in other threads (which potentially involves updating elements in the Tkinter GUI). I have the construct below.

import tkinter as tk
from threading import Thread

class DisplayWindow(object):

    def __init__(self):
        self.running = False

    def start(self):
        self.running = True
        self.thread = Thread(target = self.run)
        self.thread.start()

    def callback(self):
        self.running = False
        self.root.destroy()

    def run(self):
        self.root = tk.Tk()
        self.root.protocol('WM_DELETE_WINDOW', self.callback)
        self.root.geometry('600x600')

        tk.Label(self.root, text='Hello World').pack()

        self.root.mainloop()

I can do something like the following with this

win = DisplayWindow()
win.start()

My understanding of how this works is that when win.start() is called the first time, a new thread is created, set to run the run method, and the thread is started. This thread executes the creation of a Tkinter GUI that runs the mainloop until the window is closed (at which time the thread should become inactive). If I close the window and call win.start() again, I expect that the second call should just repeat the process, creating a new thread that calls the run method. However, calling start a second time simply crashes python.

What am I doing wrong?

0 Answers
Related