Python-使用tkinter canvas绘制的电子时钟
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 from tkinter import * 5 import math 6 import threading 7 import time 8 9 10 root = Tk() 11 cv = Canvas(root, bg='white') 12 cv.create_oval(10,10,210,210,fill='yellow') 13 cv.pack() 14 for num in range(12): 15 angle=num*30 16 x1 = abs(round(math.cos(math.pi*angle/180)*95)+110) 17 y1 = abs(110 - round(math.sin(math.pi*angle/180)*95)) 18 x2 = abs(round(math.cos(math.pi*angle/180)*100)+110) 19 y2 = abs(110 - round(math.sin(math.pi*angle/180)*100)) 20 if angle not in (0, 90, 180, 270): 21 cv.create_line(x1, y1, x2, y2) 22 23 cv.create_line(110, 10, 110, 20, width=2, fill='red') # 12 24 cv.create_text(110, 35, text='12') 25 cv.create_line(110, 200, 110, 210, width=2, fill='red') # 6 26 cv.create_text(110, 185, text='6') 27 cv.create_line(10, 110, 20, 110, width=2, fill='red') # 9 28 cv.create_text(35, 110, text='9') 29 cv.create_line(200, 110, 210, 110, width=2, fill='red') # 3 30 cv.create_text(185, 110, text='3') 31 sec_pointer = cv.create_line(110, 110, 110, 110, fill='gray') 32 miu_pointer = cv.create_line(110, 110, 110, 110, fill='green', width=2) 33 hor_pointer = cv.create_line(110, 110, 110, 110, fill='red', width=3) 34 cnt_point = cv.create_oval(107, 107, 113, 113, fill='black') 35 36 time_struct = time.localtime() 37 hour = time_struct.tm_hour - 12 if time_struct.tm_hour > 12 else time_struct.tm_hour 38 _min = time_struct.tm_min 39 sec = time_struct.tm_sec 40 41 init_sec = sec*6 42 init_miu = _min*6 + sec*6/60 43 init_hor = hour * 30 + _min * 30/3600*60 + sec * 30/3600 44 45 46 def draw_pointer(): 47 sec = 90 - init_sec 48 miu = 90 - init_miu 49 hor = 90 - init_hor 50 try: 51 while True: 52 x1 = abs(round(math.cos(math.pi*sec/180)*90)+110) 53 y1 = abs(110 - round(math.sin(math.pi*sec/180)*90)) 54 x2 = abs(round(math.cos(math.pi*miu/180)*70)+110) 55 y2 = abs(110 - round(math.sin(math.pi*miu/180)*70)) 56 x3 = abs(round(math.cos(math.pi*hor/180)*36)+110) 57 y3 = abs(110 - round(math.sin(math.pi*hor/180)*36)) 58 cv.coords(sec_pointer, 110, 110, x1, y1) 59 cv.coords(miu_pointer, 110, 110, x2, y2) 60 cv.coords(hor_pointer, 110, 110, x3, y3) 61 if sec == -180: 62 sec = 180 63 if miu == -180: 64 miu = 180 65 if hor == -180: 66 hor = 180 67 sec -= 6 68 miu -= 6/60 69 hor -= 30/3600 70 time.sleep(1) 71 except RuntimeError as e: 72 exit(0) 73 74 75 td = threading.Thread(target=draw_pointer,).start() 76 root.mainloop()
界面截图:
canvas部件使用方法参考地址:https://www.runoob.com/python/python-tk-canvas.html