Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 40 ยท Projects and Practice

Project: A Paint Program with Tools, Undo/Redo and SVG Export

Build a Tkinter paint program: pen, line, rectangle, oval and eraser tools, color and width controls, undo/redo history, and saving the drawing as SVG.

The paint program brings the Canvas chapter together. It needs mouse events, several tools that share one set of bindings, a color chooser, undo and redo, and a way to save the result. It is also a good lesson in design: if the drawing is stored as data (a list of shapes) and the canvas is only a view of that list, undo, redo, saving and loading all become easy.

You will build the document model first (runnable here, including SVG export), then the Tkinter window (read-only, as it needs a screen). Canvas basics are in Canvas: Shapes and Text and mouse handling in Canvas Mouse Drawing and Hit Testing.

Design: the drawing is a list of shapes

Every mark the user makes becomes a small record: its kind, its points, its color, its width. The canvas shows them; the list is the truth.

Shape Points Notes
pen many (x, y) freehand polyline
line 2 points straight line
rect 2 corners outline, optional fill
oval 2 corners bounding box
eraser many points white pen with a larger width

With this structure:

  • Undo removes the last shape and pushes it onto a redo stack.
  • Redo moves it back.
  • Save serializes the list (JSON for editing later, SVG or PNG for sharing).
  • Redraw deletes everything on the canvas and draws the list again, for example after loading a file.

Data first, canvas second

Shape list The single source of truth
Canvas Draws the list
Undo and redo Move shapes between two stacks
Export JSON, SVG or PostScript

Anything stored as data is easy to save and undo.

1 / 2

Step 1: The document model

Python Run: shapes, undo/redo and SVG export

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 lines show undo and redo moving shapes between the two stacks, including the rule that drawing something new empties the redo stack (otherwise redo would reinsert a shape in a place where it no longer makes sense). The printed SVG could be pasted into a file named drawing.svg and opened in a browser. Note how the eraser is just a pen drawn in the background color, a simple approach that works because the background is one flat color.

Step 2: Turning mouse positions into shapes

Each tool reacts to the same three mouse events (press, drag, release) but treats the points differently: pen and eraser append every point, while line, rectangle and oval keep the start point and the latest point. While dragging, you show a preview item on the canvas and replace it as the mouse moves; on release the final shape is added to the document.

Python Run: tool logic without a canvas

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 pen records the whole path; the rectangle keeps only two corners, no matter how long the drag was.

Step 3: The Tkinter window

Python
import tkinter as tk
from tkinter import ttk, colorchooser, filedialog, messagebox

