tkinter + threads

Timothy Docker timd at macquarie.com.au
Tue Jan 2 23:02:47 EST 2001


I've trolled deja for a definitive answer, but couldn't see one.

I have a Tkinter application which presently uses createfilehandler
on unix. I need to move it to win32, where of course, this function
doesn't exist. Ideally I'd like a non-polled solution, where a
background thread can notify the mainloop thread of updates to be
performed. Unfortunably the best I can com up with is shown
below.

This works both on win32 and unix, but I'm not happy with the
tradeoff between response time and cpu load.

Is there any means by which a background thread can notify the
tkinter mainloop? This is possible in wxpython with the PostEvent
method, which I have used in the past.

Thanks,

Tim

----------------------------------------------------------------------



from Tkinter import *
import thread, sys, time

class Slot:
    def __init__(self):
        self.val = None
        self.lock = thread.allocate_lock()

    def get(self):
        try:
            self.lock.acquire()
            v = self.val
            self.val = None
            return v
        finally:
            self.lock.release()

    def put(self, v):
        try:
            self.lock.acquire()
            self.val = v
        finally:
            self.lock.release()
        
slot = Slot()

def calcThread():
    from random import random
    while 1:
        x = random()
        slot.put ( '%0.4f' % x )
        time.sleep(0.333)

def getQueue():
    b = slot.get()
    if b != None:
        label.config(text=b)
    button.after( 100, getQueue )
    
button = Button(text="Exit",command=sys.exit)
button.after( 100, getQueue )
button.pack()
label = Label(text="________________")
label.pack()

thread.start_new_thread( calcThread, () )
button.mainloop()




More information about the Python-list mailing list