tk-clock.html
001| """Tk-Clock. Using the Python Tk toolkit.
001|
001| Classes:
001| Application ~implements a Tk application
001| AppSettings ~jcfg.JConfigSettings: app config
001| AppConfigSet ~jcfg.JConfigSettingsSet: app config set
001|
001| Data:
001| AboutText ~str: text for About msgbox
001| <name>Key ~str: settings file parameter names
001| Dflt<name> ~str: default settings parameters
001|
001| Commands:
001| main do_main ~start the Tk GUI app
001| test do_test ~test
001|
001| TODO: Copy image BMP
001| TODO: faster updates but only draw clock when second changes
001| TODO: Other clocks? Watchface?
001| """
002|
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import datetime
007| from math import radians, sin,cos
008| import tkinter as tk
009| import tkinter.ttk as ttk
010| import tkinter.messagebox as msgbox
011| from PIL import Image, ImageDraw, ImageFont, ImageTk
012| from logger import logger,info,debug,trace, LogFilenameTimestamp
013| from goodies import typename, KWARG, makefilename, isreallyafile
014| from dates import CST
015| import jconfig as jcfg
016| import tkutil as util
017|
018| BasePath = r'C:\CJS\prj\Python\app\tk'
019| CnfgPath = path.join(BasePath, 'cfg')
020| DataPath = path.join(BasePath, 'dat')
021| ListPath = path.join(BasePath, 'out')
022| Log = logger('Tk-Clock')
023|
024| CMND = 'main'
025| ARGS = {
026|
027|
028|
029| }
030| bag = {}
031|
032|
033| AboutText = '''\
033| Tk Clock.
033|
033| An old idea about a visual clock
033| brought back to life with the
033| Python Tk and Ttk suite.
033|
033| © CJSonnack November 2025
033| '''
034|
035|
036| '''Keys to settings file parameters (parameter names).'''
037| UltimateKey = 'hitch.hiker'
038|
039| '''Default dictionaries for supplying default parameters.'''
040| DfltUltimate = jcfg.JConfigItem.make_dict(42, "The ultimate answer!", "But what's the question?", 'int')
041|
042|
043| class AppConfigSet (jcfg.JConfigSettingsSet):
044| '''Settings class for Tk-Clock.'''
045|
046| def __init__ (self, name, params, papasan):
047| '''New AppConfigSet instance.'''
048| Log.debug(f'AppConfigSet({name}, {params}, {typename(papasan)})')
049| super().__init__(name, params, papasan)
050|
051| self.ultimate = self.getsetparam(UltimateKey, DfltUltimate)
052|
053|
054| class AppSettings (jcfg.JConfigSettings):
055| '''Configuration class for Tk-Clock.'''
056|
057|
058| NewSetType = AppConfigSet
059|
060| def __init__ (self, **kwargs):
061| '''New AppSettings instance.'''
062| Log.debug(f'AppSettings()')
063| super().__init__(**kwargs)
064|
065|
066|
067| class Application:
068| '''Application class - Implements a Tk application.
068|
068| Attributes:
068| title ~str: window title
068| fpath ~str: path to file to hexdump (or '')
068| fname ~str: name of file to hexdump (may include path)
068| filename ~str: fpath/fname
068| ready ~bool: app ready for clock drawing
068| settings ~AppSettings: configuration object
068| opts ~str: name of settings configuration to use
068| settings_path ~str: path to settings file (or '')
068| settings_name ~str: name of settings file (may include path)
068| root ~Tk: application window root
068| mbar ~Menu: the menubar
068| wndw ~Frame: application window frame
068| main ~Frame: application frame
068| tk_imag ~ImageTk.PhotoImage:
068| statusbar ~Frame: statusbar frame
068| lbl_imag ~Label: canvas for the image
068| imag ~Image:
068| draw ~ImageDraw:
068| fnt1 ~ImageFont:
068| fnt2 ~ImageFont:
068| fnt3 ~ImageFont:
068|
068| Methods:
068| update_clock ~update clock
068| edit_copy ~copy image
068| app_about ~about app
068| app_keypress ~application key handler
068| app_exit ~exit application; destory window(s)
068| '''
069| UpdateDelay = 333
070|
071| def __init__ (self, **kwargs):
072| '''New Application instance.'''
073| self.title = KWARG('title', 'Tk Clock', str, kwargs)
074| self.fpath = KWARG('fpath', BasePath, str, kwargs)
075| self.fname = KWARG('fname', 'untitled.txt', str, kwargs)
076| self.settings_path = KWARG('spath', CnfgPath, str, kwargs)
077| self.settings_name = KWARG('sname', 'tk-clock.cnfg', str, kwargs)
078| self.opts = KWARG('opts' , 'default', str, kwargs)
079| Log.info(f'Tk-Clock:: {str(list(kwargs.keys()))}')
080| Log.debug(f'{self.title=}')
081| Log.debug(f'{self.fpath=}')
082| Log.debug(f'{self.fname=}')
083| Log.debug(f'{self.settings_path=}')
084| Log.debug(f'{self.settings_name=}')
085| Log.debug(f'{self.opts=}')
086| Log.info()
087| self.filename = path.join(self.fpath, self.fname) if self.fpath else self.fname
088| self.ready = False
089|
090| self.settings = jcfg.JConfigSettings(cfg=self.opts, fname=self.settings_name, fpath=self.settings_path)
091| Log.debug(f'settings: {self.settings!r}')
092| Log.debug(f'> current: {self.settings.name}')
093| Log.debug(f'> configs: {self.settings.cnfgkeys}')
094| Log.debug(f'> currcnfg: {self.settings.current!r}')
095| Log.debug(f'> parmkeys: {self.settings.current.paramkeys}')
096| Log.debug(f'> wndwpos: {self.settings.current.xpos:4d}x{self.settings.current.ypos:4d}')
097| Log.debug(f'> wndwdim: {self.settings.current.xdim:4d}x{self.settings.current.ydim:4d}')
098| Log.debug(f'> wndwmin: {self.settings.current.xmin:4d}x{self.settings.current.ymin:4d}')
099| Log.debug(f'> wndwmax: {self.settings.current.xmax:4d}x{self.settings.current.ymax:4d}')
100| Log.debug()
101|
102|
103| self._build()
104|
105| def app_exit (self, *args):
106| '''Exit application; destory window(s).'''
107| Log.debug(f'Exit()')
108|
109| geo = util.TkGeometry.from_string(self.root.wm_geometry())
110| self.settings.current[jcfg.JConfigSettingsPosX].value = geo.xpos
111| self.settings.current[jcfg.JConfigSettingsPosY].value = geo.ypos
112| self.settings.current[jcfg.JConfigSettingsDimX].value = geo.xdim
113| self.settings.current[jcfg.JConfigSettingsDimY].value = geo.ydim
114|
115|
116| fn = makefilename(self.settings_path, self.settings_name)
117| self.settings.save_json_file(fn)
118|
119|
120| self.root.destroy()
121|
122| def update_clock (self):
123| '''Update clock and ask for a callback in 333ms.'''
124| Log.debug('UpdateClock()')
125| if not self.ready:
126| return
127|
128| self._clock_image()
129|
130|
131| self.tk_imag = ImageTk.PhotoImage(self.imag)
132|
133|
134| self.lbl_imag['image'] = self.tk_imag
135|
136|
137| self.root.after(type(self).UpdateDelay, self.update_clock)
138|
139| def _clock_image (self):
140| '''Draw current clock image.'''
141| size_border = 25
142| size_hub = 15
143|
144| radius_secs = 0.33
145| radius_mins = 0.60
146| radius_hrs = 0.75
147| radius_dots = 0.90
148| radius_days = 1.05
149|
150| dt0 = datetime.today()
151| dt1 = dt0
152|
153| dims = (400, 300)
154| bkgd = (255,255,255)
155|
156| fx = lambda x: (int(dims[0] / 2) + x)
157| fy = lambda y: (int(dims[1] / 2) - y)
158| sz = int((dims[1] - 80) / 2)
159|
160|
161| self.imag = Image.new('RGB', dims, bkgd)
162| self.draw = ImageDraw.Draw(self.imag)
163| self.fnt1 = ImageFont.truetype('arialbd.ttf', 24)
164| self.fnt2 = ImageFont.truetype('arial.ttf', 12)
165| self.fnt3 = ImageFont.truetype('ariali.ttf', 12)
166|
167| self.draw.rectangle((0,0)+(dims[0]-1,dims[1]-1), outline=( 0, 0, 0))
168| self.draw.rectangle((1,1)+(dims[0]-2,dims[1]-2), outline=( 63, 63, 63))
169| self.draw.rectangle((2,2)+(dims[0]-3,dims[1]-3), outline=(127,127,127))
170| self.draw.rectangle((3,3)+(dims[0]-4,dims[1]-4), outline=(191,191,191))
171|
172| x1,y1 = size_border, size_border
173| x2 = dims[0]-size_border
174| y2 = dims[1]-size_border
175| self.draw.rectangle([x1,y1, x2,y2], fill=(255,255,191), outline=(0,0,0))
176|
177| self.draw.text((x1+3,y1), "Hello!", font=self.fnt1, fill=(0,0,0))
178|
179| s = dt1.strftime('%A %B %d, %Y %I:%M %p')
180| bb = self.draw.textbbox((0,0), s, font=self.fnt2)
181| x,y = 5, dims[1] - (bb[3]+5)
182| self.draw.text((x,y), s, font=self.fnt2, fill=(0,0,0))
183|
184| s = 'cjsonnack'
185| bb = self.draw.textbbox((0,0), s, font=self.fnt3)
186| x = dims[0] - (bb[2] + 5)
187| y = dims[1] - (bb[3] + 5)
188| self.draw.text((x,y), s, font=self.fnt3, fill=(0,0,0))
189|
190| m = 32
191| d = int(sz * radius_days)
192| x1,x2 = fx(-d), fx(+d)
193| y1,y2 = fy(+d), fy(-d)
194| for a in range(m):
195| a0 = (270 + int(360.0 * (float(a-1)/float(m)))) % 360
196| a1 = (270 + int(360.0 * (float(a) /float(m)))) % 360
197| if a == 0:
198| pass
199| elif a <= dt1.day:
200| self.draw.pieslice([x1,y1, x2,y2], a0,a1, fill=(0,191,255), outline=(0,0,0))
201| else:
202| self.draw.pieslice([x1,y1, x2,y2], a0,a1, outline=(0,0,0))
203|
204| self.draw.ellipse((fx(-sz),fy(+sz), fx(+sz),fy(-sz)), fill=(127,191,255), outline=(63,63,63))
205|
206| d = float(sz * radius_dots)
207| e = 6
208| for n,a in enumerate(range(0, 360, 30)):
209| r = radians(60+(360 - a))
210| x = int(d * cos(r))
211| y = int(d * sin(r))
212| c = (191,63,7) if n < dt1.month else (0,15,63)
213| x1,x2 = fx(x-e), fx(x+e)
214| y1,y2 = fy(y+e), fy(y-e)
215| self.draw.ellipse([x1,y1, x2,y2], fill=c, outline=(0,0,0))
216|
217| d = int(sz * radius_hrs)
218| t = (270 + int(360.0 * ((dt1.hour % 12) / 12.0))) % 360
219| x1,x2 = fx(-d), fx(+d)
220| y1,y2 = fy(+d), fy(-d)
221| self.draw.pieslice([x1,y1, x2,y2], 270,t, fill=(159,127,31), outline=(63,63,0))
222|
223| d = int(sz * radius_mins)
224| t = (270 + int(360.0 * (dt1.minute / 60.0))) % 360
225| x1,x2 = fx(-d), fx(+d)
226| y1,y2 = fy(+d), fy(-d)
227| self.draw.pieslice([x1,y1, x2,y2], 270,t, fill=(191,255,127), outline=(63,127,31))
228|
229| d = int(sz * radius_secs)
230| t = (270 + int(360.0 * (dt1.second / 60.0))) % 360
231| x1,x2 = fx(-d), fx(+d)
232| y1,y2 = fy(+d), fy(-d)
233| self.draw.pieslice([x1,y1, x2,y2], 270,t, fill=(255,191,127), outline=(127,63,31))
234|
235| c = (239,239,63) if dt1.hour < 12 else (63,95,159)
236| x1,x2 = fx(-size_hub), fx(+size_hub)
237| y1,y2 = fy(+size_hub), fy(-size_hub)
238| self.draw.ellipse([x1,y1, x2,y2], fill=c, outline=(32,32,32))
239|
240| def edit_copy (self, *args):
241| '''Menu: Edit/Copy.'''
242| Log.debug('Edit/Copy()')
243|
244| def app_about (self, *args):
245| '''Menu: Help.'''
246| Log.debug('About()')
247| msgbox.showinfo('About', AboutText)
248|
249| def app_keypress (self, evt):
250| '''Application key handler.
250|
250| Key Bindings:
250| Exit Alt+Q, Esc
250| Help/About F1
250|
250| '''
251| Log.trace(f'KeyPress(sym={evt.keysym})')
252| if evt.keysym == 'F1':
253| self.app_about()
254| return
255| if evt.keysym == 'Escape':
256| self.app_exit('Escape')
257| return
258| if (evt.state & util.KEYPRESS_ALT) and (evt.keysym in ['Q','q']):
259| self.app_exit('Alt-Q')
260| return
261|
262| def _build (self):
263| '''Build the application window.'''
264|
265|
266| Log.info('Create Window...')
267| self.root = tk.Tk()
268| self.root.title(self.title)
269| self.root.geometry(self.settings.current.geometry)
270| self.root.minsize(*self.settings.current.wmin)
271| self.root.maxsize(*self.settings.current.wmax)
272| self.root.configure(bg='#224488')
273| self.root.bind('<KeyPress>', self.app_keypress)
274|
275| Log.trace('Create Menubar...')
276| self.mbar = tk.Menu(self.root)
277| self.mbar.add_command(label='Exit', underline=1, command=self.app_exit)
278| self.mbar.add_separator()
279| self.mbar.add_command(label='About', underline=0, command=self.app_about)
280| self.root['menu'] = self.mbar
281|
282| Log.trace('Create Application frames...')
283|
284| self.wndw = tk.Frame(self.root, relief='flat')
285| self.wndw.pack(side='top', anchor='nw', fill='both', expand=True, padx=5, pady=(4,6))
286| self.wndw.configure(bg='#000000')
287|
288|
289| self.main = tk.Frame(self.wndw, relief='sunken')
290| self.main.pack(side='top', anchor='nw', fill='both', expand=True, padx=2, pady=2)
291|
292|
293| Log.trace('Create Image frame...')
294| self.lbl_imag = tk.Label(self.main)
295| self.lbl_imag.pack(side='top', anchor='nw', fill='both', padx=0, pady=0, ipadx=8, ipady=8)
296| self.lbl_imag.configure(bg='#4488ee')
297|
298|
299| Log.trace('Display image...')
300| self.ready = True
301| self.update_clock()
302|
303|
304|
305| def do_main (**kwargs):
306| '''CMND: Run the GUI App.'''
307| Log.info(f'main:: {str(list(kwargs.keys()))}')
308| Log.info()
309| flag = KWARG('flag', 1, int, kwargs)
310|
311|
312| app = Application(**kwargs)
313| bag['app'] = app
314|
315|
316| if flag:
317| app.root.mainloop()
318|
319| Log.info()
320| return 'Done'
321|
322|
323| def do_test (**kwargs):
324| '''CMND: Do a test.'''
325| fpath = KWARG('fpath', BasePath, str, kwargs)
326| fname = KWARG('fname', 'test.out', str, kwargs)
327| Log.info(f'test:: {str(list(kwargs.keys()))}' )
328| Log.debug(f'{fpath=}')
329| Log.debug(f'{fname=}')
330| Log.info()
331| Log.info()
332| return 'Done'
333|
334| def dispatch (cmd, **kwargs):
335| '''Dispatch to a module function based on CMD.'''
336| Log.info(f'CMD: {cmd}')
337| for kw in kwargs:
338| Log.debug(f'argument[{kw}]: {kwargs[kw]}')
339| Log.info()
340| if cmd == 'main': return do_main(**kwargs)
341| if cmd == 'test': return do_test(**kwargs)
342| return 'Nothing to do!'
343|
344| if __name__ == '__main__':
345| print(f'autorun: {argv[0]}')
346| Log.start(path.join(BasePath,'tk-clock.log'))
347|
348| Log.level(trace())
349| Log.info(argv[0])
350| Log.info()
351| cmd = argv[1] if 1 < len(argv) else CMND
352| kwargs = ARGS
353| for a in argv[2:]:
354| nv = a.split('=', 1)
355| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
356| Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
357| try:
358| print(f'CMD: {cmd}')
359| print()
360| obj = dispatch(cmd, **kwargs)
361| if 'app' in bag: app=bag['app']
362| print()
363| print(obj)
364| Log.info()
365| Log.info(obj)
366| except:
367| etype, evalue, tb = exc_info()
368| ts = extract_tb(tb)
369| Log.error()
370| Log.error(f'{etype.__name__}: {evalue!s}')
371| Log.error()
372| for t in ts[-5:]:
373| Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
374| Log.error(f' {t[3]}')
375| Log.error()
376| raise
377| finally:
378| Log.end()
379|
380| '''eof'''
381|