2016-03-29 91 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() 

還要注意的是:

回調只爲每次調用此方法調用一次。要保持 呼叫回撥,您需要重新註冊 本身內的回叫。