Tkinter - Multiple Tk() instances/mainloops in one process?

andrew cooke andrew at acooke.org
Wed Mar 25 06:26:34 EDT 2009


i havn't used tkinter for years, and can't remember a thing about it, but
many gui toolkits (not just in python) manage a single event loop and need
care when working with multiple threads.

that doesn't mean that you cannot have multithreaded programs, but does
mean that you do not invoke gui actions from the other threads.  instead,
typically, there is a way for other threads to deposit an "event" for the
gui thread to act on.

see, for example, http://docs.huihoo.com/tkinter/TkinterSummary.html#Hints
where it says:

  All Tkinter access must be from the main thread (or, more
  precisely, the thread that called mainloop). Violating this
  is likely to cause nasty and mysterious symptoms such as
  freezes or core dumps. Yes this makes combining multi-threading
  and Tkinter very difficult. The only fully safe technique I have
  found is polling (e.g. use after from the main loop to poll a
  threading Queue that your thread writes). I have seen it
  suggested that a thread can safely use event_create to
  communicate with the main thread, but have found this is not safe.

andrew


Gregory Sheaffer wrote:
> I've been working on a Python project for several weeks involving a client
> for connecting to an AIM distribution server and holding multiple
> conversations in separate windows.
>
> Without getting into a lot of detail, the basic main program loop is
>
> while(1)
>        on message recieved
>                     if new conversation
>                               create a thread for a new window instance
>                     if old conversation
>                               route to that window for printing
>
> The window instance is a Tkinter GUI class, on a basic level
>         self.root=Tk()
>         *stuff for root*
>         self.root.mainloop()
>
> All the windows involved work fine when tested individually, and when run
> the system handles a single conversation and that window fine (And another
> after the first has been closed). However, if at any time we attempt to
> have
> multiple windows (Which are in separate threads each with their own Tk()
> call) the windows beyond the first fail to appear and tkinter seems to get
> stuck in an infinite loop somewhere in the new mainloop() call.
>
> So, basically, is this a problem inherent in using Tkinter? And if so, are
> there any workarounds besides tying the windows to a root Tk() in the main
> program (Which isn't really an option the way the system is currently
> designed).
> --
> http://mail.python.org/mailman/listinfo/python-list
>





More information about the Python-list mailing list