class PaintApp(tk.Tk):
    TOOLS = ("pen", "line", "rect", "oval", "eraser")

    def __init__(self):
        super().__init__()
        self.title("Paint")
        self.doc = Document(640, 420)
        self.tool = tk.StringVar(value="pen")
        self.color = "#000000"
        self.width = tk.IntVar(value=3)
        self.session = None
        self.preview = None
        self._build()
        self.bind("<Control-z>", lambda e: self.undo())
        self.bind("<Control-y>", lambda e: self.redo())

    def _build(self):
        bar = ttk.Frame(self, padding=6)
        bar.pack(fill="x")
        for name in self.TOOLS:
            ttk.Radiobutton(bar, text=name.title(), value=name, variable=self.tool,
                            style="Toolbutton").pack(side="left", padx=2)
        self.swatch = tk.Label(bar, width=3, bg=self.color, relief="sunken")
        self.swatch.pack(side="left", padx=(12, 4))
        ttk.Button(bar, text="Color", command=self.pick_color).pack(side="left")
        ttk.Spinbox(bar, from_=1, to=40, textvariable=self.width, width=4).pack(side="left", padx=8)
        ttk.Button(bar, text="Undo", command=self.undo).pack(side="left")
        ttk.Button(bar, text="Redo", command=self.redo).pack(side="left", padx=2)
        ttk.Button(bar, text="Save SVG", command=self.save_svg).pack(side="right")

        self.canvas = tk.Canvas(self, width=self.doc.width, height=self.doc.height,
                                bg=self.doc.background, highlightthickness=0, cursor="crosshair")
        self.canvas.pack(padx=6, pady=(0, 6))
        self.canvas.bind("<Button-1>", self.on_press)
        self.canvas.bind("<B1-Motion>", self.on_drag)
        self.canvas.bind("<ButtonRelease-1>", self.on_release)

    # --- drawing -------------------------------------------------------
    def current_style(self):
        tool = self.tool.get()
        color = self.doc.background if tool == "eraser" else self.color
        width = self.width.get() * (3 if tool == "eraser" else 1)
        return color, width

    def on_press(self, event):
        self.session = ToolSession(self.tool.get())
        self.session.press(event.x, event.y)

    def on_drag(self, event):
        if not self.session:
            return
        self.session.drag(event.x, event.y)
        self.draw_preview()

    def on_release(self, event):
        if not self.session:
            return
        shape = self.session.release(event.x, event.y)
        color, width = self.current_style()
        shape.color, shape.width = color, width
        self.doc.add(shape)
        self.session = None
        self.redraw()

    def draw_preview(self):
        if self.preview:
            self.canvas.delete(self.preview)
        color, width = self.current_style()
        self.preview = self.canvas.create_line(*self.session.flat(), fill=color, width=width) \
            if self.session.tool in ("pen", "eraser", "line") else None

    def redraw(self):
        self.canvas.delete("all")
        for s in self.doc.shapes:
            flat = [c for p in s.points for c in p]
            if s.kind in ("pen", "eraser", "line"):
                pts = flat if s.kind != "line" else flat[:2] + flat[-2:]
                if len(pts) >= 4:
                    self.canvas.create_line(*pts, fill=s.color, width=s.width,
                                            capstyle="round", joinstyle="round")
            elif s.kind == "rect":
                self.canvas.create_rectangle(*flat[:2], *flat[-2:], outline=s.color, width=s.width, fill=s.fill)
            elif s.kind == "oval":
                self.canvas.create_oval(*flat[:2], *flat[-2:], outline=s.color, width=s.width, fill=s.fill)
        self.preview = None

    # --- commands ------------------------------------------------------
    def pick_color(self):
        _, hex_code = colorchooser.askcolor(color=self.color, parent=self)
        if hex_code:
            self.color = hex_code
            self.swatch.config(bg=hex_code)

    def undo(self):
        if self.doc.undo():
            self.redraw()

    def redo(self):
        if self.doc.redo():
            self.redraw()

    def save_svg(self):
        path = filedialog.asksaveasfilename(defaultextension=".svg", filetypes=[("SVG image", "*.svg")])
        if path:
            with open(path, "w", encoding="utf-8") as f:
                f.write(self.doc.to_svg())

if __name__ == "__main__":
    PaintApp().mainloop()

A window opens with a toolbar (five tool buttons, a color swatch, a width box, Undo, Redo and Save SVG) above a white drawing area. Dragging with the pen leaves a black line; choosing Rect and dragging draws a rectangle that you can resize before releasing; Ctrl+Z removes the last shape. ToolSession is the class from Step 2 (including its flat() helper), and Document and Shape come from Step 1; put them in the same module or import them.

Notice how short the callbacks are. Every handler either feeds the session or changes the document and then calls redraw(). For long drawings, redrawing everything after each release can get slow; then draw only the new shape and call redraw after undo, redo and load.

Ideas for extensions

  • Fill color for rectangles and ovals (a second color button).
  • Open and Save documents as JSON (Document.to_json), with a "modified" flag and an "unsaved changes" question on close (Message Boxes).
  • Selection and move using find_closest, with each canvas item remembering the index of its shape.
  • Export PNG by saving canvas.postscript(file="out.ps") and converting with Pillow (needs Ghostscript), or by drawing the shape list onto a Pillow image yourself, which gives anti-aliasing control.
  • Smooth pen by thinning points (see Canvas Mouse Drawing and Hit Testing).
  • Keyboard shortcuts and a status bar showing the cursor position.

Common mistakes

  • Storing the drawing only on the canvas. You cannot undo, save or resize it reliably.
  • Forgetting to clear the redo stack on a new action.
  • Deleting the preview item incorrectly and leaving "ghost" shapes while dragging.
  • Using the canvas width and height values before the window is mapped (winfo_width() returns 1).
  • Painting the eraser in white when the background may change: use the document background.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why store shapes in a list instead of only drawing on the canvas?

    The data is the truth; the canvas is a view that can be redrawn from it.
  2. 2. Why does adding a new shape clear the redo stack?

    Once you branch from the history, the old future no longer applies.
  3. 3. How do the line, rectangle and oval tools differ from the pen while dragging?

    Shape tools replace the end point at every move, and the pen appends points.
  4. 4. How is an eraser implemented in this design?

    It works for a flat background; a layered design would need real deletion or masks.

Summary

  • Keep the drawing as a list of shape records; draw the canvas from it.
  • Undo and redo are two stacks; a new action clears redo.
  • Tools share the same press, drag and release handlers and differ in how they build points.
  • Preview while dragging, commit on release, redraw after history changes.
  • Export from the data model: JSON for editing, SVG for sharing.

Next: Tkinter Practice Exercises