import tkinter as tk
import time
import threading
class Timer(threading.Thread):
"""
See https://docs.python.org/3/library/threading.html for
differences between this class and threading.Timer:
This class runs periodically every dt seconds until the
program is terminated or a RuntimeError occurs.
threading.Timer runs only once.
"""
def __init__(self, dt,method):
"""
initializes the Timer object with the time interval dt
and a handle to the method to run().
"""
threading.Thread.__init__(self)
self.waiting = dt
self.execute = method
def run(self):
while True:
try:
time.sleep(self.waiting)
self.execute()
except RuntimeError:
return
class App(tk.Frame):
"""
see https://docs.python.org/3/library/tkinter.html
"""
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.createWidgets()
self.pack()
self.timer = Timer(1.0, self.updateWidgets)
self.timer.start()
def createWidgets(self):
"""
see http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/control-variables.html
for details about using so-called control variables:
They let you auto-update a widget text if the variable
gets updated.
"""
self.timeVar = tk.StringVar()
self.timeVar.set("hh:mm:ss")
self.time = tk.Label(self, textvariable=self.timeVar)
self.time.pack()
self.hexTVar = tk.StringVar()
self.hexTVar.set("#rrggbb")
self.hext = tk.Label(self, textvariable=self.hexTVar)
self.hext.pack()
def updateWidgets(self):
"""
This method is called periodically by our timer.
See https://docs.python.org/3/library/time.html#time.strftime
for details about formatting time "bits".
"""
self.timeVal = time.gmtime()
self.timeVar.set(time.strftime('%H:%M:%S', self.timeVal))
hextime = time.strftime('#%H%M%S', self.timeVal)
self.hexTVar.set(hextime)
self.master['bg'] = hextime
wnd = tk.Tk()
app = App(wnd)
wnd.geometry('300x200')
app.mainloop()