首页 > 解决方案 > 暂停按钮不起作用,如何正确使用 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)

标签: pythontkinter

解决方案


大多数时候.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 timerStateis FalsethetimerLabel.after(1, countdown)将永远不会被调用,所以没有意义.after_cancel

注意:您没有考虑其他代码所花费的时间,因此t实际上并不是以毫秒为单位(至少对于我的慢速计算机而言)。


推荐阅读