[Tkinter-discuss] Stumped

Cam camfarnell at cogeco.ca
Tue Nov 28 18:39:14 CET 2006


This is probably really simple but I haven't yet figured it out. It 
happens in the context of a much larger program but stripped to it's 
essence is per the little program below.

The general idea is that the user clicks on a button, that initiates an 
operation which is going to take some time, so I would like to allow the 
user to press ESCAPE to cancel the operation. In the code below the 
"on_button" function is the one that takes some time, but if the user 
presses ESCAPE while it is running, the escape isn't processed until 
*after* the "on_button" function returns which sort of defeats the 
purpose. I've tried inserting update_idletasks() into the function and 
various other things without success.

Any suggestions? I'm running Python 2.4.2 under Linux.

Thanks

Cam Farnell

- - - - -

from Tkinter import *
import time

def on_button():
     for J in range(10):
         print J
         if CancelNow:
             break
         time.sleep(1)

def Cancel(Event):
     print 'Cancelling now'
     CancelNow = True
     Root.quit()

Root = Tk()
Root.bind_all('<Key-Escape>',Cancel)

B = Button(Root,command=on_button,text='Go')
B.pack()
CancelNow = False

Root.mainloop()



More information about the Tkinter-discuss mailing list