Sabtu, 11 April 2026

Python Animation Text Random Position

 



import tkinter as tk

import random


def start_animation():

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

    # Create the text item on the canvas

    text_id = canvas.create_text(

        400, 300, text="hello", font=("Arial", 24), fill="blue"

    )

    # Start the animation loop

    animate_text(text_id)


def animate_text(text_id):

    """Moves the text to a random position."""

    # Get canvas dimensions

    c_width = canvas.winfo_width()

    c_height = canvas.winfo_height()

    

    # Calculate new random position

    x = random.randint(50, c_width - 50)

    y = random.randint(50, c_height - 50)

    

    # Move the text to the new position

    canvas.coords(text_id, x, y)

    

    # Repeat after 500ms

    root.after(500, lambda: animate_text(text_id))


# Setup the main window

root = tk.Tk()

root.title("Animated Text")


# Create Canvas

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

canvas.pack()


# Create Button

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

btn.pack()


root.mainloop()

Tidak ada komentar: