Python Tkinter Animation

In this tutorial, we are going to learn about Python Tkinter Animation. Here we will understand how to create animations using Tkinter in python and we will cover different examples related to animation. And we will also cover these topics

  • Python tkinter animation
  • Python tkinter loading animation
  • Python tkinter timer animation
  • Python tkinter matplotlib animation
  • Python tkinter Simple animation
  • Python tkinter Button animation

Python Tkinter Animation

In this section, we are learning about Python Tkinter Animation. By animation, we mean to create an illusion of moment on any object.

In the following code, we have taken two starting positions of “x” & “y” and give a window some width and height and inside that, we made a ball using canvas and to add a moment to the ball just inside a screen space what we created.

Code:

import tkinter
import time
 

Window_Width=800

Window_Height=600

Ball_Start_XPosition = 50

Ball_Start_YPosition = 50

Ball_Radius = 30

Ball_min_movement = 5

Refresh_Sec = 0.01
 

def create_animation_window():
  Window = tkinter.Tk()
  Window.title("Python Guides")

  Window.geometry(f'{Window_Width}x{Window_Height}')
  return Window
 

def create_animation_canvas(Window):
  canvas = tkinter.Canvas(Window)
  canvas.configure(bg="Blue")
  canvas.pack(fill="both", expand=True)
  return canvas
 

def animate_ball(Window, canvas,xinc,yinc):
  ball = canvas.create_oval(Ball_Start_XPosition-Ball_Radius,
            Ball_Start_YPosition-Ball_Radius,
            Ball_Start_XPosition+Ball_Radius,
            Ball_Start_YPosition+Ball_Radius,
            fill="Red", outline="Black", width=4)
  while True:
    canvas.move(ball,xinc,yinc)
    Window.update()
    time.sleep(Refresh_Sec)
    ball_pos = canvas.coords(ball)
    # unpack array to variables
    al,bl,ar,br = ball_pos
    if al < abs(xinc) or ar > Window_Width-abs(xinc):
      xinc = -xinc
    if bl < abs(yinc) or br > Window_Height-abs(yinc):
      yinc = -yinc
 

Animation_Window = create_animation_window()
Animation_canvas = create_animation_canvas(Animation_Window)
animate_ball(Animation_Window,Animation_canvas, Ball_min_movement, Ball_min_movement)

Here are some of the main highlights of the given code.

  • Canvas.create_oval() is used to give the Oval shape to the ball.
  • Canvas.move() = Motion of the ball
  • time.sleep() it suspends execution for a given number of seconds.

Output:

After running the above code, we can see the following output in which a ball is changing its position. The ball is going up and down and showing an example of animation.

Python Tkinter Animation
Output

Read: Python Tkinter Editor

Python Tkinter Loading Animation

In this section, we are learning about python Tkinter loading animation. By loading, we mean the processing of any page or loading any data over the internet.

Code:

In the following code, we made a processing bar that runs after clicking on the run button and it shows us loading in page.

  • Progressbar() is used to display the loading bar.
  • mode=’determinate’ shows an indicator that moves starting point to the ending point.
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()

Output:

After running the following code, we get the following output which shows us how loading is done in python Tkinter. Here in this, we can see when a user clicks on the “Run” button a loading of data is started on a page.

Python Tkinter Animation1
Output

Read: Python Tkinter Table Tutorial

Python tkinter timer animation

In this section, we are learning about python Tkinter 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.

Code:

In the following code, we imported a time library that used to define hours, minutes & seconds. Here a user is setting up some time counter which does works like giving an alert after time is up.

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()

Output:

After running the above code, we can see a user has set some timer for few seconds and it is working as per an order of timer.

Python Tkinter Countdown
Output

Read: How to Create a Snake Game in Python Tkinter

Python tkinter matplotlib animation

Matplotlib is a Python library used for plotting graphs. It is an open-source library we can use freely. It is written in Python Language. Here is a tool that is specifically used to work on the function of matplotlib named “MATLAB“. In here Numpy is its numerical mathematical extension used to represent graphical values of its axis.

Code:

  • plt.bar() is used to represent that the bar graph is to be plotted by using X-axis and Y-axis values.
  • ptl.xlabel() is used to represent the x-axis.
  • plt.ylabel() is used to represent the y-axis.
  • plt.title() is used for giving the title to the bar graph.
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()

Output:

After running the following code, we see the bar graph is generated. Here are the months and sales amount variables that represent the x-axis and y-axis values of data points and the bar are representing the total sale in a month. In the following gif, we can see the x-axis and y-axis are giving some values when we hover the mouse on a bar.

Python Tkinter Matplotlib Animation
Output

Read: Python Tkinter Image

Python tkinter Simple animation

In the following section, we are learning about python Tkinter’s simple animation. In this, we have made a button through which clicking on that button changes the background color.

Code:

√Źn the following code 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” on that which changes the color of the background randomly.

  • random.choice() return a list with randomly select color.
  • ws.title is used for giving a title to the window.
  • Button() is used to run the command to generate random colors in this.
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()

Output:

After running the above code, we can run a simple animation with help of python Tkinter.

simple animation
Simple animation

Read: Python Tkinter Colors

Python tkinter Button animation

in this section, we are learning about the Python Tkinter animation button.

We here use button animation as a feature that we can use in any gaming application or any similar application to turn on or to turn off that function. Here button is working like a normal switch which we used in our daily life to have access to switch on the light of the house.

Code:

from tkinter import *
ws = Tk()
ws.title("Python Guides")

def convert():
    if(a1['state']==NORMAL):
        a1["state"] = DISABLED
        a2["text"]="enable"
    elif (a1['state']==DISABLED):
        a1["state"]=NORMAL
        a2["text"]="disable"

#--Buttons
a1=Button(ws, text="button")
a1.config(height = 8, width = 9)
a1.grid(row=0, column=0)    
a2 = Button(text="disable", command=convert)
a2.grid(row=0,column=1)
ws.mainloop()

In the above code, first, we have created a button object “a1” and then, we are using the IF statement to check the state of the button. In the end, we are using the state to change the behavior of the button to get the desired result.

Output:

After running the following code, we get the following output in which we see when we click on them the button will be disabled. And when we click on them again, the button will get enabled.

Python Tkinter Button Animation
Output

You may also like to read the following articles.

So, in this tutorial, we discuss Python Tkinter Animation. Here is the list of the examples that we have covered.

  • Python Tkinter animation
  • Python Tkinter animation tutorial
  • Python Tkinter loading animation
  • Python Tkinter timer animation
  • Python Tkinter matplotlib animation
  • Python Tkinter Simple animation
  • Python Tkinter Button animation