如何使用python 3.8取消tkinter中关闭延迟定时器的after方法



我有一个关闭延迟程序,当我选择输入检查按钮时,输出为1。当我取消选择输入检查按钮时,输出会在计时器(按比例设置(后返回到0。为此,我使用after方法。这部分有效。我的问题是,如果在输出为0之前再次选择复选按钮,我想重置计时器;但是,一旦第一次选择了checkbutton,after方法就会被触发,并且不会停止。我试着用after_cancel,但我不能用它。有什么解决方案吗?

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()

预期:在输出为0之前按下check按钮时,重置计数器。

因此,当checkbutton的值为1:时,您可以使用.after_cencel

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()

最新更新