1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as TK
class tkTimer (TK.Frame):
def __init__ (self, master=None, delay=100, callback=None, *args, **kw):
# superclass inits
TK.Frame.__init__(self, master)
# member inits
self.master = master
self.delay = delay
self.callback = callback
self.args = args
self.kw = kw
self.tid = 0
self.started = False
# end def
def start (self):
if not self.started:
self.started = True
self.__tick()
# end if
# end def
def stop (self):
self.after_cancel(self.tid)
self.tid = 0
self.started = False
# end def
def __tick (self):
if callable(self.callback):
self.callback(*self.args, **self.kw)
self.tid = self.after(self.delay, self.__tick)
# end if
# end def
# end class tkTimer
# ---------------------------- ZONE DEMO -------------------------------
def update_clock ():
_hours = ticks // 3600
_minutes = (ticks // 60) % 60
_seconds = ticks % 60
cvar_clock.set(
"{HH:02d}:{MM:02d}:{SS:02d}"
.format(HH=_hours, MM=_minutes, SS=_seconds)
)
# end def
def run_clock ():
global ticks
update_clock()
ticks += 1
# end def
def demo ():
global root, timer, ticks, cvar_clock
root = TK.Tk()
root.title("tkTimer demo")
timer = tkTimer(root, delay=1000, callback=run_clock)
ticks = 0
cvar_clock = TK.StringVar()
TK.Label(root, textvariable=cvar_clock, font="sans 36 bold").pack(padx=5, pady=5)
TK.Button(root, text="Start", command=timer.start).pack(side=TK.LEFT, padx=5, pady=5)
TK.Button(root, text="Stop", command=timer.stop).pack(side=TK.LEFT, padx=5, pady=5)
TK.Button(root, text="Quit", command=root.destroy).pack(side=TK.RIGHT, padx=5, pady=5)
update_clock()
root.mainloop()
# end def
if __name__ == "__main__":
demo()
# end if |
Partager