Tkinter and asyncronous socket

Eric Brunel see.signature at no.spam
Thu Nov 27 11:43:28 EST 2008


On Fri, 28 Nov 2008 04:20:22 +0100, Hendrik van Rooyen  
<mail at microcorp.co.za> wrote:
> If you are not already doing it, you need to make a "stutter thread"
> by using the after() call on some gui object to periodically check for
> input on the queue.

You don't need to in fact: from the secondary thread, it seems to be safe  
to post a user-defined event in the GUI event loop on which you can set a  
binding in the GUI thread. This allows a thread switch without having to  
do a periodical check.

Here is an example:

------------------------------------
import time
 from threading import Thread
 from Tkinter import *

root = Tk()

v = IntVar()
v.set(0)

Label(root, width=8, textvariable=v).pack()

def incr_counter(event=None):
   v.set(v.get() + 1)

root.bind('<<heartbeat>>', incr_counter)

def heartbeat():
   while 1:
     time.sleep(1)
     root.event_generate('<<heartbeat>>', when='tail')

th = Thread(None, heartbeat)
th.setDaemon(True)
th.start()

root.mainloop()
------------------------------------

The custom event '<<heartbeat>>' is posted in the event loop from the  
secondary thread. Note the when='tail' option, which is absolutely  
necessary or the binding might be called immediatly without even an actual  
event posting. The binding on this event will then be executed in the  
thread that launched the mainloop.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"



More information about the Python-list mailing list