here2share

#Tk_pendulum.py ^ 7/10/22

Jul 19th, 2022 (edited)
1,008
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. # Tk_pendulum.py
  2.  
  3. from math import sin, cos, degrees, atan2, radians
  4. from tkinter import *
  5. from time import time
  6.  
  7. ww = 500
  8. hh = 500
  9. root = Tk()
  10. root.title('Pendulum')
  11. canvas = Canvas(width=ww, height=hh, background='#343434')
  12. canvas.pack()
  13.  
  14. canvas.noMousePress = 1
  15.  
  16. r = 30
  17. rPend = int(ww * 0.5 - r * 2)
  18. gravity = 0.9995
  19. mid = int(ww * 0.5)
  20. penh = 50
  21. velocity = 120
  22. angle = 0
  23. acc = 1.0
  24. swing = 180
  25.  
  26.  
  27. def xy2deg(
  28.     x1,
  29.     y1,
  30.     x2,
  31.     y2,
  32.     ):
  33.     return degrees(atan2(x2 - x1, y2 - y1)) % 360
  34.  
  35.  
  36. def deg2xy(angle, r):
  37.     a = radians(angle)
  38.     return (sin(a) * r, cos(a) * r)
  39.  
  40.  
  41. YVEL = 1 / 180.0
  42.  
  43.  
  44. def y2vel(z=angle):
  45.     return 180 - abs(180 - z)
  46.  
  47.  
  48. def mouse(e):
  49.     global velocity, acc, swing
  50.     x = e.x
  51.     y = e.y
  52.     canvas.noMousePress = 0
  53.     swing = 180
  54.     velocity = y2vel(xy2deg(mid, penh, x, y))
  55.     if 'ButtonRelease' in str(e):
  56.         canvas.noMousePress = 1
  57.     acc = abs(acc)
  58.     if x < mid:
  59.         acc *= -1
  60.         velocity *= -1
  61.  
  62.  
  63. canvas.bind('<Button-1>', mouse)
  64. canvas.bind('<B1-Motion>', mouse)
  65. canvas.bind('<ButtonRelease-1>', mouse)
  66.  
  67. while 1:
  68.     endtime = time() + 0.01
  69.     canvas.delete('pendulum')
  70.  
  71.     swing += acc
  72.     swing %= 360
  73.  
  74.     if canvas.noMousePress:
  75.         angle = cos(radians(swing)) * velocity * -1
  76.     else:
  77.         angle = velocity
  78.  
  79.     (ballX, ballY) = deg2xy(angle, rPend)
  80.     velocity *= gravity
  81.  
  82.     canvas.create_line(
  83.         mid,
  84.         penh,
  85.         mid + ballX,
  86.         penh + ballY,
  87.         width=5,
  88.         fill='orange',
  89.         tags='pendulum',
  90.         )
  91.     canvas.create_oval(
  92.         mid + ballX - r,
  93.         penh + ballY - r,
  94.         mid + ballX + r,
  95.         penh + ballY + r,
  96.         fill='white',
  97.         outline='orange',
  98.         width=5,
  99.         tags='pendulum',
  100.         )
  101.     canvas.update()
  102.     while endtime > time():
  103.         0
  104.     print(velocity)
Add Comment
Please, Sign In to add comment