简体   繁体   English

Tkinter 滞后于“更新”命令

[英]Tkinter lag at the "update" command

I made a timer just to test something out.我做了一个计时器只是为了测试一些东西。 and for some reason it starts lagging, here is the timer:由于某种原因它开始滞后,这是计时器:

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)

Can someone figure out where it happens?有人能弄清楚它发生在哪里吗? I noticed I can run the timer without tkinter and just with print , but I need to use tkinter for other projects too.我注意到我可以在没有tkinter的情况下运行计时器,而只需使用print ,但我也需要将tkinter用于其他项目。

You are creating text widgets covered by black rectangles in succession, without ever removing them - in essence, every second, you are piling two more canvas items on top of all the previous ones!您正在连续创建被黑色矩形覆盖的文本小部件,而没有删除它们 - 实际上,每一秒,您都在之前的所有项目之上再堆放两个 canvas 项目!

The correct approach is to use the tkinter.mainloop in conjunction with the tkinter.after method, and steer clear from using a while loop, and tkinter.update .正确的方法是将tkinter.mainlooptkinter.after方法结合使用,并避免使用 while 循环和tkinter.update You can change the text displayed by a canvas text item using itemconfigure .您可以使用itemconfigure更改 canvas 文本项显示的文本。

The use of time.sleep in a GUI is a recipe to have your GUI stop responding to interactions - don't do that!在 GUI 中使用time.sleep是让你的 GUI 停止响应交互的方法 - 不要那样做!

Maybe do this instead:也许这样做:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM