1. 程式人生 > 實用技巧 >Python-使用tkinter canvas繪製的電子時鐘

Python-使用tkinter canvas繪製的電子時鐘

 #!/usr/bin/env python
# -*- coding: utf-8 -*- from tkinter import *
import math
import threading
import time root = Tk()
cv = Canvas(root, bg='white')
cv.create_oval(10,10,210,210,fill='yellow')
cv.pack()
for num in range(12):
angle=num*30
x1 = abs(round(math.cos(math.pi*angle/180)*95)+110)
y1 = abs(110 - round(math.sin(math.pi*angle/180)*95))
x2 = abs(round(math.cos(math.pi*angle/180)*100)+110)
y2 = abs(110 - round(math.sin(math.pi*angle/180)*100))
if angle not in (0, 90, 180, 270):
cv.create_line(x1, y1, x2, y2) cv.create_line(110, 10, 110, 20, width=2, fill='red') #
cv.create_text(110, 35, text='')
cv.create_line(110, 200, 110, 210, width=2, fill='red') # 6
cv.create_text(110, 185, text='')
cv.create_line(10, 110, 20, 110, width=2, fill='red') #
cv.create_text(35, 110, text='')
cv.create_line(200, 110, 210, 110, width=2, fill='red') #
cv.create_text(185, 110, text='')
sec_pointer = cv.create_line(110, 110, 110, 110, fill='gray')
miu_pointer = cv.create_line(110, 110, 110, 110, fill='green', width=2)
hor_pointer = cv.create_line(110, 110, 110, 110, fill='red', width=3)
cnt_point = cv.create_oval(107, 107, 113, 113, fill='black') time_struct = time.localtime()
hour = time_struct.tm_hour - 12 if time_struct.tm_hour > 12 else time_struct.tm_hour
_min = time_struct.tm_min
sec = time_struct.tm_sec init_sec = sec*6
init_miu = _min*6 + sec*6/60
init_hor = hour * 30 + _min * 30/3600*60 + sec * 30/3600 def draw_pointer():
sec = 90 - init_sec
miu = 90 - init_miu
hor = 90 - init_hor
try:
while True:
x1 = abs(round(math.cos(math.pi*sec/180)*90)+110)
y1 = abs(110 - round(math.sin(math.pi*sec/180)*90))
x2 = abs(round(math.cos(math.pi*miu/180)*70)+110)
y2 = abs(110 - round(math.sin(math.pi*miu/180)*70))
x3 = abs(round(math.cos(math.pi*hor/180)*36)+110)
y3 = abs(110 - round(math.sin(math.pi*hor/180)*36))
cv.coords(sec_pointer, 110, 110, x1, y1)
cv.coords(miu_pointer, 110, 110, x2, y2)
cv.coords(hor_pointer, 110, 110, x3, y3)
if sec == -180:
sec = 180
if miu == -180:
miu = 180
if hor == -180:
hor = 180
sec -= 6
miu -= 6/60
hor -= 30/3600
time.sleep(1)
except RuntimeError as e:
exit(0) td = threading.Thread(target=draw_pointer,).start()
root.mainloop()

canvas部件使用方法參考地址:https://www.runoob.com/python/python-tk-canvas.html