Threaded Tkinter script crashes when creating the second Toplevel widget

后端 未结 3 754
深忆病人
深忆病人 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:17

    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.

    0 讨论(0)
  • 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;-).

    0 讨论(0)
  • 2020-11-28 14:42

    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

    0 讨论(0)
提交回复
热议问题