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;-).

Leave a Comment