Python Tkinter: App hangs when changing window title via callback event Python Tkinter: App hangs when changing window title via callback event tkinter tkinter

Python Tkinter: App hangs when changing window title via callback event


I encountered the same problem, where the UI hangs when calling self.title() from a thread other than the main thread. Tkinter expects all UI stuff to be done in the same thread (the main thread).

My solution was to have the separate thread put functions in a queue. The queue is serviced periodically by the main thread, making use of the after(ms) function provided by Tkinter. Here's an example with your code:

import Tkinterimport threadingfrom Queue import Queue, Emptyclass Gui(Tkinter.Tk):    def __init__(self, parent=None):        Tkinter.Tk.__init__(self, parent)        self.ui_queue = Queue()        self._handle_ui_request()        self.title('Original Title')        self.label = Tkinter.Label(self, text='Just a Label.',            width=30, anchor='center')        self.label.grid()        self.bind('<<change_title>>', self.change_title)        timer = threading.Timer(1, self.event_generate, ['<<change_title>>'])        timer.start()    def change_title(self, event=None):        # Separate the function name, it's args and keyword args,         # and put it in the queue as a tuple.        ui_function = (self.title, ('New Title',), {})        self.ui_queue.put(ui_function)    def _handle_ui_request(self):        '''        Periodically services the UI queue to handles UI requests in the main thread.        '''        try:            while True:                f, a, k = self.ui_queue.get_nowait()                f(*a, **k)        except Empty:            pass        self.after(200, self._handle_ui_request)G = Gui(None)G.mainloop()


Well, your code actually runs fine to me.

Except that, when interrupted before the ten secs, it says "RuntimeError: main thread is not in main loop"

I'm using python 2.6.6 under ubuntu 10.10

Hope this was of some help.


I tried it as well with 2.6.2 (Windows) and the caption/title didn't change. No runtime error though.