import tkinter as tk
import math
# --- Configuration ---
WIDTH = 800
HEIGHT = 200
RADIUS = 30
WHEEL_SPEED = 5
ROTATION_SPEED = 0.1 # Radians per frame
# --- Setup Canvas ---
root = tk.Tk()
root.title("Rolling Wheel Animation")
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="white")
canvas.pack()
# --- Create Wheel Parts ---
# Main Circle
wheel = canvas.create_oval(50-RADIUS, 100-RADIUS, 50+RADIUS, 100+RADIUS, width=2)
# Spoke (to show rotation)
spoke = canvas.create_line(50, 100, 50+RADIUS, 100, width=2)
def animate():
# 1. Move Forward
canvas.move(wheel, WHEEL_SPEED, 0)
canvas.move(spoke, WHEEL_SPEED, 0)
# 2. Rotate Spoke
# Get current spoke coordinates
x1, y1, x2, y2 = canvas.coords(spoke)
center_x = (x1 + x2) / 2 # Actually this is wrong, need to calculate center correctly
# Correction: need the center of the wheel, not the line
wheel_coords = canvas.coords(wheel)
center_x = (wheel_coords[0] + wheel_coords[2]) / 2
center_y = (wheel_coords[1] + wheel_coords[3]) / 2
# Calculate new spoke endpoint based on rotation
new_x2 = center_x + RADIUS * math.cos(animate.angle)
new_y2 = center_y + RADIUS * math.sin(animate.angle)
# Update spoke position
canvas.coords(spoke, center_x, center_y, new_x2, new_y2)
# Increment angle
animate.angle += ROTATION_SPEED
# 3. Reset position if it goes off-screen
if wheel_coords[0] > WIDTH:
canvas.coords(wheel, 0-RADIUS, 100-RADIUS, 0+RADIUS, 100+RADIUS)
canvas.coords(spoke, 0, 100, 0+RADIUS, 100)
# 4. Loop Animation
root.after(20, animate)
# Initialize angle for rotation
animate.angle = 0
animate()
root.mainloop()

Tidak ada komentar:
Posting Komentar