暂停按钮不起作用,取消后如何正确使用?

db2dz4w8  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(304)

所以我正在制作一个有定时器的程序,定时器工作,现在我正在使用暂停功能。经过一些研究,我发现了一个在取消后调用的函数。这个函数应该取消after函数,因为在这种情况下,after函数会创建一个无限循环。在这种情况下,我如何正确使用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)
yh2wf1be

yh2wf1be1#

大多数时候 .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 格式。要点是如果 timerStateFalse 这个 timerLabel.after(1, countdown) 将永远不会被调用,因此没有必要使用 .after_cancel .
注意:您没有考虑其他代码所用的时间,所以 t 并不是以毫秒为单位(至少对于我的速度较慢的计算机而言)。

z4bn682m

z4bn682m2#

下面是一个演示 afterafter_cancel 每一个 after 需要取消以清除事件队列。
在该程序中,每次按下按钮都会生成一个延时事件。事件id存储在 self.after_time 为了演示,我将延迟值设置为每按一次按钮增加100毫秒。它从视图中撤回主控形状。
当时间延迟事件完成时,它调用
self.action self.action 使用取消事件 after_cancel( self.after_time ) 主屏幕显示,为下一次按钮按下做好准备。

import tkinter

class after_demo:

    delay = 100

    def __init__( self ):

        self.master = tkinter.Tk()
        self.master.title( 'After Demo' )
        self.control = tkinter.Button(
            self.master, text = 'Begin Demo',
            width = 40, command = self.pause )
        self.control.grid(row=0,column=0,sticky='nsew')

    def action( self ):

        self.master.after_cancel( self.after_time )
        self.control[ 'text' ] = 'Delay( {} ) ms'.format( self.delay )

        self.master.deiconify()

    def pause( self ):

        self.after_time = self.master.after( self.delay, self.action )
        self.delay += 100

        self.master.withdraw()

if __name__ == '__main__':

    timer = after_demo( )
    tkinter.mainloop()

相关问题