Create Basic Animations with Python Modules

Python’s modules make it relatively easy to create shapes, or display graphics, and animate them accordingly. Animation, though, can be a tricky element to get right in code. There are so many different ways of achieving the same end result. Here’s one such example.

Lights, Camera, Action

The Tkinter module is an ideal starting point to learning animation within Python. Naturally, there are better custom modules out there, but Tkinter does the job well enough to get a grasp on what’s needed.

Step 1 – Let’s make a bouncing ball animation. First, we will need to create a canvas (window), and the ball to animate:

from tkinter import *
import time

gui = Tk()
gui.title("Pi Animation")
canvas = Canvas(gui, width=800,height=600,bg='white')

ball1 = canvas.create_oval(5,5,60,60, fill='red')


Step 2 – Save and Run the code. You will see a blank window appear, with a red ball sitting in the upper left corner of the window. While great, it’s not very animated. Let’s add the following code:

a = 5
b = 5

for x in range(0,100):

Step 3 – Insert the new code between the ball1 = canvas.create_oval(5,5,60,60, fill=’red’) line, and the gui.mainloop() line. Save it and Run. You will now see the ball move from the top left corner of the animation window, down to the bottom right corner. You can alter the speed in which the ball traverses the window by altering the time.sleep(.01) line. Try (.05).

Step 4 – The canvas.move(ball1,a,b) line is the part that moves the ball from one corner to the other; obviously with both a and b equalling 5. We can change things around a bit already, such as the size and colour of the ball, with the line:

ball1 = canvas.create_oval(5,5,60,60, fill='red')

and we can change the values of a and b to something else.

Step 5 – Let’s see if we can animate the ball so that it bounces around the window until you close the program.

xa = 5
ya = 10

while True:
 if pos[3] >=600 or pos[1] <=0:
  ya = -ya
 if pos[2] >=800 or pos[0] <=0:
  xa = -xa

Step 6 – Remove the code you entered in Step 2, and insert the code from Step 5 in its place; again, between the ball1 = canvas.create_oval(5,5,60,60, fill=’red’), and the gui.mainloop() lines. Save the code, and Run it as normal. If you’ve entered the code correctly, then you will see the red ball bounce off the edges of the window until you close the program.

Step 7 – The bouncing animation takes place within the While True loop. First, we have the values of xa and xy before the loop, both of 5 and 10. The pos=canvas.coords(ball1) line takes the value of the ball’s location in the window. When it reaches the limits of the window, 800 or 600, it will make the values negative; moving the ball around the screen.

Step 8 – Pygame, however is a much better module at producing higher-end animations. Begin by creating a New File, and entering:

import pygame
from random import randrange
MAX_STARS  = 250
def init_stars(screen):
  """ Create the starfield """
  global stars
  stars = []
  for i in range(MAX_STARS):
    # A star is represented as a list with this format: [X,Y]
    star = [randrange(0,screen.get_width() - 1),
            randrange(0,screen.get_height() - 1)]
def move_and_draw_stars(screen):
  """ Move and draw the stars """
  global stars
  for star in stars:
    star[1] += STAR_SPEED
    if star[1] >= screen.get_height():
      star[1] = 0
      star[0] = randrange(0,639)

Step 9 – Now add the following:

def main():
  screen = pygame.display.set_mode((640,480))
  pygame.display.set_caption("Starfield Simulation")
  clock = pygame.time.Clock()
  while True:
    # Lock the framerate at 50 FPS
    # Handle events
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
if __name__ == "__main__":

Step 10 – Save and Run the code. You will agree that the simulated starfield code looks quite impressive. bImagine this as the beginning of some game code, or even the start to a presentation? Using a combination of Pygame and Tkinter, your Python animations will look fantastic.

Find more guides like this in…

Russ Ware

Russ has been testing, reviewing and writing guides for tech since the heady days of Windows 95 and the Sega Saturn. A self-confessed (and proud) geek about all things tech, if it has LED's, a screen, beeps or has source code, Russ will want to master it (and very likely take it apart to see how it works...)

Related Articles

Back to top button