Tk canvas animation
last modified November 24, 2026 Tcl 8.6
A Tk canvas is a widget that holds items: rectangles, ovals, lines, text and
images, each with its own identifier and coordinates. Because those
coordinates can be changed at any time, a canvas is also the simplest place
to build an animation. A procedure moves the items a little, Tk redraws them,
and after calls the procedure again a few milliseconds later.
This article starts with a still scene, then moves items, adds a timer, makes a ball bounce, steers it with the keyboard, detects collisions and finishes with a photo image sprite that can be stopped and restarted.
A static canvas first
Before anything moves, the scene is built from ordinary items. Each
create subcommand takes coordinates and options and returns an
integer identifier. The script creates four items and inspects them.
package require Tk
wm title . "Static canvas"
canvas .c -width 300 -height 160 -background white
pack .c -padx 8 -pady 8
.c create rectangle 20 60 80 100 -fill #3a6ea5 -outline ""
.c create oval 140 40 220 120 -fill gold -outline ""
.c create line 20 140 280 140 -fill gray70 -width 2
.c create text 150 20 -text "A static scene" -fill #1f2933
puts "items: [.c find all]"
puts "types: [.c type 1] [.c type 2] [.c type 3] [.c type 4]"
puts "oval bbox: [.c bbox 2]"
after 500 {destroy .}
find all returns the identifiers in stacking order, and
type maps an identifier to its item class. Rectangles and ovals
are given by two opposite corners, a line by its end points, and text by a
single anchor point. The bounding box of the oval matches the coordinates
used to create it.
$ wish static.tcl items: 1 2 3 4 types: rectangle oval line text oval bbox: 140 40 220 120
Moving items with move and coords
move shifts an item by a relative amount, and
coords sets its coordinates absolutely. move is the
natural choice for animation because the current position is kept by the
canvas; coords is used when the exact position is known.
package require Tk
canvas .c -width 300 -height 160 -background white
pack .c
set ball [.c create oval 10 10 50 50 -fill navy -outline ""]
puts "start: [.c coords $ball]"
.c move $ball 40 20
puts "moved: [.c coords $ball]"
.c coords $ball 200 80 240 120
puts "placed: [.c coords $ball]"
set coords [.c coords $ball]
set cx [expr {([lindex $coords 0] + [lindex $coords 2]) / 2}]
set cy [expr {([lindex $coords 1] + [lindex $coords 3]) / 2}]
puts "centre: $cx $cy"
puts "bbox: [.c bbox $ball]"
destroy .
Moving by 40 and 20 changes both corners by the same amount, and setting the
coordinates replaces them completely. Coordinates are floating point numbers
even when whole pixels are used, which is why the output shows
10.0 rather than 10. The centre is the average of
the two corners, and the bounding box rounds the values to integers.
$ wish move.tcl start: 10.0 10.0 50.0 50.0 moved: 50.0 30.0 90.0 70.0 placed: 200.0 80.0 240.0 120.0 centre: 220.0 100.0 bbox: 200 80 240 120
Animating with after
An animation is a loop that must not block the event loop, so it cannot be a
while loop. Instead, a procedure moves the item and schedules
itself with after, which returns immediately and lets Tk process
other events. The next script moves an oval across the canvas in 24 steps.
package require Tk
canvas .c -width 300 -height 120 -background white
pack .c
set x 10
set ball [.c create oval $x 40 [expr {$x + 40}] 80 -fill #3a6ea5 -outline ""]
proc step {} {
global x ball
.c move $ball 10 0
incr x 10
if {$x % 50 == 0} {
puts "x = $x"
}
if {$x < 250} {
after 20 step
} else {
puts "finished at [.c coords $ball]"
destroy .
}
}
after 20 step
The global variable x tracks the left edge so the procedure
knows when to stop. A 20 millisecond delay gives roughly fifty frames per
second, although Tk does not guarantee the interval: a busy callback makes
the next frame late. The Tcl after article explains
the timer model in detail.
$ wish animate.tcl x = 50 x = 100 x = 150 x = 200 x = 250 finished at 250.0 40.0 290.0 80.0
A bouncing ball
A bouncing ball needs a position and a velocity. Each tick adds the velocity to the position, and when the ball reaches a wall the sign of the matching velocity component is reversed. The script counts steps so that it can stop by itself after a few bounces.
package require Tk
canvas .c -width 300 -height 200 -background white
pack .c
set r 20
set x 40
set y 100
set dx 9
set dy 7
set steps 0
set ball [.c create oval [expr {$x-$r}] [expr {$y-$r}] \
[expr {$x+$r}] [expr {$y+$r}] -fill #c07000 -outline ""]
proc tick {} {
global x y dx dy r ball steps
incr x $dx
incr y $dy
incr steps
if {$x - $r <= 0 || $x + $r >= 300} {
set dx [expr {-$dx}]
puts "wall on x at step $steps, x = $x"
}
if {$y - $r <= 0 || $y + $r >= 200} {
set dy [expr {-$dy}]
puts "wall on y at step $steps, y = $y"
}
.c coords $ball [expr {$x-$r}] [expr {$y-$r}] \
[expr {$x+$r}] [expr {$y+$r}]
if {$steps < 55} {
after 20 tick
} else {
puts "last centre: $x $y"
destroy .
}
}
after 20 tick
The ball is stored as a centre point and a radius, which makes the wall test
readable: the left wall is hit when x - r reaches zero. Because
the position is updated before the test, the ball can pass a few pixels into
the wall on a fast frame, and it leaves the wall from that slightly deeper
point. The printed step numbers show where each bounce happened.
$ wish bounce.tcl wall on y at step 12, y = 184 wall on x at step 27, x = 283 wall on y at step 36, y = 16 last centre: 31 149
Keyboard control
A canvas can react to key presses through bindings on the widget. Tk delivers
key events to the widget that has the keyboard focus, so the script must call
focus -force and the window must be mapped. Each arrow key calls
a procedure with a fixed offset.
package require Tk
canvas .c -width 300 -height 160 -background white
pack .c
set x 150
set y 80
set ball [.c create oval [expr {$x-20}] [expr {$y-20}] \
[expr {$x+20}] [expr {$y+20}] -fill navy -outline ""]
proc move_by {dx dy} {
global x y ball
set x [expr {$x + $dx}]
set y [expr {$y + $dy}]
.c coords $ball [expr {$x-20}] [expr {$y-20}] \
[expr {$x+20}] [expr {$y+20}]
puts "centre: $x $y"
}
bind .c <Key-Left> {move_by -10 0}
bind .c <Key-Right> {move_by 10 0}
bind .c <Key-Up> {move_by 0 -10}
bind .c <Key-Down> {move_by 0 10}
wm deiconify .
update
focus -force .c
puts "focus: [focus]"
event generate .c <Key-Left>
event generate .c <Key-Up>
event generate .c <Key-Right>
event generate .c <Key-Down>
after 300 {destroy .}
The bindings pass the four directions to one procedure, so the movement rule
lives in a single place. The event generate calls at the end
simulate the four key presses, which lets the example run unattended; in a
real program the user presses the keys. The sequence ends where it started
because the four moves cancel out.
$ wish keys.tcl focus: .c centre: 140 80 centre: 140 70 centre: 150 70 centre: 150 80
Collision detection
A collision is an overlap between two items. The canvas can report the bounding box of an item and list the items inside a rectangle, so a simple test takes the box of the moving item, finds everything in it and removes the moving item from the result.
package require Tk
canvas .c -width 300 -height 160 -background white
pack .c
set target [.c create rectangle 220 40 280 120 \
-fill "" -outline #2f7d4f -width 2]
set x 30
set y 80
set ball [.c create oval [expr {$x-18}] [expr {$y-18}] \
[expr {$x+18}] [expr {$y+18}] -fill #3a6ea5 -outline ""]
set steps 0
proc tick {} {
global x y ball target steps
incr x 8
incr steps
.c coords $ball [expr {$x-18}] [expr {$y-18}] \
[expr {$x+18}] [expr {$y+18}]
set hits [.c find overlapping {*}[.c bbox $ball]]
set hits [lsearch -all -inline -exact -not $hits $ball]
if {[llength $hits] > 0} {
puts "hit target at step $steps, x = $x"
puts "overlapping items: $hits"
destroy .
return
}
if {$steps < 40} {
after 20 tick
} else {
puts "no hit after $steps steps"
destroy .
}
}
after 20 tick
find overlapping with a bounding box is a cheap approximation:
it compares rectangles, not the visible shapes, which is enough for most
games and editors. Removing the ball from the list with
lsearch -not leaves the target and any other item. The ball
travels eight pixels per tick and meets the target on step 22.
$ wish collide.tcl hit target at step 22, x = 206 overlapping items: 1
A sprite from a photo image
A photo image becomes a canvas item with create image. The item
has a single anchor coordinate instead of two corners, and
-anchor w puts the anchor at the middle of the left edge, which
suits a sprite that moves along a line. The script uses a 36 pixel ball
stored in sprite.png.
package require Tk
canvas .c -width 320 -height 120 -background white
pack .c
set sprite [image create photo -file sprite.png]
set x 20
set id [.c create image $x 60 -image $sprite -anchor w]
set steps 0
proc tick {} {
global x id sprite steps
incr x 6
incr steps
.c coords $id $x 60
if {$steps % 10 == 0} {
puts "sprite bbox: [.c bbox $id]"
}
if {$x < 300} {
after 20 tick
} else {
puts "sprite stopped at x = $x"
destroy .
}
}
after 20 tick
The sprite moves six pixels per tick and reports its bounding box every tenth
step, which is a convenient way to check that the image is really being
redrawn. The bounding box grows by six pixels horizontally and stays at the
same height, as expected from a single anchor point. A different frame of the
sprite can be shown at any time with itemconfigure -image.
$ wish sprite.tcl sprite bbox: 80 42 116 78 sprite bbox: 140 42 176 78 sprite bbox: 200 42 236 78 sprite bbox: 260 42 296 78 sprite stopped at x = 302
Stopping and restarting
An animation should be stoppable without destroying the scene. The
after command returns an identifier, and after cancel
removes the pending callback. Keeping that identifier in one variable makes
start and stop symmetrical, and a guard prevents two timers from running at
the same time.
package require Tk
canvas .c -width 300 -height 120 -background white
pack .c
set x 10
set ball [.c create oval $x 40 [expr {$x + 40}] 80 -fill #2f7d4f -outline ""]
set timer {}
proc step {} {
global x ball timer
.c move $ball 6 0
incr x 6
set timer [after 20 step]
}
proc stop {} {
global timer
if {$timer ne {}} {
after cancel $timer
set timer {}
puts "stopped at x = [lindex [.c coords $::ball] 0]"
}
}
proc start {} {
global timer
if {$timer eq {}} {
puts "starting at x = [lindex [.c coords $::ball] 0]"
set timer [after 20 step]
}
}
after 100 start
after 400 stop
after 550 start
after 900 {stop; destroy .}
The timer variable doubles as a state flag: an empty value means the
animation is stopped. stop reads the current position before
cancelling, and start refuses to start a second chain. The four
after calls at the end simulate a user pressing start, stop and
start again within a second.
$ wish stop.tcl starting at x = 10.0 stopped at x = 94.0 starting at x = 94.0 stopped at x = 196.0
Source
The canvas items, the after timer and the photo image are
documented in the Tk manual.
This article built a still canvas, moved items, animated them with
after, added bouncing, keyboard control, collision detection and
a photo image sprite, and made the loop stoppable. Continue with
Tk images for the file formats behind the sprite,
or with Tk clipboard and drag and drop for
another kind of canvas interaction.
Author
List all Tcl Tutorials.