Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 40 ยท Projects and Practice

Project: A To-Do List App with Saving, Filters and Undo

Build a Tkinter to-do app: a tested task model with priorities and due dates, JSON persistence, filters, undo, and a Treeview window wired with a presenter.

A to-do app is the best next step after a calculator. It has data that must survive between runs, a list view with selection, several actions (add, edit, complete, delete), filters, and a good reason to use everything from the previous lessons: a model separate from the view (Separating Logic from the GUI), a Treeview (Treeview), dialogs (Dialogs and Menus) and a settings-style file in the user's folder (Packaging a Tkinter App).

You will build the model first and run it here, then the window, which is read-only because Tkinter needs a display. Because the model has the rules, the window stays short.

Step 1: Requirements

  • A task has a title, a priority (low, normal, high), an optional due date, a done flag and an id.
  • The user can add, edit, complete, delete and undo the last change.
  • Filter: all, active, done, overdue; plus text search.
  • Sort by due date or priority; overdue tasks are highlighted.
  • Tasks are saved to a JSON file when the window closes and loaded at start; a broken file must not crash the app.

Step 2: The model

Dates use datetime.date, so "overdue" is a comparison with today. The model takes today as a function, which keeps tests deterministic (the same trick as injecting a clock).

Python Run: task model, filters, sorting 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.

The output shows each filter, the sort orders, undo restoring a deleted task, a JSON round trip, and the three rejected inputs. Every rule that the window needs is already working.

Design points worth noticing:

  • Undo by snapshot. Instead of writing an "inverse" for each action, store the whole list before each change. For a few hundred tasks this is trivial and makes undo always correct.
  • Validation in the model. The window will not repeat these checks; it catches ValueError and shows the message.
  • from_json never raises. A corrupted file returns an empty store. A real app might first rename the damaged file to tasks.bak so the user can recover it.
  • today is injected, so the overdue tests do not depend on the real date.

Step 3: The window plan

The window

Top bar Filter combobox and search entry
Table Treeview: Done, Title, Priority, Due
Form Entry, priority, due date, Add
Toolbar Toggle, Delete, Undo

The view only shows what the store returns.

1 / 2

Step 4: The Tkinter view

Python
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from pathlib import Path

DATA_FILE = Path.home() / ".todo_app.json"

class TodoApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("To-Do")
        self.geometry("640x420")
        self.store = (TaskStore.from_json(DATA_FILE.read_text(encoding="utf-8"))
                      if DATA_FILE.exists() else TaskStore())
        self.mode = tk.StringVar(value="all")
        self.search = tk.StringVar()
        self._build()
        self.refresh()
        self.protocol("WM_DELETE_WINDOW", self.on_close)

    def _build(self):
        top = ttk.Frame(self, padding=8)
        top.pack(fill="x")
        mode = ttk.Combobox(top, textvariable=self.mode, state="readonly",
                            values=("all", "active", "done", "overdue"), width=10)
        mode.pack(side="left")
        mode.bind("<<ComboboxSelected>>", lambda e: self.refresh())
        ttk.Entry(top, textvariable=self.search, width=24).pack(side="left", padx=8)
        self.search.trace_add("write", lambda *a: self.refresh())

        columns = ("done", "title", "priority", "due")
        self.tree = ttk.Treeview(self, columns=columns, show="headings", selectmode="browse")
        for col, text, width in (("done", "โœ“", 40), ("title", "Task", 300),
                                 ("priority", "Priority", 90), ("due", "Due", 100)):
            self.tree.heading(col, text=text)
            self.tree.column(col, width=width, anchor="w" if col == "title" else "center")
        self.tree.tag_configure("overdue", foreground="#b00020")
        self.tree.tag_configure("done", foreground="#888888")
        self.tree.pack(fill="both", expand=True, padx=8)
        self.tree.bind("<Double-1>", lambda e: self.toggle())

        form = ttk.Frame(self, padding=8)
        form.pack(fill="x")
        self.title_var, self.prio_var, self.due_var = tk.StringVar(), tk.StringVar(value="normal"), tk.StringVar()
        ttk.Entry(form, textvariable=self.title_var, width=30).pack(side="left")
        ttk.Combobox(form, textvariable=self.prio_var, values=tuple(PRIORITIES),
                     state="readonly", width=8).pack(side="left", padx=6)
        ttk.Entry(form, textvariable=self.due_var, width=11).pack(side="left")
        ttk.Button(form, text="Add", command=self.add).pack(side="left", padx=6)
        ttk.Button(form, text="Toggle", command=self.toggle).pack(side="left")
        ttk.Button(form, text="Delete", command=self.delete).pack(side="left", padx=6)
        ttk.Button(form, text="Undo", command=self.undo).pack(side="left")

        self.bind("<Control-z>", lambda e: self.undo())
        self.bind("<Delete>", lambda e: self.delete())

    def refresh(self):
        self.tree.delete(*self.tree.get_children())
        for t in self.store.view(self.mode.get(), self.search.get()):
            tags = ("done",) if t.done else (("overdue",) if self.store.is_overdue(t) else ())
            self.tree.insert("", "end", iid=str(t.id), tags=tags,
                             values=("โœ“" if t.done else "", t.title, t.priority, t.due or ""))

    def selected_id(self):
        sel = self.tree.selection()
        return int(sel[0]) if sel else None

    def add(self):
        try:
            self.store.add(self.title_var.get(), self.prio_var.get(), self.due_var.get().strip() or None)
        except ValueError as exc:
            messagebox.showwarning("Cannot add", str(exc), parent=self)
            return
        self.title_var.set("")
        self.due_var.set("")
        self.refresh()

    def toggle(self):
        if (task_id := self.selected_id()) is not None:
            self.store.toggle(task_id)
            self.refresh()

    def delete(self):
        task_id = self.selected_id()
        if task_id is not None and messagebox.askyesno("Delete", "Delete this task?", parent=self):
            self.store.delete(task_id)
            self.refresh()

    def undo(self):
        if self.store.undo():
            self.refresh()

    def on_close(self):
        DATA_FILE.write_text(self.store.to_json(), encoding="utf-8")
        self.destroy()

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

