here2share

# tk_dist_degrees.py

Sep 24th, 2025
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. # tk_dist_degrees.py
  2.  
  3. import tkinter as tk
  4. from PIL import Image, ImageTk, ImageDraw, ImageFont
  5. import math
  6. WW, HH = 640, 640
  7. cx, cy = WW // 2, HH // 2
  8. root = tk.Tk()
  9. root.geometry('+0+0')
  10. canvas = tk.Canvas(root, width=WW, height=HH)
  11. canvas.pack()
  12.  
  13. current_mouse_x, current_mouse_y = cx, cy
  14.  
  15. def get_degrees(x, y):
  16.     dx = x - cx
  17.     dy = y - cy
  18.     degrees = math.degrees(math.atan2(-dy, dx))
  19.     if degrees < 0:
  20.         degrees += 360
  21.     return degrees
  22.  
  23. def get_distance_from_center(x, y):
  24.     dx = x - cx
  25.     dy = y - cy
  26.     distance = math.sqrt(dx * dx + dy * dy)
  27.     return distance
  28.  
  29. def on_drag(event):
  30.     global current_mouse_x, current_mouse_y
  31.     current_mouse_x, current_mouse_y = event.x, event.y
  32.  
  33. def on_motion(event):
  34.     global current_mouse_x, current_mouse_y
  35.     current_mouse_x, current_mouse_y = event.x, event.y
  36.  
  37. canvas.bind("<B1-Motion>", on_drag)
  38. canvas.bind("<Motion>", on_motion)
  39.  
  40. while 1:
  41.     canvas.delete('all')
  42.     degrees = get_degrees(current_mouse_x, current_mouse_y)
  43.     distance = get_distance_from_center(current_mouse_x, current_mouse_y)
  44.  
  45.     arm_angle = math.radians(degrees)
  46.     arm_end_x = cx + distance * math.cos(arm_angle)
  47.     arm_end_y = cy - distance * math.sin(arm_angle)  # negative because canvas y is flipped
  48.  
  49.     canvas.create_line(cx, cy, arm_end_x, arm_end_y, fill='blue', width=3)
  50.     canvas.create_oval(cx-5, cy-5, cx+5, cy+5, fill='red', outline='red')  # center dot
  51.        
  52.     canvas.create_text((20, 20), text=f"{degrees:.0f}ยฐ", fill='red', anchor='nw')
  53.     canvas.create_text((20, 40), text=f"Distance: {distance:.0f}", fill='green', anchor='nw')
  54.     root.update()
Advertisement
Add Comment
Please, Sign In to add comment