user-interface - 为什么 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()
解决方案
您不能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
然后按预期工作。
推荐阅读
- javascript - 我的 Vue Js 应用程序会在每个文档更改时刷新
- c# - 如何避免在 csproj 中使用新的 PackageReference xml 标签复制引用的程序集
- php - laravel 引导方法在模型中不起作用
- powerapps - 如果 Power Apps 中的 json 中存在整数值,我无法将 json 绑定到集合
- javascript - 使用 javascript 或 jquery 以 html 形式上传默认图像
- python - Python:列表中的用户输入与第二个列表中的索引对齐,输出第二个列表元素
- python - 编写一个名为 ten-sum-even.py 的 Python 脚本,它只输出遇到的偶数之和
- python - 将字典列表中的字典值替换为另一个字典列表中的值
- npm - VSCode 在 package.json 中显示错误的 npm 包信息
- python - maketrans前面字符串的用途