A window opens with a filter drop-down and a search box at the top, a table of tasks in the middle (overdue ones in red, finished ones gray) and an entry row at the bottom. Typing in the search box filters live; double-clicking a row flips it done; Ctrl+Z undoes the last change; closing the window writes the JSON file.

A few notes on the view:

  • iid=str(t.id) makes the tree row id equal to the task id, so no lookup table is needed.
  • Every action ends with refresh(). Rebuilding a few hundred rows is instant; if your list grows to tens of thousands, update single rows with tree.item(iid, ...).
  • messagebox is used only in the view; the model raises ValueError.
  • The model file would live in its own module (store.py) and the view in app.py. The view has no business rules to test.

Step 5: Improvements

  • A due-date picker: a small custom dialog with three spinboxes (year, month, day) built like in Toplevel Windows and Custom Dialogs.
  • Edit with a double-click that opens a dialog prefilled from store.get(id).
  • Sort by clicking headings (Treeview shows the pattern).
  • Reminders: use after(60000, check_due) to show a banner when a task becomes due.
  • Export to CSV through filedialog.asksaveasfilename and the csv module.
  • SQLite instead of JSON for many tasks: the TaskStore interface stays the same, only to_json/from_json change.

Common mistakes

  • Saving only on exit. If the program crashes, everything is lost; also save after each change or on a timer.
  • Writing the file in place without an atomic replace (see the settings loader in the packaging lesson).
  • Using datetime.today() directly inside the model, which makes tests unrepeatable.
  • Selecting rows by index in the list; indexes change after sorting or filtering, ids do not.
  • Updating the tree and the model separately and letting them drift apart: always refresh the view from the model.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is iid set to the task id when inserting Treeview rows?

    selection() returns iids, so using the task id makes the mapping direct and survives filtering and sorting.
  2. 2. How does the model implement undo?

    Snapshots are simple and always correct for small data.
  3. 3. Why is today passed into TaskStore as a function?

    Injecting the clock removes hidden dependence on the real date.
  4. 4. What should from_json do with a corrupted file?

    The app must start; renaming the damaged file to a backup lets the user recover data.

Summary

  • Build the model first: validated actions, filters, sorting, snapshot undo, JSON in and out.
  • Keep the clock and storage injectable; keep Tkinter out of the model.
  • The view rebuilds the Treeview from the model after every action, using task ids as row ids.
  • Save on close and handle damaged files gracefully.
  • Extend with edit dialogs, reminders, export and SQLite.

Next: Project: A Paint Program