Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 40 ยท Canvas and Drawing

Canvas Mouse Drawing, Dragging Items and Hit Testing

Draw freehand lines with the mouse, drag canvas items, find what was clicked with find_closest and find_overlapping, and add undo to a Tkinter drawing.

A canvas becomes interactive when you connect it to the mouse. Three patterns cover most programs: freehand drawing (draw while the button is held), dragging (move an item with the pointer) and hit testing (find out which item was clicked). This lesson builds each one, shows the geometry behind them, and adds undo.

The Tkinter code is read-only. The runnable stand-ins implement the same logic in plain Python: line smoothing, drag offsets, point-in-shape tests and an undo stack. The bindings used here (<Button-1>, <B1-Motion>, <ButtonRelease-1>) are explained fully in the Events and Bindings chapter; this lesson uses them in the simplest way.

Freehand drawing

The mouse has three events that matter: the button goes down, the mouse moves with the button held, the button goes up.

Python
import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=320, bg="white", cursor="crosshair")
canvas.pack()

last = None

def press(event):
    global last
    last = (event.x, event.y)

def draw(event):
    global last
    x, y = event.x, event.y
    canvas.create_line(last[0], last[1], x, y, width=3, fill="black",
                       capstyle="round", smooth=True, tags="stroke")
    last = (x, y)

def release(event):
    global last
    last = None

canvas.bind("<Button-1>", press)
canvas.bind("<B1-Motion>", draw)
canvas.bind("<ButtonRelease-1>", release)
root.mainloop()

The user can scribble on a white canvas with a crosshair cursor. Each motion event adds one short line from the previous point to the new one, so a fast mouse creates visible straight segments. capstyle="round" hides the joins. Tkinter reports motion at the screen's event rate, so a single stroke may create hundreds of tiny line items, which is wasteful when you want to select or erase a stroke as one object.

One item per stroke

A better design creates one polyline item when the button goes down and extends it while moving:

Python
current = None

def press(event):
    global current
    current = canvas.create_line(event.x, event.y, event.x, event.y,
                                 width=3, capstyle="round", joinstyle="round", tags="stroke")

def draw(event):
    coords = canvas.coords(current)
    canvas.coords(current, *coords, event.x, event.y)

def release(event):
    global current
    current = None

canvas.coords(item) returns the point list, and canvas.coords(item, *points) replaces it. Now a stroke is one item: one id to delete for undo, one tag to recolor. The stand-in below models the same bookkeeping and also drops points that are too close to each other, which keeps the item small.

Python Stand-in: strokes, point thinning and undo

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.

Dragging items

To drag an item you must remember where inside the item the user grabbed it. If you set the item's position to the pointer position at every motion, the item jumps so that its corner sits under the mouse. Instead, store the previous pointer position and move by the difference:

Python
drag = {"item": None, "x": 0, "y": 0}

def grab(event):
    items = canvas.find_withtag("current")      # item under the pointer
    if items and "draggable" in canvas.gettags(items[0]):
        drag["item"] = items[0]
        drag["x"], drag["y"] = event.x, event.y
        canvas.tag_raise(items[0])

def move(event):
    if drag["item"] is None:
        return
    canvas.move(drag["item"], event.x - drag["x"], event.y - drag["y"])
    drag["x"], drag["y"] = event.x, event.y

def drop(event):
    drag["item"] = None

canvas.tag_bind("draggable", "<Button-1>", grab)
canvas.bind("<B1-Motion>", move)
canvas.bind("<ButtonRelease-1>", drop)

You see a few colored shapes, and you can pick any of them up and carry it around, with the shape staying under the exact spot you grabbed. canvas.tag_bind(tag, event, handler) binds an event for items with a given tag, so clicks on the empty background do nothing. The tag "current" always names the item under the pointer.

Hit testing: what is under the mouse?

For simple click handling tag_bind is enough. Sometimes you need geometry directly, for example when the canvas has a custom scale or you want hover effects.

Question Tool
Which item is at this point? find_closest(x, y) or find_overlapping(x, y, x, y)
Which items are inside this rubber-band rectangle? find_enclosed(x1, y1, x2, y2)
Which items touch this rectangle? find_overlapping(x1, y1, x2, y2)
Where is the item? bbox(item)

find_closest always returns something (the nearest item, however far away), so you must check the distance. find_overlapping uses the item's bounding box for most shapes, so a click in the empty corner of a circle's box can still count as a hit. For precise tests on circles, compute the distance yourself.

Python Stand-in: precise hit tests for rectangles and circles

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.

Point (139, 139) is inside the box of the red disc but outside the circle (its distance from the center is about 55). A bounding-box test would say "hit"; the circle test is right. The overlap at (105, 105) returns the disc because it was drawn last and therefore sits on top.

Rubber-band rectangles and selection

A selection rectangle is another drag pattern: on press, create a zero-size rectangle; on motion, update its coordinates; on release, collect the items with find_enclosed and delete the rectangle.

Python
rubber = None
start = (0, 0)

def start_select(event):
    global rubber, start
    start = (event.x, event.y)
    rubber = canvas.create_rectangle(*start, *start, outline="blue", dash=(4, 2))

def update_select(event):
    canvas.coords(rubber, start[0], start[1], event.x, event.y)

def finish_select(event):
    x1, y1, x2, y2 = canvas.coords(rubber)
    selected = canvas.find_enclosed(min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2))
    canvas.delete(rubber)
    print("selected:", selected)

Note the min/max: if the user drags up and to the left, the coordinates are reversed, and find_enclosed expects the first corner to be the top-left.

Common mistakes

  • Drawing one line item per motion event and then wondering why the canvas becomes slow after a long drawing.
  • Setting the item position to the pointer position while dragging (the item jumps).
  • Trusting find_closest without checking the distance.
  • Forgetting canvas.canvasx() / canvasy() when the canvas is scrolled.
  • Binding <B1-Motion> on the root window and getting coordinates relative to another widget.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is it better to extend one line item per stroke than to create a new line per motion event?

    A stroke as one item stays small and can be handled as a unit; hundreds of tiny items slow the canvas down.
  2. 2. How do you avoid an item jumping while dragging?

    Using the delta preserves the offset between the grab point and the item's corner.
  3. 3. What does canvas.find_closest(x, y) return when no item is near the point?

    It always returns the nearest item (unless the canvas is empty), so check the distance yourself.
  4. 4. Why use min() and max() when finishing a rubber-band selection?

    find_enclosed expects the top-left corner first, so normalize the rectangle.

Summary

  • Freehand drawing uses press, motion and release bindings; build each stroke as one polyline.
  • Drag by applying the delta between pointer positions; raise the dragged item.
  • tag_bind handles clicks on tagged items; find_* methods answer geometric questions.
  • Bounding boxes are not precise for circles; use real geometry when it matters.
  • Keep strokes in a list so you can undo.

Next: Themed Widgets with ttk