python - 暂停按钮不起作用,如何正确使用 after_cancel?
问题描述
所以我正在制作一个有定时器的程序并且定时器工作,现在我正在使用暂停功能。经过一番研究,我发现了一个名为 after_cancel 的函数。这个函数应该取消后函数,因为在这种情况下后函数会创建一个无限循环。在这种情况下如何正确使用 after_cancel 或者是否有其他可能的解决方案?
提前致谢。
t = 60000
global timerState
timerState = True
def pause():
timerLabel.after_cancel(countdown)
timerState = False
timerButton.config(text="Play", command=countdown)
def countdown():
global t
if t == 0:
timer = "00:00"
timerLabel.config(text=timer)
return
if timerState == False:
timerLabel.after_cancel(countdown)
timerButton.config(text="Play", command=countdown)
return
mins = t / 60000
secs = t / 1000
secs = secs - int(mins) * 60
mills = t
mills = mills - int(secs) * 1000
if timerState == True:
timer = "{:02d}:{:02d}".format(int(mins),int(secs))
timerLabel.config(text=timer)
t -= 1
timerLabel.after(1, countdown)
timerButton.config(text="Pause", command=pause)
解决方案
大多数时候.after_cancel
脚本可以通过使用if
语句来避免。例如看这个:
import tkinter as tk
t = 60000
def pause():
global timerState
timerState = False
timerButton.config(text="Play", command=start_countdown)
def start_countdown():
global timerState
timerState = True
timerButton.config(text="Pause", command=pause)
countdown()
def countdown():
global t
if timerState:
timerLabel.config(text=t)
t -= 1
if t > 0:
timerLabel.after(1, countdown)
root = tk.Tk()
timerLabel = tk.Label(root, text="")
timerLabel.pack()
timerButton = tk.Button(root, text="Play", command=start_countdown)
timerButton.pack()
root.mainloop()
我修改了您的代码以显示t
而不以mm:ss
格式显示。要点是 if timerState
is False
thetimerLabel.after(1, countdown)
将永远不会被调用,所以没有意义.after_cancel
。
注意:您没有考虑其他代码所花费的时间,因此t
实际上并不是以毫秒为单位(至少对于我的慢速计算机而言)。
推荐阅读
- python-3.x - 字典的元组到元组python的列表
- c# - 正确衡量流程执行
- node.js - 响应拦截器的CatchError函数多次执行 - Angular 6
- swift - 通过 DJI iOS SDK 访问 DJI Osmo Pocket 上的相机
- javascript - 传递带有其他数据参数的序列化表单
- typescript - 如果类显式扩展 Object,为什么不能调用方法?
- python - timedelta.seconds 返回错误值
- android - 如何使Android应用程序登录请求全部显示为一个IP
- mysql - 特定产品的时差
- angular - “功能”类型上不存在属性“功能”
'