How to Create Animations in Python with Tkinter?

In this tutorial, I will explain how to create animations in Python with Tkinter library. As a Python developer based in the USA, I’ve faced the challenge of creating visually appealing user interfaces that attract users. Through my experience, I have discovered the uses of Tkinter animations, and I will share my findings with you with examples.

Create Animations in Python with Tkinter

Let us see some examples of creating animations in Python with Tkinter.

Read How to Create Scrollable Frames with Python Tkinter?

1. Hover Animation

To begin creating animations with Python Tkinter, let’s start with a simple example. We’ll create an animated button that changes color when hovered over. Here’s the code:

import tkinter as tk

class AnimatedButton(tk.Button):
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)
        self.default_color = self.cget("background")
        self.hover_color = "lightblue"
        self.bind("<Enter>", self.on_enter)
        self.bind("<Leave>", self.on_leave)

    def on_enter(self, event):
        self.configure(background=self.hover_color)

    def on_leave(self, event):
        self.configure(background=self.default_color)

root = tk.Tk()
button = AnimatedButton(root, text="Click Me!", font=("Arial", 16))
button.pack(pady=20)
root.mainloop()

You can look at the output in the screenshot below.

Create Animations in Python with Tkinter

In this example, we create a custom AnimatedButton class that inherits from tk.Button. We define the default and hover colors and bind the <Enter> and <Leave> events to the on_enter and on_leave methods, respectively. These methods update the button’s background color when the mouse enters or leaves the button.

Check out How to Display Images in Python Tkinter?

2. Loading Animation

Loading means the processing of any page or loading any data over the internet. we made a processing bar that runs after clicking on the run button and it shows us the loading on the page.

from tkinter import *
from tkinter.ttk import *

ws=Tk()
Progress_Bar=Progressbar(ws,orient=HORIZONTAL,length=250,mode='determinate')

def Slide():
    import time
    Progress_Bar['value']=20
    ws.update_idletasks()
    time.sleep(1)
    Progress_Bar['value']=50
    ws.update_idletasks()
    time.sleep(1)
    Progress_Bar['value']=80
    ws.update_idletasks()
    time.sleep(1)
    Progress_Bar['value']=100

Progress_Bar.pack()
Button(ws,text='Run',command=Slide).pack(pady=10)
mainloop()

You can look at the output in the screenshot below.

How to Create Animations in Python with Tkinter

We can see when a user clicks on the “Run” button a loading of data is started on a page.

Read How to Use Colors in Python Tkinter?

3. Timer Animation

By timer, we mean to set any time count for our alert to remember our task. The best example to understand about the timer is an alarm which we use in our common routine.

import time
from tkinter import *
from tkinter import messagebox

ws = Tk()
ws.geometry("300x300")
ws.title("Python Guides")

Hour=StringVar()
Minute=StringVar()
Second=StringVar()

Hour.set("00")
Minute.set("00")
Second.set("00")

Hour_entry= Entry(ws, width=3, font=("Arial",18,""),textvariable=Hour)
Hour_entry.place(x=80,y=20)
Minute_entry= Entry(ws, width=3, font=("Arial",18,""),textvariable=Minute)			
Minute_entry.place(x=130,y=20)
Second_entry= Entry(ws, width=3, font=("Arial",18,""),textvariable=Second)
Second_entry.place(x=180,y=20)

def OK():
	try:
		temp = int(Hour.get())*3600 + int(Minute.get())*60 + int(Second.get())
	except:
		print("Please Input The Correct Value")
	while temp >-1:
		Mins,Secs = divmod(temp,60)
		Hours=0
		if Mins >60:	
		Hours, Mins = divmod(Mins, 60)	
		Hour.set("{0:2d}".format(Hours))
		Minute.set("{0:2d}".format(Mins))
		Second.set("{0:2d}".format(Secs))		
		ws.update()
		time.sleep(1)	
		if (temp == 0):
			messagebox.showinfo("Time Countdown", "Time up ")		
		temp -= 1
button = Button(ws, text=' countdown', bd='5',
			command= OK)
button.place(x = 100,y = 110)

ws.mainloop()

You can look at the output in the screenshot below.

Create Animations in Python with Tkinter timer animation

We can see a user has set some timer for a few minutes and it is working as per an order of timer.

4. matplotlib Animation

Matplotlib is a Python library used for plotting graphs. Here is a tool that is specifically used to work on the function of Matplotlib named “MATLAB”. Here Numpy is its numerical mathematical extension used to represent the graphical values of its axis.

