here2share

# Tk_analog_clock.py

Dec 3rd, 2020
712
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Tk_analog_clock.py
  2.  
  3. from math import cos, sin, pi
  4.  
  5. import datetime
  6. import tkinter as tk
  7.  
  8. def _create_circle(self, x, y, radius, **kwargs):
  9.     return self.create_oval(x - radius, y - radius, x + radius, y + radius, **kwargs)
  10.  
  11. tk.Canvas.create_circle = _create_circle
  12.  
  13. root = tk.Tk()  
  14. root.attributes('-fullscreen', True)
  15. root.title("Analog Clock")
  16.  
  17. SCREEN_WIDTH = root.winfo_screenwidth()
  18. SCREEN_HEIGHT = root.winfo_screenheight()
  19.  
  20. canvas = tk.Canvas(root)
  21. canvas.pack(fill="both", expand=True)
  22.  
  23. radius = SCREEN_HEIGHT / 2 - 50
  24.  
  25. def draw_hour_handle(now):
  26.     hour = now.hour % 12 + now.minute / 60
  27.     percentage = hour / 12
  28.     angle = percentage * 2 * pi - pi / 2
  29.  
  30.     x = cos(angle) * radius * 0.60 + SCREEN_WIDTH / 2
  31.     y = sin(angle) * radius * 0.60 + SCREEN_HEIGHT / 2
  32.    
  33.     canvas.create_line(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, x, y, width = 10)
  34.    
  35. def draw_minute_handle(now):
  36.     minutes = now.minute + now.second / 60
  37.     percentage = minutes / 60
  38.     angle = percentage * 2 * pi - pi / 2
  39.  
  40.     x = cos(angle) * radius * 0.87 + SCREEN_WIDTH / 2
  41.     y = sin(angle) * radius * 0.87 + SCREEN_HEIGHT / 2
  42.    
  43.     canvas.create_line(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, x, y, width = 5)
  44.    
  45. def draw_second_handle(now):
  46.     seconds = now.second
  47.     percentage = seconds / 60
  48.     angle = percentage * 2 * pi - pi / 2
  49.  
  50.     x = cos(angle) * radius * 0.90 + SCREEN_WIDTH / 2
  51.     y = sin(angle) * radius * 0.90 + SCREEN_HEIGHT / 2
  52.    
  53.     canvas.create_line(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, x, y, width = 3, fill='red')
  54.    
  55. def draw_ticks():
  56.     for i in range(12):
  57.         hour = i % 12
  58.         percentage = hour / 12
  59.         angle = percentage * 2 * pi - pi / 2
  60.        
  61.         x0 = cos(angle) * radius * 0.85 + SCREEN_WIDTH / 2
  62.         y0 = sin(angle) * radius * 0.85 + SCREEN_HEIGHT / 2
  63.    
  64.         x1 = cos(angle) * radius + SCREEN_WIDTH / 2
  65.         y1 = sin(angle) * radius + SCREEN_HEIGHT / 2
  66.        
  67.         canvas.create_line(x0, y0, x1, y1, width = 2)
  68.    
  69. def draw():
  70.     now = datetime.datetime.now()
  71.    
  72.     canvas.create_circle(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, radius, width = 5)
  73.     draw_hour_handle(now)
  74.     draw_minute_handle(now)
  75.     draw_second_handle(now)
  76.     draw_ticks()
  77.  
  78. def tick():
  79.     canvas.delete(tk.ALL)
  80.     draw()        
  81.     canvas.after(60, tick) # 30 FPS Update rate
  82.  
  83. tick()
  84.  
  85. tk.mainloop()
RAW Paste Data