fernando
fernando

Reputation: 99

how to cancel the after method for an off delay timer in tkinter using python 3.8

I have a off delay program in which when I select the input checkbutton, the output is 1. When I deselect the input checkbutton, the output goes back to 0 after a timer (set up in a scale). For that I use the after method. That part works. My problem is that I want to reset the timer if the checkbutton is selected again before the output went to 0; but once the checkbutton is selected the first time, the after method get triggered and it doesn't stop. I'm trying to use after_cancel, but I can't get it to work. Any solution?

from tkinter import *
root = Tk()

t1= IntVar()
out = Label(root, text="0")
remain_time = IntVar()
grab_time = 1000

def start_timer(set_time):
    global grab_time
    grab_time = int(set_time) * 1000

def play():
    if t1.get() == 1:
        button1.configure(bg='red')
        out.configure(bg="red", text="1")
    else:
        button1.configure(bg='green')
        def result():
            out.configure(bg="green", text="0")
        out.after(grab_time,result)

button1 = Checkbutton(root,variable=t1, textvariable=t1, command=play)
time = Scale(root, from_=1, to=10, command=start_timer)

button1.pack()
time.pack()
out.pack()

root.mainloop()

Upvotes: 1

Views: 148

Answers (1)

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

Expected: when press the checkbutton before the output went to 0, reset the counter.

So you could use the .after_cencel when the value of checkbutton is 1:

from tkinter import *
root = Tk()

t1= IntVar()
out = Label(root, text="0")
remain_time = IntVar()
grab_time = 1000

def start_timer(set_time):
    global grab_time
    grab_time = int(set_time) * 1000

def play():
    if t1.get() == 1:
        button1.configure(bg='red')
        out.configure(bg="red", text="1")
        try: # when the first time you start the counter, root.counter didn't exist, use a try..except to catch it.
            root.after_cancel(root.counter)
        except :
            pass
    else:
        button1.configure(bg='green')
        def result():
            out.configure(bg="green", text="0")
        root.counter = out.after(grab_time,result)

button1 = Checkbutton(root,variable=t1, textvariable=t1, command=play)
time = Scale(root, from_=1, to=10, command=start_timer)

button1.pack()
time.pack()
out.pack()

root.mainloop()

Upvotes: 2

Related Questions