如何使用graphics.py实现圆形绕另一圆形的公转效果?
Solution: Orbiting Circle with graphics.py
Here's the modified code to make c1 orbit around c:
from graphics import * from math import sin, cos, pi from time import sleep win = GraphWin('Program', 500, 500) win.setBackground('white') # Stationary circle c = Circle(Point(250, 250), 50) c.draw(win) # Orbiting circle (initial position above the stationary circle) orbit_radius = 75 # Distance between centers (sum of both radii: 50 + 25) c1 = Circle(Point(250, 250 - orbit_radius), 25) c1.draw(win) theta = -pi/2 # Starting angle to match initial upward position try: while True: # Calculate new center position using trigonometric orbital formula new_x = 250 + orbit_radius * cos(theta) new_y = 250 + orbit_radius * sin(theta) c1.setCenter(Point(new_x, new_y)) theta += 0.1 # Increment angle to move the circle along its orbit sleep(0.05) # Adjust animation speed (smaller value = faster movement) except GraphicsError: # Gracefully handle window closure pass win.close()
Key Details:
- Orbit Radius: The distance between the two circle centers is set to
75(sum of their radii) to avoid overlapping during orbit. - Trigonometric Math:
cos(theta)calculates the horizontal offset from the stationary circle's center.sin(theta)calculates the vertical offset. Sincegraphics.pyuses a downward-increasing y-axis, starting withtheta = -pi/2placesc1directly above the center (matching your initial code).
- Orbit Control:
- Adjust
theta += 0.1to change orbit speed (larger values = faster movement). - Swap to
theta -= 0.1for counterclockwise orbit. - Modify
sleep(0.05)to tweak animation smoothness (smaller values = smoother motion).
- Adjust
- Error Handling: The
try/exceptblock prevents crashes if the user closes the window manually.
内容的提问来源于stack exchange,提问作者iamstudentsorry
相关产品推荐
相关产品推荐

