Jumat, 10 April 2026

Python Animation Cart Animation Moving Forward Carrying 3 stacked Box

 



import tkinter as tk

import math


# Setup canvas

root = tk.Tk()

root.title("Moving Cart Animation")

canvas = tk.Canvas(root, width=800, height=400, bg='white')

canvas.pack()


# Cart parameters

cart_x, cart_y = 50, 250

wheel_radius = 20

spokes = 10

angle = 0


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

    # Wheel rim

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

    spoke_lines = []

    # Spokes

    for i in range(num_spokes):

        spoke_angle = angle + (i * 2 * math.pi / num_spokes)

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

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

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

    return wheel, spoke_lines


def animate():

    global cart_x, angle

    canvas.delete("cart") # Clear previous frame


    # Update positions

    cart_x += 5

    angle += 0.2

    if cart_x > 850: cart_x = -100


    # Draw cart body (Brown Rectangle)

    body = canvas.create_rectangle(cart_x, cart_y-40, cart_x+100, cart_y, 


fill="#8B4513", tags="cart")

    

    # Draw boxes

    box1 = canvas.create_rectangle(cart_x+10, cart_y-60, cart_x+30, cart_y-40, 


fill="red", tags="cart")

    box2 = canvas.create_rectangle(cart_x+40, cart_y-60, cart_x+60, cart_y-40, 


fill="blue", tags="cart")

    box3 = canvas.create_rectangle(cart_x+25, cart_y-80, cart_x+45, cart_y-60, 


fill="green", tags="cart")


    # Draw wheels with spokes

    w1_rim, w1_spokes = draw_wheel(cart_x+25, cart_y, wheel_radius, angle, 


spokes)

    w2_rim, w2_spokes = draw_wheel(cart_x+75, cart_y, wheel_radius, angle, 


spokes)

    

    # Add all parts to tags for easy deletion

    for item in [w1_rim, w2_rim] + w1_spokes + w2_spokes:

        canvas.addtag_withtag("cart", item)


    canvas.after(30, animate)


animate()

root.mainloop()

Tidak ada komentar: