Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 40 ยท Canvas and Drawing

Tkinter Animation with after(): Moving Items on a Canvas

Animate a Tkinter canvas without freezing the window: use after() instead of sleep, build a frame loop with delta time, bounce a ball and start or stop safely.

Animation means changing something a little bit, many times a second. In most languages you would write a while True loop that updates and sleeps. In Tkinter that loop is a trap: the GUI only redraws and responds to clicks while the event loop (mainloop) is running, so a long while loop or a time.sleep() freezes the window.

The Tkinter answer is after(): you ask the event loop to call your function again later. Each call does a small amount of work and returns, so the window stays responsive. This lesson builds a bouncing ball, explains timing and start/stop control, and models the scheduler in plain Python so you can see the order of events. The Tkinter code is read-only (it needs a display).

Why while and sleep freeze the window

Python
# DO NOT DO THIS
for i in range(100):
    canvas.move(ball, 2, 0)
    time.sleep(0.02)

You will not see 100 smooth steps. The window stays blank or frozen for two seconds, and then jumps to the final position, because Tkinter never got a chance to repaint between the steps. The same happens with long calculations or slow network calls inside a button handler.

The after() loop

Python
import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=240, bg="black", highlightthickness=0)
canvas.pack()

ball = canvas.create_oval(20, 100, 60, 140, fill="orange", outline="")
dx, dy = 4, 3

def tick():
    global dx, dy
    canvas.move(ball, dx, dy)
    x1, y1, x2, y2 = canvas.coords(ball)
    if x1 <= 0 or x2 >= 400:
        dx = -dx
    if y1 <= 0 or y2 >= 240:
        dy = -dy
    root.after(16, tick)        # schedule the next frame in about 16 ms

tick()
root.mainloop()

A black canvas with an orange ball that glides diagonally and bounces off all four walls appears. root.after(16, tick) means "call tick in about 16 milliseconds" (roughly 60 frames per second). The call returns immediately; mainloop handles redraws, clicks and the timer in between. after(ms, func, *args) can also pass arguments to the function.

Three rules for after loops:

  1. Do a little, then return. Never loop inside a callback.
  2. Schedule the next call yourself. A callback runs once; to repeat, call after again at the end.
  3. The delay is a minimum. If the event loop is busy, the callback is late.

Stopping and starting

after returns a token you can pass to after_cancel. Save it so a Start/Stop button can control the loop:

Python
job = None
running = False

def tick():
    global job
    step()                              # move things
    job = root.after(16, tick)

def start():
    global running, job
    if job is None:                     # avoid starting a second loop
        job = root.after(0, tick)

def stop():
    global job
    if job is not None:
        root.after_cancel(job)
        job = None

The easy bug is pressing Start twice, which creates two parallel loops and doubles the speed. Guard with if job is None as above. The other easy bug is cancelling with the wrong id, which leaves the loop running.

Time-based movement

Moving "4 pixels per frame" ties the speed to the frame rate. If a frame is late, the animation slows down. A more robust approach is to measure the time between frames (delta time) and move by speed multiplied by that time:

Python
import time

last = time.perf_counter()
speed = 240            # pixels per second

def tick():
    global last
    now = time.perf_counter()
    dt = now - last
    last = now
    canvas.move(ball, speed * dt, 0)
    root.after(16, tick)

On a fast machine or a slow one, the ball now covers about 240 pixels each second. Tkinter does not guarantee exact timing, and its canvas can only render about as fast as the machine allows, so measuring is the only reliable method.

One animation frame

Update Change positions
Draw move or itemconfig
Schedule root.after(16, tick)
Return Event loop handles input

Never block inside a frame.

1 / 2

Separating the model from the drawing

Mixing physics and drawing in one function gets hard to test. Keep the numbers in a plain class and let the callback only draw them:

Python
class Ball:
    def __init__(self, x, y, r, dx, dy):
        self.x, self.y, self.r, self.dx, self.dy = x, y, r, dx, dy

    def step(self, width, height):
        self.x += self.dx
        self.y += self.dy
        if self.x - self.r <= 0 or self.x + self.r >= width:
            self.dx = -self.dx
        if self.y - self.r <= 0 or self.y + self.r >= height:
            self.dy = -self.dy

The drawing function then calls canvas.coords(item, x - r, y - r, x + r, y + r). The block below runs the model with no GUI. It also shows a subtle detail: when a ball is already past the wall, flipping its speed is not enough, so we clamp the position to stay inside.

Python Stand-in: the bouncing ball model without a window

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can see the ball reverse direction when it touches a wall, and never leave the 100 by 80 area.

Modeling the after() scheduler

To really understand why sleep freezes things, it helps to see an event loop. The stand-in below is a tiny version of what mainloop does with timers: it keeps a queue of (time, callback) pairs and runs whichever is due next. A callback that "sleeps" blocks everything behind it; one that re-schedules itself lets other events slip in.

Python Stand-in: a miniature event loop with after()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first run handles the click at 40 ms, between two animation frames. In the second run the click is stuck behind the slow job and handled at 500 ms. That is exactly what a frozen window feels like.

Updating the display manually

root.update() and root.update_idletasks() force a redraw inside a long loop. They are a workaround, not a design: update() re-enters the event loop, which can run other callbacks (including the same button handler) in the middle of your function. Prefer after. For genuinely long work, use a worker thread, covered in Threads and Background Work.

Common mistakes

  • Using time.sleep or a long while loop in a callback.
  • Writing root.after(16, tick()): the parentheses call tick immediately and pass its return value (None).
  • Starting several loops by pressing a button repeatedly.
  • Forgetting to cancel pending after callbacks when a window is destroyed, which can raise TclError for an item that no longer exists.
  • Creating new canvas items every frame instead of moving existing ones; the canvas fills up and slows down.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does time.sleep(1) inside a button handler freeze a Tkinter window?

    Tkinter handles everything in one thread; a blocking callback blocks redraws and clicks.
  2. 2. What is wrong with root.after(100, tick())?

    Pass the function itself: root.after(100, tick).
  3. 3. How do you stop a repeating after loop?

    after returns a token; after_cancel(token) removes the pending call.
  4. 4. Why use delta time (time between frames) for movement?

    Moving by speed times elapsed seconds keeps the animation speed independent of the frame rate.

Summary

  • Never block the event loop; schedule work with after.
  • A frame callback updates state, draws, and re-schedules itself.
  • Save the after token to cancel; guard against starting twice.
  • Use delta time for stable speed and keep the model separate from drawing.
  • update() is a workaround; threads are the tool for long jobs.

Next: Canvas Mouse Drawing and Hit Testing