Threaded Tkinter script crashes when creating the second Toplevel widget

后端 未结 3 765
深忆病人
深忆病人 2020-11-28 14:00

I have a Python script which uses Tkinter for the GUI. My little script should create a Toplevel widget every X seconds. When I run my code, the first Toplevel widget is cre

3条回答
  •  孤街浪徒
    2020-11-28 14:41

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

提交回复
热议问题