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

Thomas Lane tom at
Tue Mar 14 23:11:04 CET 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.



from Tkinter import *
import time

class counter:

    def __init__(self,app): = app
        self.stopped = 0                            # flag indicating stopped
        self.count = IntVar()
        self.entry = Entry(,textvariable=self.count)
        self.pbstop = Button(,text='Stop',command=self.stop)
        # start counter loop after 1/4 second delay,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
               # update the screen
            time.sleep(.25)                         # 1/4 second pause

app = Tk()
mainwindow = counter( app )

More information about the Python-list mailing list