import tkinter as tk
import math
# Configuration
WIDTH, HEIGHT = 800, 300
WHEEL_RADIUS = 40
SPOKES = 10
SPEED = 5
ANGLE_STEP = 5
class VehicleAnimation:
def __init__(self, root):
self.canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg='white')
self.canvas.pack()
self.angle = 0
self.x_pos = 50
self.y_ground = 200
# Create shapes
self.rect = self.canvas.create_rectangle(0, 0, 150, 60, fill='blue')
self.wheel1 = self.create_wheel(self.x_pos, self.y_ground)
self.wheel2 = self.create_wheel(self.x_pos + 100, self.y_ground)
self.animate()
def create_wheel(self, x, y):
# Create circle + 10 spokes
wheel_items = []
circle = self.canvas.create_oval(x-WHEEL_RADIUS, y-WHEEL_RADIUS,
x+WHEEL_RADIUS, y+WHEEL_RADIUS, outline='black', width=2)
wheel_items.append(circle)
for i in range(SPOKES):
spoke = self.canvas.create_line(x, y, x, y-WHEEL_RADIUS, fill='black')
wheel_items.append(spoke)
return wheel_items
def animate(self):
self.angle = (self.angle + ANGLE_STEP) % 360
# Move forward
self.x_pos += SPEED
if self.x_pos > WIDTH + 100: self.x_pos = -100
# Update Wheel 1
self.update_wheel(self.wheel1, self.x_pos, self.y_ground)
# Update Wheel 2
self.update_wheel(self.wheel2, self.x_pos + 100, self.y_ground)
# Update Rectangle (body)
self.canvas.coords(self.rect, self.x_pos-25, self.y_ground-60, self.x_pos+125, self.y_ground-10)
self.canvas.after(20, self.animate)
def update_wheel(self, wheel_items, x, y):
# Update circle
self.canvas.coords(wheel_items[0], x-WHEEL_RADIUS, y-WHEEL_RADIUS,
x+WHEEL_RADIUS, y+WHEEL_RADIUS)
# Update Spokes
for i in range(SPOKES):
angle_rad = math.radians(self.angle + i * (360/SPOKES))
x2 = x + WHEEL_RADIUS * math.cos(angle_rad)
y2 = y + WHEEL_RADIUS * math.sin(angle_rad)
self.canvas.coords(wheel_items[i+1], x, y, x2, y2)
root = tk.Tk()
root.title("Moving Wheels Animation")
app = VehicleAnimation(root)
root.mainloop()

Tidak ada komentar:
Posting Komentar