Sabtu, 25 April 2026

Python Animation - Text Falling Down

 




anvas.pack()
        
        self.text = text
        self.chars = []
        self.target_y = 200  # Final resting height
        
        # Create each character at the top (y=0) with horizontal spacing
        for i, char in enumerate(self.text):
            char_id = self.canvas.create_text(
                100 + (i * 20), 0, 
                text=char, fill="white", 
                font=("Arial", 24, "bold")
            )
            # Store ID and a slight delay for staggered start
            self.chars.append({'id': char_id, 'delay': i * 150})
        
        self.animate()

    def animate(self):
        all_finished = True
        for char in self.chars:
            # Get current position of the character
            coords = self.canvas.coords(char['id'])
            
            # Start falling only if delay has passed and hasn't reached target
            if char['delay'] <= 0:
                if coords[1] < self.target_y:
                    self.canvas.move(char['id'], 0, 5) # Move down 5 pixels
                    all_finished = False
            else:
                char['delay'] -= 20 # Countdown staggered start
                all_finished = False

        if not all_finished:
            # Repeat function every 20ms for smooth movement
            self.root.after(20, self.animate)

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Falling Animation")
    app = FallingTextAnimation(root)
    root.mainloop()
Key Animation Concepts
  • Individual Objects: Standard Label widgets cannot move fluidly; using canvas.create_text allows for pixel-perfect positioning.
  • Staggered Start: Each character is assigned a delay value that decreases each frame, ensuring they don't all fall at once.
  • The .after() Loop: This is the standard way to create animations in Tkinter without freezing the main application window

Tidak ada komentar: