为什么 Tkinter 不显示我的秒表递增?

Why doesn't Tkinter show my stopwatch incrementing?

我已经成功地制作了一个输出(如 print() )秒表时间从 0 到 5 秒的函数。

当您单击按钮 'start' 时,我想使用 Tkinter 在条目 window 中显示秒表输出。出于某种原因,当您单击开始时,它只加载 5 秒,然后仅显示最后的输出(5.0 秒)。

为什么它不显示从 0.0 - 5.0 秒动态变化的输出?我在此处附上代码 - 我无法弄清楚为什么这不起作用...

from tkinter import *
import time

win = Tk()  # creating a window instance
win.title('stopwach')

def start_timer():
    """begin timer from 1-5"""
    start_time = time.time()
    stopwatch=0 # initializing
    while stopwatch <= 5:
        current_time = time.time()
        stopwatch = current_time - start_time
        entry_field.delete(0, END)
        entry_field.insert(0, str(format(stopwatch, ".1f")) + " sec")
        time.sleep(0.01)
    

entry_field = Entry(win, width=35, borderwidth=5)
entry_field.pack()

message_1 = Label(win, text='5 second stopwatch')
message_1.pack()

button_1 = Button(win, text='START', command=start_timer)
button_1.pack()


win.mainloop()

您不能将 time.sleep 与 tkinter 一起使用,因为它会阻塞 GUI 直到它完成。对于 tkinter,你应该使用 root.after,像这样:

def start_timer():
    """begin timer from 1-5"""
    global start_time, stopwatch
    start_time = time.time()
    stopwatch=0 # initializing
    tick_timer()

def tick_timer():
    global start_time, stopwatch
    if stopwatch <= 5:
        current_time = time.time()
        stopwatch = current_time - start_time
        entry_field.delete(0, END)
        entry_field.insert(0, "%.1f" % stopwatch + " sec")
        win.after(100, tick_timer) #Wait 100ms then run again

这将计时器分成两个函数。 start_timer 初始化变量然后调用 tick_timer。这和以前一样,但最后我使用 win.after 而不是 time.sleep 在 100 毫秒后再次调用 tick_timer 函数。然后这会按预期工作。