简体   繁体   English

Tkinter 如何持续更新一个 label

[英]Tkinter how to continuously update a label

I am trying to create a clock in tkinter and I am attempting to update a label whenever the time changes however, I have no idea how to do this.我正在尝试在 tkinter 中创建一个时钟,并且我正在尝试在时间更改时更新 label 但是,我不知道该怎么做。 I have tried the after method however I believe I am doing something wrong.我尝试了 after 方法,但是我相信我做错了什么。

My code:我的代码:

from tkinter import *
import time
from datetime import date
from datetime import datetime
date = date.today()
now = datetime.now()
time = now.strftime("%H:%M:%S")

root = Tk()
root.title("Clock")
root.geometry("500x500")
Time = Label(root, text = f"{time}", font = ("Times New Roman", 50))
Time.place(x = "160", y = "100")
def Update():
    Time.config(text = f"{time}")
    
root.after(1000, Update())

root.mainloop()

Does anyone know what I am doing wrong?有谁知道我做错了什么?

First of all, root.after takes a function, not the result of a function:首先, root.after采用 function,而不是 function 的结果:

root.after(1000, Update)

Secondly, you need some way to make the update happen every second, rather than just once.其次,您需要某种方法来使更新每秒发生一次,而不仅仅是一次。 The easiest way is to add a root.after call to your Update function, as well as calculating the new time string each time the function is called:最简单的方法是在Update function 中添加root.after调用,并在每次调用 function 时计算新的时间字符串:

def Update():
    now = datetime.now()
    time = now.strftime("%H:%M:%S")
    Time.config(text = f"{time}")
    root.after(1000, Update)

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

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