Advertisement
here2share

# Tk_mouse2rotate.py

Jun 24th, 2020
1,247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. # Tk_mouse2rotate.py
  2.  
  3. from Tkinter import *
  4. import math
  5. import time
  6.  
  7. root = Tk()
  8. root.title("Tk mouse2rotate")
  9. ww=200; hh=200
  10.  
  11. z = 0
  12. spin = {}
  13. while z < 1000:
  14.     x = int(math.sin(math.radians(z))*1000.0)
  15.     y = int(math.cos(math.radians(z))*1000.0)
  16.     spin[z] = x,y
  17.     z += 1
  18.  
  19. canvas = Canvas(width=ww, height=hh)
  20. canvas.pack()
  21.  
  22.  
  23. # a square
  24. xy = [(50, 50), (150, 50), (150, 150), (50, 150)]
  25.  
  26. polygon_item = canvas.create_polygon(xy)
  27.  
  28. center = ww/2, hh/2
  29.  
  30. def getangle(event):
  31.     dx = canvas.canvasx(event.x) - center[0]
  32.     dy = canvas.canvasy(event.y) - center[1]
  33.     print dx,dy
  34.     try:
  35.         return complex(dx, dy) / abs(complex(dx, dy))
  36.     except ZeroDivisionError:
  37.         return 0.0 # cannot determine angle
  38.  
  39. def getspinangle():
  40.     x,y = spin[z]
  41.     dx = x - center[0]
  42.     dy = y - center[1]
  43.     return complex(dx, dy) / abs(complex(dx, dy))
  44.  
  45. def press(event):
  46.     # calculate angle at start point
  47.     global start
  48.     start = getangle(event)
  49.  
  50. def motion(event):
  51.     # calculate current angle relative to initial angle
  52.     global start, delay
  53.     delay = time.clock()+1
  54.     angle = getangle(event) / start
  55.     offset = complex(center[0], center[1])
  56.     newxy = []
  57.     for x, y in xy:
  58.         v = angle * (complex(x, y) - offset) + offset
  59.         newxy.append(v.real)
  60.         newxy.append(v.imag)
  61.     canvas.itemconfig(polygon_item, fill='green')
  62.     canvas.coords(polygon_item, *newxy)
  63.  
  64. canvas.bind("<Button-1>", press)
  65. canvas.bind("<B1-Motion>", motion)
  66.  
  67. z = 0
  68. Lz = len(spin)
  69. delay = 0
  70. while 1:
  71.     if delay < time.clock():
  72.         offset = complex(center[0], center[1])
  73.         newxy = []
  74.         angle = getspinangle()
  75.         z += 1
  76.         z = z%Lz
  77.         for x, y in xy:
  78.             v = angle * (complex(x, y) - offset) + offset
  79.             newxy.append(v.real)
  80.             newxy.append(v.imag)
  81.         canvas.itemconfig(polygon_item, fill='orange')
  82.         canvas.coords(polygon_item, *newxy)
  83.         delay = time.clock()+0.1
  84.     canvas.update()
  85.  
  86. mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement