2016-03-29 96 views
-4

我想用Tkinter和时间库创建实时时钟。我创建了一个班,但不知何故我无法弄清楚我的问题。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() 
+0

你应该提供你得到的堆栈跟踪,或描述你面临的问题。 –

+0

你有错误信息吗?你可以发布它吗? –

回答

2

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

还要注意的是:

回调只为每次调用此方法调用一次。要保持 呼叫回拨,您需要重新注册 本身内的回叫。