Robin Andrews
Robin Andrews

Reputation: 3794

Tkinter root.after_cancel

I want to stop my recursive timer. Using tick as the argument to after_cancel doesn't work. Using "after#2" does, if I happen to press Return at the right time.

What am I missing here please?

from Tkinter import *   
root = Tk()             

root.title("Tick")     
root.geometry("320x400")   

def tick():                
    print ("tick!")        
    print root.after(1000, tick)

def key_pressed(event):
    if event.keysym == "Return":
        root.after_cancel(tick)

root.bind("<Key>", key_pressed)
root.after(1000, tick)   
mainloop()

Upvotes: 0

Views: 3609

Answers (1)

Pythonista
Pythonista

Reputation: 11635

You need to pass the after reference. Here's a quick edit to show that.

from tkinter import *   
root = Tk()             

root.title("Tick")     
root.geometry("320x400")   

AFTER = None
def tick():                
    print ("tick!")        
    global AFTER
    AFTER = root.after(1000, tick)

def key_pressed(event):
    if event.keysym == "Return":
        root.after_cancel(AFTER)

root.bind("<Key>", key_pressed)
root.after(1000, tick)   
mainloop()

Upvotes: 1

Related Questions