Monday, July 1, 2013

Updating Tkinter applications at an interval - Clock demo

Python version: 2.7.5
Tkinter version: 8.5.2

 Tkinter includes a method after() that provides the ability to call a method after a certain amount of time.  Here is a simple demo of how to use that method to update a clock.  The delay variable in after is in mili-seconds (1/100 th second).  By updating every 50 I am able to show the clock down the the second with relative precision.

from ttk import Frame, Label
from Tkinter import StringVar
from time import strftime

class Clock(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Simple Clock")
        self.pack()

        self.time = StringVar()

        Label(self, textvariable=self.time, width=30).pack(padx=10, pady=15)

        self.update_time()

    def update_time(self):
        self.time.set(strftime('%m/%d/%Y - %H:%M:%S'))
        self.after(50, self.update_time)

if __name__ == '__main__':
    Clock().mainloop()

No comments:

Post a Comment