Sabtu, 11 April 2026

Python Animation Box Moving Forward with Button Click Start Moving

 




import tkinter as tk

import math


def start_animation():

    """Initializes and starts the animation loop."""

    global running

    if not running:

        running = True

        animate()


def animate():

    """Handles the movement and rotation of objects."""

    global rect_pos, wheel1_angle, wheel2_angle, running

    

    if running:

        # Move rectangle forward (right)

        rect_pos += 5

        if rect_pos > 800: rect_pos = -150 # Reset if off-screen

        

        # Redraw components

        canvas.delete("all")

        

        # Draw Brown Rectangle

        canvas.create_rectangle(rect_pos, 100, rect_pos+150, 200, fill="brown", tags="car")

        

        # Draw Wheels (10 spokes)

        for center_x in [rect_pos + 30, rect_pos + 120]:

            center_y = 200

            radius = 25

            canvas.create_oval(center_x-radius, center_y-radius, center_x+radius, center_y+radius, fill="black")

            

            # Draw Spokes

            for i in range(10):

                angle = wheel1_angle + (i * 2 * math.pi / 10)

                end_x = center_x + radius * math.cos(angle)

                end_y = center_y + radius * math.sin(angle)

                canvas.create_line(center_x, center_y, end_x, end_y, fill="white", width=2)

        

        # Rotate Wheels

        wheel1_angle += 0.1

        

        # Loop animation

        root.after(20, animate)


# Setup Window

root = tk.Tk()

root.title("Moving Car Animation")

canvas = tk.Canvas(root, width=800, height=300, bg="white")

canvas.pack()


# Variables

rect_pos = 0

wheel1_angle = 0

running = False


# Button

btn = tk.Button(root, text="Start Moving", command=start_animation)

btn.pack()


root.mainloop()

Tidak ada komentar: