猿问

如何在函数后停止 tkinter

我是 Python 的初学者,我正在尝试在 tkinter 中创建一个计时器。我想要一个可以停止计时器的按钮,但是我似乎无法弄清楚如何做到这一点。我曾尝试研究线程和类,但是对于像计时器这样简单的任务,我需要这些复杂的概念吗?


import tkinter as tk

from 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 time

countdown(10)

# root.after(0, countdown, 5)


# Button, pressing it leads to greeting command

button = Button(text="OK", command=stop)

button.pack()


root.mainloop()

我只是想知道这个问题是否有一个简单的解决方案,因为当我研究所有 tkinter 停止计时器时都有如此复杂的代码。先感谢您!


偶然的你
浏览 127回答 1
1回答

繁星点点滴滴

您只需要在某个地方存储after()函数中的作业编号。job = Nonedef 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
随时随地看视频慕课网APP

相关分类

Python
我要回答