且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Tkinter 中的实时时钟显示

更新时间:2022-02-25 23:20:41

after() 应该是一个 function - 当你给出 any 时 - 但你给出的是一个 str 对象.因此,您收到错误消息.

Second parameter of after() should be a function -when you are giving any- but you are giving a str object. Hence you are getting an error.

from tkinter import *    
import time

root = Tk()

class Clock:
    def __init__(self):
        self.time1 = ''
        self.time2 = time.strftime('%H:%M:%S')
        self.mFrame = Frame()
        self.mFrame.pack(side=TOP,expand=YES,fill=X)

        self.watch = Label(self.mFrame, text=self.time2, font=('times',12,'bold'))
        self.watch.pack()

        self.changeLabel() #first call it manually

    def changeLabel(self): 
        self.time2 = time.strftime('%H:%M:%S')
        self.watch.configure(text=self.time2)
        self.mFrame.after(200, self.changeLabel) #it'll call itself continuously

obj1 = Clock()
root.mainloop()

还要注意:

每次调用此方法只调用一次回调.保持调用回调,需要在里面重新注册回调自己.

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself.