Tkinter - how to catch button clicks when app is busy?

Thomas Lane tom at parlant.com
Tue Mar 14 17:11:04 EST 2000


I have written a small test application that loops, incrementing a counter and
displaying it to a window. I want to be able to interrupt the counter by
clicking a button. I realize I can do this by running the counter in a separate
thread, but I want to be able to do this in a single thread. I want this program
to be able to run on a Mac, and my understanding is that Mac OS does not support
threads, thus the need for a single thread. Is this possible?

The source for my test application is below. It creates the widgets on the
screen and starts the timer loop. Inside the loop it increments the count, calls
update_idletasks() to refresh the screen, and sleeps briefly. Once the loop is
started the window does not respond to mouse commands. The only way to stop the
counter is to forcibly terminate the application. 

If anyone can help me out here, I'd be very appreciative.

-Tom

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

from Tkinter import *
import time

class counter:

    def __init__(self,app):
        self.app = app
        self.stopped = 0                            # flag indicating stopped
        self.count = IntVar()
        self.count.set(0)
        self.entry = Entry(self.app,textvariable=self.count)
        self.pbstop = Button(self.app,text='Stop',command=self.stop)
        self.entry.grid()
        self.pbstop.grid()
        # start counter loop after 1/4 second delay
        self.app.after(250,self.countloop)

    def stop(self):
        self.stopped = 1

    def countloop(self):
        # continue the counter loop until the stopped flag is set
        while self.stopped == 0:
            self.count.set( self.count.get() + 1 )  # increment counter
            self.app.update_idletasks()             # update the screen
            time.sleep(.25)                         # 1/4 second pause

app = Tk()
mainwindow = counter( app )
app.mainloop()



More information about the Python-list mailing list