首页 > 解决方案 > 为什么 Tkinter 不显示我的秒表递增?

问题描述

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

当您单击“开始”按钮时,我想使用 Tkinter 在输入窗口中显示秒表输出。出于某种原因,当您单击开始时,它只加载 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()

标签: user-interfacetkinterwhile-looptimer

解决方案


您不能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而不是在 100 毫秒后再次time.sleep调用该函数。tick_timer然后按预期工作。


推荐阅读