Code: Alles auswählen
#!/usr/bin/env python
"""
Simple analog clock widget for Tk UIs.
Works with Python 2 and 3.
"""
from __future__ import division
import cmath
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
from datetime import datetime as DateTime, timedelta as TimeDelta
from math import pi as PI
__all__ = ['AnalogClock']
__author__ = "Marc 'BlackJack' Rintsch"
__version__ = '0.1'
__date__ = '2012-12-28'
if sys.version_info[0] > 2:
xrange = range
class Hand(object):
def __init__(self, clock, length, width, color, tick_factor=1):
self.clock = clock
self.length = length
self.width = width
self.color = color
self.tick_factor = tick_factor
self.tick = 0
self.line = None
self.draw()
def draw(self):
self.clock.delete(self.line)
self.line = self.clock._create_rotated_line(
0,
self.length,
self.tick * self.tick_factor,
width=self.width,
fill=self.color
)
def update(self, tick):
if tick != self.tick:
self.tick = tick
self.draw()
class AnalogClock(tk.Canvas):
def __init__(
self, master, size=100, clock_bg='white', hands_color='black',
seconds_hand_color='red', **kwargs
):
tk.Canvas.__init__(self, master, width=size, height=size, **kwargs)
self.size = size
self.radius = size // 2
tick_count = 60
self.tick_coordinates = list()
for i in xrange(tick_count):
x_y = cmath.rect(1, (i - tick_count / 4) * PI / (tick_count / 2))
self.tick_coordinates.append((x_y.real, x_y.imag))
self.create_oval(1, 1, self.size - 1, self.size - 1, fill=clock_bg)
for i in xrange(tick_count):
self._create_rotated_line(
self.radius - self.radius // 10,
self.radius - self.radius // 50,
i,
width=(self.radius // 50 if i % 5 == 0 else self.radius // 100)
)
self.hands = [
Hand(self, self.radius - 2, self.size // 25, hands_color),
Hand(self, self.radius // 2, self.size // 25, hands_color, 5),
Hand(self, self.radius - 2, self.size // 100, seconds_hand_color)
]
self.update_hands()
def _create_rotated_line(
self, distance_a, distance_b, tick_index, **kwargs
):
x, y = self.tick_coordinates[tick_index % len(self.tick_coordinates)]
return self.create_line(
x * distance_a + self.radius,
y * distance_a + self.radius,
x * distance_b + self.radius,
y * distance_b + self.radius,
**kwargs
)
def update_hands(self):
time = DateTime.now()
for hand, value in zip(
self.hands, (time.minute, time.hour, time.second)
):
hand.update(value)
def run(self):
self.update_hands()
self.after(500, self.run)
def main():
root = tk.Tk()
for i in xrange(5):
clock = AnalogClock(root, (i + 1) * 100)
clock.pack(side=tk.LEFT)
clock.run()
root.mainloop()
if __name__ == '__main__':
main()