from matplotlib import pyplot as plt
plt.bar([0.25,1.25,2.25,3.25,4.25],[50000,40000,70000,80000,200000],label="MAC",color='r',width=.4)
plt.bar([0.75,1.75,2.75,3.75,4.75],[80000,20000,20000,50000,60000],label="Dominos",color='b',width=.4)
plt.legend(loc='upper right')
plt.xlabel('Months')
plt.ylabel('Sales Amount')
plt.title('Information')
plt.show()

You can look at the output in the screenshot below.

Create Animations in Python with Tkinter graph

Here are the months and sales amount variables that represent the x-axis and y-axis values of data points and the bar represents the total sales in a month. we can see x-axis and the y-axis gives some values when we hover the mouse on a bar.

Check out How to Create a Text Box in Python Tkinter?

5. Color Animation

We use a random library that gives a random choice to our options and at the top, we added a button with the text “click me” which changes the color of the background randomly.

from tkinter import *
import random

def gen_color():
    ws.configure(background=random.choice(["black", "red" , "green" , "blue"]))
    
ws =Tk()
ws.title("Python Guides")
ws.geometry('500x500')

button=Button(ws,text='Click Me',command = gen_color).pack()
ws.mainloop()

You can look at the output in the screenshot below.

Create Animations in Python with Tkinter color animation

Read How to Create Labels in Python with Tkinter?

Create Complex Animations

For more complex animations, we can leverage the canvas widget in Tkinter. The canvas allows us to draw shapes, lines, and images and provides methods to animate them. Let’s create an animated bouncing ball:

import tkinter as tk

class BouncingBall:
    def __init__(self, canvas, x, y, diameter, xVelocity, yVelocity, color):
        self.canvas = canvas
        self.image = canvas.create_oval(x, y, x + diameter, y + diameter, fill=color)
        self.xVelocity = xVelocity
        self.yVelocity = yVelocity

    def move(self):
        coordinates = self.canvas.coords(self.image)
        if coordinates[2] >= self.canvas.winfo_width() or coordinates[0] < 0:
            self.xVelocity = -self.xVelocity
        if coordinates[3] >= self.canvas.winfo_height() or coordinates[1] < 0:
            self.yVelocity = -self.yVelocity

        self.canvas.move(self.image, self.xVelocity, self.yVelocity)

root = tk.Tk()
WIDTH, HEIGHT = 800, 600
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()

ball = BouncingBall(canvas, 10, 10, 50, 1, 1, "red")

while True:
    ball.move()
    root.update()
    root.after(10)

root.mainloop()

In this example, we create a BouncingBall class that represents a ball on the canvas. The move method updates the ball’s position based on its velocity and handles the bouncing logic when the ball reaches the canvas boundaries. We continuously call the move method using root.after to create the animation effect.

Read How to Create Buttons in Python with Tkinter?

Animate Text

Tkinter also allows us to create animated text effects. Let’s create a scrolling text animation:

import tkinter as tk

def scroll_text():
    text.configure(state=tk.NORMAL)
    text.delete(1.0, 2.0)
    text.insert(tk.END, message[-1])
    message.pop(0)
    message.append(message[0])
    text.configure(state=tk.DISABLED)
    root.after(100, scroll_text)

root = tk.Tk()
message = list("Hello, John! Welcome to Tkinter Animations.")
text = tk.Text(root, height=1, width=30, font=("Arial", 16))
text.pack(pady=20)

scroll_text()
root.mainloop()

In this example, we define a scroll_text function that updates the text widget by removing the first character and appending it to the end, creating a scrolling effect. We use root.after to repeatedly call the scroll_text function, creating a continuous animation.

Check out How to Create a Menu Bar in Tkinter?

Animate Widgets

In addition to animating shapes and text, we can also animate Tkinter widgets themselves. Let’s create an animated sidebar that expands and collapses when clicked:

import tkinter as tk

def toggle_sidebar():
    if sidebar.winfo_width() == 50:
        sidebar.configure(width=200)
    else:
        sidebar.configure(width=50)

root = tk.Tk()
root.geometry("800x600")

sidebar = tk.Frame(root, width=50, bg="lightblue")
sidebar.pack(side=tk.LEFT, fill=tk.Y)

toggle_button = tk.Button(sidebar, text="☰", command=toggle_sidebar)
toggle_button.pack(pady=10)

content = tk.Frame(root, bg="white")
content.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

root.mainloop()

In this example, we create a sidebar frame with a fixed width and a toggle button. When the button is clicked, the toggle_sidebar function is called, which expands or collapses the sidebar by adjusting its width. This creates a smooth animation effect.

Read How to Use Tkinter Entry Widget in Python?

Conclusion

In this tutorial, I helped you to learn how to create animations in Python with Tkinter. I covered various animation styles like hover animation, loading animation, timer animation, matplotlib animation and color animation. I also discussed how to create complex animations, animation text, and animation widgets.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.