【问题标题】:Real time clock display in TkinterTkinter 中的实时时钟显示
【发布时间】:2016-03-29 08:36:30
【问题描述】:

我想使用 Tkinter 和时间库创建实时时钟。我创建了一个类,但不知何故我无法弄清楚我的问题。

我的代码

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.watch.after(200,self.time2)

obj1 = Clock()
root.mainloop()

【问题讨论】:

  • 你应该提供你得到的堆栈跟踪,或者描述你面临的问题。
  • 您是否收到错误消息?请问可以发一下吗?

标签: python tkinter


【解决方案1】:

after() 的第二个参数应该是 function - 当你给任何 - 但你给的是一个 str 对象。因此你得到一个错误。

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

还要注意:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 2019-12-19
    • 2020-01-17
    相关资源
    最近更新 更多