Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 40 ยท Canvas and Drawing

Canvas Tags, Moving Items, Images and Scrolling

Control Tkinter canvas items after drawing: tags, move, coords, itemconfig, delete, stacking order, PhotoImage references and a scrollable canvas.

A canvas item is not a pixel; it is an object that lives on after you draw it. That is the key difference from drawing libraries that paint and forget. Because items persist, you can change their color, move them, group them with tags, stack them, delete them and query them. This lesson covers all of those operations, plus images and scrolling.

The Tkinter code needs a window, so it is read-only. The runnable blocks use MiniCanvas, a small model of the canvas written in plain Python (labelled each time), so you can experiment with ids, tags and hit tests without a screen.

Item ids and tags

Every create_* call returns an integer id. You can also give an item tags, which are string labels. One item can have several tags and one tag can belong to many items:

Python
player = canvas.create_rectangle(10, 10, 40, 40, fill="blue", tags=("sprite", "player"))
coin_a = canvas.create_oval(100, 50, 120, 70, fill="gold", tags=("coin",))
coin_b = canvas.create_oval(160, 50, 180, 70, fill="gold", tags=("coin",))

Tags let you operate on groups without keeping lists of ids: canvas.itemconfig("coin", fill="orange") recolors both coins at once. Two tags are built in: "all" (every item) and "current" (the item under the mouse pointer, updated by the canvas on mouse events).

Changing items

Method What it does
itemconfig(tag_or_id, **options) change options such as fill, outline, width, text, state
itemcget(id, "fill") read one option
coords(id) get the coordinates as a list
coords(id, x1, y1, x2, y2) set new coordinates
move(tag_or_id, dx, dy) shift by an offset
moveto(tag_or_id, x, y) put the item's top-left corner at an absolute position
scale(tag_or_id, x0, y0, xscale, yscale) scale around an origin
delete(tag_or_id) remove; delete("all") clears the canvas
tag_raise(id) / tag_lower(id) stacking order (z-order)
bbox(tag_or_id) bounding box (x1, y1, x2, y2)
find_withtag(tag) tuple of ids with that tag
find_overlapping(x1, y1, x2, y2) ids touching that rectangle
find_closest(x, y) the id nearest to a point
addtag_withtag, dtag add or remove a tag later
Python
canvas.move("coin", 0, -5)                # both coins jump 5 pixels up
canvas.itemconfig(player, fill="red")
canvas.itemconfig(coin_a, state="hidden") # invisible, but still exists
x1, y1, x2, y2 = canvas.bbox(player)

move is relative; calling it ten times moves ten steps. Use it for animation. coords is absolute.

Stacking order

Items are drawn in creation order: later items cover earlier ones. tag_raise(item) brings an item to the top, tag_lower(item) sends it to the bottom, and both accept a second argument to place one item just above or below another. A common idiom is canvas.tag_raise("current") so that the item you are dragging stays on top.

Stand-in: a canvas model

The model below is not Tkinter, but it implements the same ideas in about 40 lines: ids, tags, move, bbox, find_withtag, find_overlapping and tag_raise (as list order). Run it to see how tags and overlap queries behave.

Python Stand-in: MiniCanvas with ids, tags and overlap queries

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.

Notice that move("coin", 0, -5) changed both coin items in one call, find_overlapping returned only ids whose boxes touch the query rectangle, and tag_raise just moved an id to the end of the drawing order.

Images on a canvas

PhotoImage loads PNG, GIF and PPM/PGM files (and, since Tk 8.6, PNG natively). For JPEG and other formats you need the Pillow library's ImageTk.PhotoImage.

Python
img = tk.PhotoImage(file="logo.png")
canvas.create_image(200, 150, image=img, anchor="center")
canvas.image = img            # keep a reference!

The logo appears centered at (200, 150). The last line matters. Tkinter does not hold a Python reference to the image; if the variable img goes out of scope (for example when the function that created it returns), Python deletes the image and the canvas silently shows nothing. Store the image in an attribute, a list or a global that lives as long as the window. This is the single most common "my image does not show" bug.

Anchors work like for text: anchor="nw" pins the top-left corner of the image at the point. PhotoImage also offers subsample(2) to shrink by integer factors, zoom(2) to enlarge, and put(color, to=(x, y)) to set pixels. Because there is no resampling filter, use Pillow (Image.resize) for smooth scaling.

Scrolling a canvas

A canvas can be larger than its window. Set the total drawing area with scrollregion and attach scrollbars:

Python
frame = tk.Frame(root)
frame.pack(fill="both", expand=True)

canvas = tk.Canvas(frame, width=300, height=200, scrollregion=(0, 0, 1000, 1000))
hbar = tk.Scrollbar(frame, orient="horizontal", command=canvas.xview)
vbar = tk.Scrollbar(frame, orient="vertical", command=canvas.yview)
canvas.configure(xscrollcommand=hbar.set, yscrollcommand=vbar.set)

vbar.pack(side="right", fill="y")
hbar.pack(side="bottom", fill="x")
canvas.pack(side="left", fill="both", expand=True)

A 300 by 200 window with two scrollbars lets you pan across a 1000 by 1000 world. The two-way link is the standard Tkinter pattern: the scrollbar's command scrolls the view, and the view's scrollcommand updates the scrollbar thumb. If your content changes, recompute the region with canvas.configure(scrollregion=canvas.bbox("all")).

Mouse position inside a scrolled canvas needs conversion, because event.x is relative to the visible window, not to the scrolled world:

Python
def on_click(event):
    world_x = canvas.canvasx(event.x)
    world_y = canvas.canvasy(event.y)

Mixing up window coordinates and canvas coordinates is the second most common canvas bug, usually noticed as "items appear in the wrong place once I scroll".

Python Stand-in: window to canvas coordinates

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.

Embedding widgets

create_window(x, y, window=widget) places an ordinary widget (a button, an entry or a frame) on the canvas so that it scrolls and moves with the other items. This is also how a scrollable frame is built: put a Frame inside a Canvas and use the canvas's scrolling.

Common mistakes

  • Image not stored, so it disappears.
  • Using coords for animation when a relative move is simpler, or using move when you want an absolute position.
  • Hiding items by drawing a background-colored shape over them. Use state="hidden" or delete.
  • Using event.x directly in a scrolled canvas instead of canvasx(event.x).
  • Forgetting to update scrollregion after adding items.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does canvas.move('coin', 0, -5) do?

    move is relative and acts on all items matching the tag or id.
  2. 2. Why might a PhotoImage not appear on the canvas?

    Store the image in an attribute or list that lives as long as the window.
  3. 3. How do you convert window coordinates of a mouse click to canvas coordinates in a scrolled canvas?

    canvasx and canvasy add the scroll offset so you get coordinates in the drawing world.
  4. 4. Which method keeps an item above all others?

    Later items are drawn on top, and tag_raise moves an item to the end of the display list.

Summary

  • Items persist; ids and tags let you change, move, hide, raise and delete them.
  • move is relative, coords and moveto are absolute; find_overlapping and bbox answer geometric questions.
  • Keep references to PhotoImage objects.
  • Use scrollregion with scrollbars, and convert event coordinates with canvasx / canvasy.

Next: Canvas Animation with after()