Jumat, 10 April 2026

Python Animation Moving Cart Animation


 


import tkinter as tk

import math


# Configuration

WIDTH, HEIGHT = 800, 300

WHEEL_RADIUS = 30

SPOKES = 10

BROWN = "#8B4513"

COLORS = ["red", "blue", "green"]


root = tk.Tk()

root.title("Moving Cart Animation")

canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="white")

canvas.pack()


# Initial Positions

cart_x = 50

cart_y = 150

angle = 0


def draw_wheel(x, y, r, angle, spokes):

    """Draws a wheel with rotating spokes."""

    wheel = canvas.create_oval(x-r, y-r, x+r, y+r, outline="black", width=2)

    spoke_lines = []

    for i in range(spokes):

        # Calculate spoke angle

        s_angle = angle + (i * (360 / spokes))

        rad = math.radians(s_angle)

        x_end = x + r * math.cos(rad)

        y_end = y + r * math.sin(rad)

        line = canvas.create_line(x, y, x_end, y_end, fill="black")

        spoke_lines.append(line)

    return wheel, spoke_lines


def draw_cart(x, y, color):

    """Draws the brown rectangle and 3 colored boxes."""

    rect = canvas.create_rectangle(x-50, y-30, x+50, y, fill=color, outline="black")

    boxes = []

    box_width = 25

    for i in range(3):

        box_x = x - 40 + (i * (box_width + 5))

        box = canvas.create_rectangle(box_x, y-25, box_x+box_width, y-5, fill=COLORS[i])

        boxes.append(box)

    return rect, boxes


def animate():

    """Main animation loop."""

    global cart_x, angle

    canvas.delete("all")

    

    # Update position and rotation

    cart_x += 2

    angle += 5

    if cart_x > WIDTH + 100:

        cart_x = -100


    # Draw elements

    wheel1, spokes1 = draw_wheel(cart_x - 30, cart_y + 30, WHEEL_RADIUS, angle, SPOKES)

    wheel2, spokes2 = draw_wheel(cart_x + 30, cart_y + 30, WHEEL_RADIUS, angle, SPOKES)

    rect, boxes = draw_cart(cart_x, cart_y, BROWN)

    

    root.after(20, animate)


animate()

root.mainloop()



Tidak ada komentar: