In this video I’ll show you how to Animate Widgets with Tkinter and Python.

Tkinter doesn’t come with a built in animation function, instead we’re going to have to hack together a solution using the .after() function and a series of counters and .config() functions.

We can also move the position of a widget by using the .pack_configure() or .grid_configure() functions.

Tkinter canvas allows you to move things fairly easily, but for regular widgets; this method gets the job done!

Python Code: anim.py
(Github Code)

from tkinter import *

root = Tk()
root.title('Codemy.com - Simple Button Animation')
root.iconbitmap('c:/gui/codemy.ico')
root.geometry("400x300")

#define some variables
count = 0
size = 26
pos = 100

# Contract the button
def contract():
	global count, size, pos
	if count <= 10 and count > 0:
		size -= 2
		# Configure button font size
		my_button.config(font=("Helvetica", size))
		# Change button position
		my_button.pack_configure(pady=pos)
		# decrease the count by 1
		count -= 1
		pos -= 20
		# Set a timer
		root.after(100, contract)

# Expand the button
def expand():
	global count, size, pos
	if count < 10:
		size += 2 
		# Configure button font size
		my_button.config(font=("Helvetica", size))
		# Change button position
		my_button.pack_configure(pady=pos)
		# Increase the count by 1 
		count += 1
		pos += 20
		# Set the timer
		root.after(100, expand)

	elif count == 10:
		contract()


# Create a button
my_button = Button(root, 
	text="Click Me!", 
	command=expand,
	font=("Helvetica", 24),
	fg="red")
my_button.pack(pady=100)


root.mainloop()

John Elder

John is the CEO of Codemy.com where he teaches over 100,000 students how to code! He founded one of the Internet's earliest advertising networks and sold it to a publicly company at the height of the first dot com boom. After that he developed the award-winning Submission-Spider search engine submission software that's been used by over 3 million individuals, businesses, and governments in over 42 countries. He's written several Amazon #1 best selling books on coding, and runs a popular Youtube coding channel.

View all posts

Add comment

Your email address will not be published. Required fields are marked *

John Elder

John is the CEO of Codemy.com where he teaches over 100,000 students how to code! He founded one of the Internet's earliest advertising networks and sold it to a publicly company at the height of...