How can I schedule updates (f/e, to update a clock) in tkinter?
Tkinter root windows have a method called after
which can be used to schedule a function to be called after a given period of time. If that function itself calls after
you've set up an automatically recurring event.
Here is a working example:
# for python 3.x use 'tkinter' rather than 'Tkinter'import Tkinter as tkimport timeclass App(): def __init__(self): self.root = tk.Tk() self.label = tk.Label(text="") self.label.pack() self.update_clock() self.root.mainloop() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.root.after(1000, self.update_clock)app=App()
Bear in mind that after
doesn't guarantee the function will run exactly on time. It only schedules the job to be run after a given amount of time. It the app is busy there may be a delay before it is called since Tkinter is single-threaded. The delay is typically measured in microseconds.
Python3 clock example using the frame.after() rather than the top level application. Also shows updating the label with a StringVar()
#!/usr/bin/env python3# Display UTC.# started with https://docs.python.org/3.4/library/tkinter.html#module-tkinterimport tkinter as tkimport timedef current_iso8601(): """Get current date and time in ISO8601""" # https://en.wikipedia.org/wiki/ISO_8601 # https://xkcd.com/1179/ return time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.now = tk.StringVar() self.time = tk.Label(self, font=('Helvetica', 24)) self.time.pack(side="top") self.time["textvariable"] = self.now self.QUIT = tk.Button(self, text="QUIT", fg="red", command=root.destroy) self.QUIT.pack(side="bottom") # initial time display self.onUpdate() def onUpdate(self): # update displayed time self.now.set(current_iso8601()) # schedule timer to call myself after 1 second self.after(1000, self.onUpdate)root = tk.Tk()app = Application(master=root)root.mainloop()
from tkinter import *import timetk=Tk()def clock(): t=time.strftime('%I:%M:%S',time.localtime()) if t!='': label1.config(text=t,font='times 25') tk.after(100,clock)label1=Label(tk,justify='center')label1.pack()clock()tk.mainloop()