首页 > 解决方案 > 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用于其他项目。

标签: pythonpython-3.xtkinterlag

解决方案


您正在连续创建被黑色矩形覆盖的文本小部件,而无需删除它们 - 实质上,每一秒,您都会在之前的所有画布项目之上再堆积两个画布项目!

正确的做法是将tkinter.mainlooptkinter.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()

推荐阅读