Advertisement
here2share

# Tk_earth_moon_orbit.py

Mar 20th, 2022
678
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.14 KB | None | 0 0
  1. # Tk_earth_moon_orbit.py
  2.  
  3. import tkinter as tk
  4. import math
  5.  
  6. # --- functions ---
  7.  
  8. def calculate_position(data):
  9.     #unpack data
  10.     center_x, center_y, radius, distance, angle, angle_speed, x, y = data
  11.  
  12.     # calculate new position of object
  13.     x = center_x - distance * math.sin(math.radians(-angle))
  14.     y = center_y - distance * math.cos(math.radians(-angle))
  15.  
  16.     # save positon so other object can use it as its center of rotation
  17.     data[6] = x
  18.     data[7] = y
  19.  
  20.     # calcuate oval coordinates
  21.     x1 = x - radius
  22.     y1 = y - radius
  23.     x2 = x + radius
  24.     y2 = y + radius
  25.  
  26.     return x1, y1, x2, y2
  27.  
  28. def create_object(data):
  29.     # calculate oval coordinates
  30.     x1, y1, x2, y2 = calculate_position(data)
  31.  
  32.     # create oval
  33.     return c.create_oval(x1, y1, x2, y2)
  34.  
  35. def move_object(object_id, data):
  36.     # calculate oval coordinates
  37.     x1, y1, x2, y2 = calculate_position(data)
  38.  
  39.     # move oval
  40.     c.coords(object_id, x1, y1, x2, y2)
  41.  
  42. def animate():
  43.     # move earth - angle += angle_speed
  44.     earth[4] += earth[5]
  45.     move_object(e_id, earth)
  46.  
  47.     # moon uses earth position as center of rotation
  48.     moon[0] = earth[6]
  49.     moon[1] = earth[7]
  50.  
  51.     # move move - angle += angle_speed
  52.     moon[4] += moon[5]
  53.     move_object(m_id, moon)
  54.  
  55.     # animate again after 100ms
  56.     root.after(100, animate)
  57.  
  58. # --- main ---
  59.  
  60. # canvas size
  61. WIDTH  = 500
  62. HEIGHT = 500
  63.  
  64. # center of solar system
  65. center_x = WIDTH//2
  66. center_y = HEIGHT//2
  67.  
  68. # objects data
  69. # [center of rotation x and y, radius, distance from center, current angle, angle speed, current positon x and y]
  70. sun   = [center_x, center_y, 30, 0, 0, 0, 0, 0]
  71. earth = [center_x, center_y, 10, 100, 0, 1, 0, 0]
  72. moon  = [0, 0, 5, 40, 0, 3, 0, 0]
  73.  
  74. # - init -
  75. root = tk.Tk()
  76. root.title("Solar System")
  77.  
  78. # - canvas -
  79. c = tk.Canvas(root, width=WIDTH, heigh=HEIGHT)
  80. c.pack()
  81.  
  82. # create sun and earth
  83. s_id = create_object(sun)
  84. e_id = create_object(earth)
  85.  
  86. # moon uses earth position as center of rotation
  87. moon[0] = earth[6]
  88. moon[1] = earth[7]
  89.  
  90. # create moon
  91. m_id = create_object(moon)
  92.  
  93. # start animation
  94. animate()
  95.  
  96. # - start program -
  97. root.mainloop()
  98.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement