import tkinter as tk
import math
# ------------------------------
# Configuration
# ------------------------------
WHEEL_RADIUS = 40
SPOKES = 10
WHEEL_DISTANCE = 150
BODY_WIDTH = 180
BODY_HEIGHT = 50
MOVE_SPEED = 2 # pixels per frame
ROTATE_SPEED = 5 # degrees per frame
FPS = 30 # frames per second
# ------------------------------
# Helper functions
# ------------------------------
def create_wheel(canvas, cx, cy, radius, spokes):
"""Create a wheel with spokes and return IDs of all parts."""
parts = []
# Outer circle
parts.append(canvas.create_oval(cx - radius, cy - radius,
cx + radius, cy + radius,
outline="black", width=2))
# Spokes
for i in range(spokes):
angle = math.radians(i * (360 / spokes))
x_end = cx + radius * math.cos(angle)
y_end = cy + radius * math.sin(angle)
parts.append(canvas.create_line(cx, cy, x_end, y_end, fill="black", width=1.5))
return parts
def rotate_wheel(canvas, parts, cx, cy, angle_deg):
"""Rotate spokes of the wheel around its center."""
# First part is the circle, skip it
for spoke_id in parts[1:]:
coords = canvas.coords(spoke_id)
x0, y0, x1, y1 = coords
# Rotate endpoint (x1, y1) around center (cx, cy)
dx, dy = x1 - cx, y1 - cy
r = math.hypot(dx, dy)
current_angle = math.atan2(dy, dx)
new_angle = current_angle + math.radians(angle_deg)
new_x = cx + r * math.cos(new_angle)
new_y = cy + r * math.sin(new_angle)
canvas.coords(spoke_id, cx, cy, new_x, new_y)
# ------------------------------
# Animation setup
# ------------------------------
root = tk.Tk()
root.title("Two Wheels with Rotating Spokes and Moving Body")
canvas = tk.Canvas(root, width=800, height=300, bg="white")
canvas.pack()
# Initial positions
wheel1_center = [100, 200]
wheel2_center = [100 + WHEEL_DISTANCE, 200]
# Create wheels
wheel1_parts = create_wheel(canvas, *wheel1_center, WHEEL_RADIUS, SPOKES)
wheel2_parts = create_wheel(canvas, *wheel2_center, WHEEL_RADIUS, SPOKES)
# Create body rectangle above wheels
body_top_left = (wheel1_center[0] - (BODY_WIDTH - WHEEL_DISTANCE) / 2, wheel1_center[1] - WHEEL_RADIUS - BODY_HEIGHT)
body_bottom_right = (body_top_left[0] + BODY_WIDTH, body_top_left[1] + BODY_HEIGHT)
body_id = canvas.create_rectangle(*body_top_left, *body_bottom_right, fill="skyblue", outline="black", width=2)
# Group all parts for movement
all_parts = wheel1_parts + wheel2_parts + [body_id]
# ------------------------------
# Animation loop
# ------------------------------
def animate():
# Move all parts forward
for part in all_parts:
canvas.move(part, MOVE_SPEED, 0)
# Update wheel centers
wheel1_center[0] += MOVE_SPEED
wheel2_center[0] += MOVE_SPEED
# Rotate spokes
rotate_wheel(canvas, wheel1_parts, *wheel1_center, ROTATE_SPEED)
rotate_wheel(canvas, wheel2_parts, *wheel2_center, ROTATE_SPEED)
# Loop animation
root.after(int(1000 / FPS), animate)
animate()
root.mainloop()

Tidak ada komentar:
Posting Komentar