Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

python - Real time clock display in Tkinter

I want to create real time clock using Tkinter and time library. I have created a class but somehow I am not able to figure out my problem.

My code

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Also note that:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...