我是 Python 的初学者,我正在尝试在 tkinter 中创建一个计时器。我想要一个可以停止计时器的按钮,但是我似乎无法弄清楚如何做到这一点。我曾尝试研究线程和类,但是对于像计时器这样简单的任务,我需要这些复杂的概念吗?import tkinter as tkfrom tkinter import *def countdown(count): # change text in label label['text'] = count if count > 0: # call countdown again after 1000ms (1s) root.after(1000, countdown, count-1)def stop(): # THIS IS THE FUNCTION I WANT TO USE TO STOP THE TIMER, HOWEVER I DO NOT KNOW HOW, RIGHT NOT I HAVE JUST PUT exit() WHICH QUITS THE WHOLE PROGRAM countdown(exit())root = tk.Tk()root.geometry('600x600-200-0')label = tk.Label(root)label.place(x=35, y=15)# call countdown first timecountdown(10)# root.after(0, countdown, 5)# Button, pressing it leads to greeting commandbutton = Button(text="OK", command=stop)button.pack()root.mainloop()我只是想知道这个问题是否有一个简单的解决方案,因为当我研究所有 tkinter 停止计时器时都有如此复杂的代码。先感谢您!
1 回答
繁星点点滴滴
TA贡献1803条经验 获得超3个赞
您只需要在某个地方存储after()函数中的作业编号。
job = None
def countdown(count):
# change text in label
label['text'] = count
if count > 0:
global job
# call countdown again after 1000ms (1s)
job = root.after(1000, countdown, count-1)
def stop():
global job
if job:
root.after_cancel(job)
job = None
添加回答
举报
0/150
提交
取消