Home >Backend Development >Python Tutorial >How Can I Use Tkinter's `after` Method to Create a Simple Animation?

How Can I Use Tkinter's `after` Method to Create a Simple Animation?

Linda Hamilton
Linda HamiltonOriginal
2024-12-14 07:57:15475browse

How Can I Use Tkinter's `after` Method to Create a Simple Animation?

Tkinter — Executing Functions over Time

In event-driven programming, the application can schedule functions to run at specified times. Tkinter widgets have a after method that can be used to execute a function after a certain number of milliseconds has passed.

To make a rectangle blink three times, we need to write a function that changes the rectangle's fill color and schedule it to run three times at 1-second intervals. Here's how we can do it:

import tkinter as tk
from time import sleep

def blink(rect, canvas):
    for i in range(3):
        canvas.itemconfigure(rect, fill="red")
        sleep(1)
        canvas.itemconfigure(rect, fill="white")
        sleep(1)

root = tk.Tk()
fr = tk.Frame(root)
fr.pack()
canv = tk.Canvas(fr, height=100, width=100)
canv.pack()
rect = canv.create_rectangle(25, 25, 75, 75, fill="white")

# Schedule blink function to run
canv.after(1000, blink, rect, canv)
canv.after(2000, blink, rect, canv)
canv.after(3000, blink, rect, canv)

root.mainloop()

This code will create a rectangle and schedule it to change its fill color from white to red and back, three times at 1-second intervals.

The after method can also be used to schedule a function to run after a specified number of milliseconds, or it can be used to schedule a function to run repeatedly at a specified interval. This can be useful for creating animations or for periodically checking for new data.

The above is the detailed content of How Can I Use Tkinter's `after` Method to Create a Simple Animation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn