.after() 函数不会让秒表等待

.after() function doesn't make stopwatch wait

我想在 python 中创建一个秒表。我曾尝试使用 time.sleep 让程序等待一秒钟,以便它能正常工作,但它没有工作,按钮(因为它是一个在 tkinter 中制作的 GUI 应用程序)一直在工作。所以我使用了 .after 功能,但应用程序现在也无法运行,当我尝试关闭程序时它没有回答。

我已尽力修复此问题,但我是 python 的新手,我找不到问题所在。

def stop_app():
    global stop
    stop = 1


def start():
    global series, minutes,seconds

    minutes=25,
    seconds=60
    print(minutes, seconds)
    while True :
        if series==4:
            break
        seconds -=1
        print (seconds, minutes)

        if minutes == 00 and seconds ==00:
            #dzwięk
            minutes = 4
            seconds=59
            series +=1

        if seconds ==00:
            minutes-=1
            seconds = 60
            print (seconds, minutes, seria)

        clock = tk.Label(root, height=1, background="#000000", foreground='white',
                         font=("Lemon Milk", 70), anchor=CENTER, text="00:00:00")
        clock.place(x=120, y=90)
        clock.after(1000,start)

我真的不明白你的代码正在做或想做的几件事,但下面是基于它的一些东西,它展示了如何使用通用小部件在 tkinter 中做一个计时器的本质 after() 方法.

一般来说,它取代了 显式循环,例如您正在使用的while True:。它所做的是在指定的延迟后安排对同一函数的另一个调用。停止“循环”很容易,只是在返回之前不要再次调用 after()

另一个需要注意的重要事项是用于显示时间的 Label 仅创建 一次 并且每次 start() 执行时更新。

import tkinter as tk
from tkinter.constants import *


def start():
    global hours, minutes, seconds

    if hours == 4:
        return  # Stop timer.

    seconds -= 1

    if seconds == 00:
        minutes -= 1
        seconds = 60

    if minutes == 00 and seconds == 00:
        hours += 1

    clock.config(text=f'{hours:02}:{minutes:02}:{seconds:02}')

    root.after(1000, start)  # Call again in 1 second (1000 ms).


root = tk.Tk()
clock = tk.Label(root, height=1, background="#000000", foreground='white',
                 font=("Lemon Milk", 20), anchor=CENTER, text="00:00:00")
clock.place(relx=0.5, rely=0.5, anchor=CENTER)
hours, minutes, seconds = 0, 25, 60  # Initialize global variables.
start()
root.mainloop()