You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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. Since graphics.py uses a downward-increasing y-axis, starting with theta = -pi/2 places c1 directly above the center (matching your initial code).
  • Orbit Control:
    • Adjust theta += 0.1 to change orbit speed (larger values = faster movement).
    • Swap to theta -= 0.1 for counterclockwise orbit.
    • Modify sleep(0.05) to tweak animation smoothness (smaller values = smoother motion).
  • Error Handling: The try/except block prevents crashes if the user closes the window manually.

内容的提问来源于stack exchange,提问作者iamstudentsorry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 01:35:26