python - Tkinter 滞后于“更新”命令
问题描述
我做了一个计时器只是为了测试一些东西。由于某种原因它开始滞后,这是计时器:
from tkinter import *
from time import sleep
main = Tk()
main.title("Timer")
c = Canvas(main,width=1000,height=400)
c.pack()
c.config(bg="black")
hours = -1
while True:
hours += 1
for minutes in range(60):
for seconds in range(60):
c.create_rectangle(0,0,1000,400,fill="black")
c.create_text(500,200,text=(str(hours)+":"+str(minutes)+":"+str(seconds)),font=("",200),fill="white")
c.update()
sleep(1)
有人能弄清楚它发生在哪里吗?我注意到我可以在没有tkinter
和仅使用的情况下运行计时器print
,但我也需要tkinter
用于其他项目。
解决方案
您正在连续创建被黑色矩形覆盖的文本小部件,而无需删除它们 - 实质上,每一秒,您都会在之前的所有画布项目之上再堆积两个画布项目!
正确的做法是将tkinter.mainloop
与tkinter.after
方法结合使用,并避免使用 while 循环和tkinter.update
. 您可以使用 更改画布文本项显示的文本itemconfigure
。
在 GUI 中使用time.sleep
是让您的 GUI 停止响应交互的秘诀——不要那样做!
也许这样做:
import tkinter as tk
def update_clock():
clock_text = f'{hours}:{str(minutes).zfill(2)}:{str(seconds).zfill(2)}'
canvas.itemconfigure(clock, text=clock_text)
main.after(1000, _increment_time)
def _increment_time():
global clock, hours, minutes, seconds
seconds += 1
if seconds == 60:
seconds = 0
minutes += 1
if minutes == 60:
minutes = 0
hours += 1
update_clock()
main = tk.Tk()
main.title('Timer')
canvas = tk.Canvas(main, width=1000, height=400, bg='black')
canvas.pack()
hours, minutes, seconds = 0, 0, 0
clock = canvas.create_text(500, 200, font=('', 200), fill='white')
update_clock()
main.mainloop()
推荐阅读
- mongodb - 合并数组元素和去重Mongodb聚合
- java - NoClassDefFoundError - 动态加载 URLClassLoader 中加载的 Classpath 类依赖项
- html - 背景图片不显示,链接正常,选择器正常,有没有我没有意识到的干扰?
- ios - iOS 如何在广播上传扩展中实现开放主机应用程序?
- arrays - 如何在 Google 工作表中为 importhtml 转置这些数据
- java - spring boot 无法连接非主数据库
- javascript - 当我击中拇指不完全在中心时,使输入范围不跳跃
- sql-server - 根据返回供应商 ID 的子查询获取前 10 个唯一供应商数据
- javascript - 在按键上应用滚动动画与在鼠标单击时相同
- sql-server - 修复迁移数据库上的孤立用户