Threaded Tkinter script crashes when creating the second Toplevel widget Threaded Tkinter script crashes when creating the second Toplevel widget tkinter tkinter

Threaded Tkinter script crashes when creating the second Toplevel widget


Tkinter is designed to run from the main thread, only. See the docs:

Just run all UI code in the main thread, and let the writers write to a Queue object; e.g.

...and a substantial example follows, showing secondary threads writing requests to a queue, and the main loop being exclusively responsible for all direct interactions with Tk.

Many objects and subsystems don't like receiving requests from multiple various threads, and in the case of GUI toolkit it's not rare to need specfically to use the main thread only.

The right Python architecture for this issue is always to devote a thread (the main one, if one must) to serving the finicky object or subsystem; every other thread requiring interaction with said subsystem or object must them obtain it by queueing requests to the dedicated thread (and possibly waiting on a "return queue" for results, if results are required as a consequence of some request). This is also a very sound Python architecture for general-purpose threading (and I expound on it at length in "Python in a Nutshell", but that's another subject;-).


Tkinter has issues dealing with input from multiple threads, I use mtTkinter instead, you won't need to change any code and everything will work fine. Just import mtTkinter instead of Tkinter.

You can get it here:

http://tkinter.unpythonic.net/wiki/mtTkinter


Is there a reason you want (or think you need) one event loop per toplevel window? A single event loop is able to handle dozens (if not hundreds or thousands) of toplevel windows. And, as has been pointed out in another answer, you can't run this event loop in a separate thread.

So, to fix your code you need to only use a single event loop, and have that run in the main thread.