tkinter and CustomTkinter · lesson 4 of 8
Parts in this lesson
ALibraryPresenter(library, storage)the middle layer
BRow(...)3.6: a frozen dataclass of text
CMessage(text, ok)a refusal, as a value
Dexcept LibraryError4.8: one family of errors

A presenter between the window and the library

Last updated

A window is hard to test: something has to click it. The library is easy to test, but it speaks in objects and errors, not in text for a screen. In this lesson you'll put a small class between them, a presenter, which turns the library into rows and messages and never imports tkinter. It runs in this page, and pytest can test it.

By the end of this lesson you can

  • Explain the Model–View–Presenter pattern, and what each part may know
  • Use a presenter that turns library objects into rows and refusals into messages
  • Say what happens when a library error reaches a tkinter button
  • Test the presenter with pytest, without opening a window

Three parts, three jobs

A window program that does everything in its button methods gets hard to change and harder to test. The usual fix is to split it into three parts, each with one job. This split is called Model–View–Presenter:

PartHere it's…Its jobIt knows about…
Modelthe capstone's Library, unchangedthe rules: lending, fines, savingnothing outside itself
PresenterLibraryPresenter, newturns the model into text for the screen, and the user's actions into model callsthe model, but no toolkit
Viewthe tkinter windowshows what the presenter gives it, and passes on clicksthe presenter, and tkinter

Each part only talks to its neighbour. The view never calls Library itself, and the presenter never imports tkinter. That's why the same presenter works for a CustomTkinter window in lesson T.7, and would work for a Flet app too.

It's the same idea as the capstone's menu (lesson C.7), which only read and printed, and left every rule to the library. The presenter does the menu's job for a window.

The presenter

Make library_gui/presenter.py beside the window code from T.2:

The project folder
your project folder
├── library/
├── library_gui/
│   ├── __init__.py
│   └── presenter.py     new
└── tests/
    ├── conftest.py
    └── test_presenter.py   new

Here's the reference's. Read the two small dataclasses first:

How the reference does it library_gui/presenter.py, lines 15–36
@dataclass(frozen=True)
class Row:
    """One line of the catalogue table, already turned into text."""

    item_id: str
    title: str
    kind: str
    state: str
    due: str


@dataclass(frozen=True)
class Message:
    """What to tell the user after they do something: ok is False for a refusal."""

    text: str
    ok: bool


def money(cents: int) -> str:
    return f"${cents // 100}.{cents % 100:02}"

A Row is one line of the catalogue table, already turned into text: the window just shows the five strings. A Message is what to tell the user after they do something, and ok says whether it worked. Both are frozen (lesson 3.6), because they're answers, not things to change.

Now the class itself:

How the reference does it library_gui/presenter.py, lines 38–86
class LibraryPresenter:
    def __init__(self, library: Library, storage: Storage) -> None:
        self._library = library
        self._storage = storage

    def rows(self, search: str = "") -> list[Row]:
        """The catalogue, or the items that match a search, in title order."""
        rows = []
        for item in self._library.catalogue.search(search):
            loan = self._library.loan_of(item.item_id)
            if not item.can_lend():
                state, due = "Reference", ""
            elif loan:
                who = self._library.member(loan.member_id).get_name()
                state, due = f"Out: {who}", loan.due_on.isoformat()
            else:
                state, due = "In", ""
            rows.append(Row(item.item_id, item.title, item.kind, state, due))
        return rows

    def members(self) -> list[tuple[str, str]]:
        """Every member as (id, name), in name order, for a drop-down."""
        people = sorted(self._library.members(), key=lambda m: m.get_name())
        return [(m.get_id(), m.get_name()) for m in people]

    def lend(self, item_id: str, member_id: str) -> Message:
        if not item_id or not member_id:
            return Message("Choose an item and a member first.", False)
        try:
            loan = self._library.lend(item_id, member_id)
        except LibraryError as e:
            return Message(f"Sorry: {e}.", False)
        self._storage.save(self._library)
        title = self._library.catalogue.get(item_id).title
        name = self._library.member(member_id).get_name()
        return Message(f"Lent {title} to {name}. Due back {loan.due_on}.", True)

    def give_back(self, item_id: str) -> Message:
        if not item_id:
            return Message("Choose an item first.", False)
        try:
            fine = self._library.give_back(item_id)
        except LibraryError as e:
            return Message(f"Sorry: {e}.", False)
        self._storage.save(self._library)
        title = self._library.catalogue.get(item_id).title
        if fine:
            return Message(f"{title} is back. Fine: {money(fine)}.", True)
        return Message(f"{title} is back, on time.", True)
  • rows asks the catalogue to search, then works out each item's state: in, out with whom and until when, or a reference book.
  • lend and give_back call the library inside try. A LibraryError (lesson C.4's family of refusals) becomes a Message with ok=False. Nothing is raised.
  • After every change, the presenter saves. The window never has to remember.

Here it is at work. There's no window, so it runs in this page. Press Run:

Step 2 code
Edit the code, then run it again

The three lend calls give one success and two refusals, all as plain values. Try a change: take Dune back with presenter.give_back("b1"), and print the rows again.

When a refusal reaches the window

The wrong way. Without a presenter, a button's method calls the library straight away. Here's what a Lend button might do. Press Run:

Step 3 code raw.py
Edit the code, then run it again

The first loan works. The second raises NotAvailable, because a reference book can't be borrowed, and the program stops.

In a tkinter window it's quieter, and that's worse. tkinter catches an error in a button's command, prints it in the terminal, and carries on:

The terminal behind the window
Exception in Tkinter callback
Traceback (most recent call last):
  ...
library.errors.NotAvailable: Atlas of the World can't be borrowed

The window stays open, and the user, who isn't looking at the terminal, sees nothing at all. They click Lend again, and nothing happens again.

The presenter's except LibraryError is the fix: a refusal becomes a Message, and the window shows it (lesson T.6 puts it in a dialog). Notice it catches only LibraryError. A real bug, like a typo in a method name, should still show up loudly.

Why does the presenter catch LibraryError and not every Exception?

Test it without a window

The presenter is plain Python, so it's tested like the rest of the capstone. Save the tests as tests/test_presenter.py. They use the library and clock fixtures from the capstone's conftest.py (lesson C.9), and MemoryStorage, so nothing touches your real library.json:

How the reference does it tests/test_presenter.py, lines 1–48
"""The presenter is plain Python, so it's tested without opening a window."""
from library.storage import MemoryStorage
from library_gui.presenter import LibraryPresenter, Row


def make(library):
    storage = MemoryStorage()
    return LibraryPresenter(library, storage), storage


def test_rows_in_title_order(library):
    presenter, _ = make(library)
    titles = [row.title for row in presenter.rows()]
    assert titles == ["Atlas of the World", "Dune", "Emma", "Rivers of Ice"]


def test_rows_show_state(library):
    presenter, _ = make(library)
    presenter.lend("b1", "sam")
    rows = {row.item_id: row for row in presenter.rows()}
    assert rows["b1"] == Row("b1", "Dune", "book", "Out: Sam Okafor", "2026-03-23")
    assert rows["b2"].state == "In"
    assert rows["r1"].state == "Reference"


def test_search(library):
    presenter, _ = make(library)
    assert [row.item_id for row in presenter.rows("austen")] == ["b2"]


def test_members_by_name(library):
    presenter, _ = make(library)
    assert presenter.members() == [("ana", "Ana Lima"), ("sam", "Sam Okafor")]


def test_lend_saves(library):
    presenter, storage = make(library)
    message = presenter.lend("b1", "sam")
    assert message.ok
    assert message.text == "Lent Dune to Sam Okafor. Due back 2026-03-23."
    assert storage.load().loan_of("b1") is not None


def test_refusal_is_a_message(library):
    presenter, storage = make(library)
    message = presenter.lend("r1", "sam")
    assert not message.ok
    assert message.text == "Sorry: Atlas of the World can't be borrowed."
Terminal
pytest tests/test_presenter.py

All eight should pass. Most of what the window does is now tested, and the window class that's left is thin: it shows rows and messages, and passes on clicks.

Check

Which part may import tkinter?
A button's command raises NotAvailable in a tkinter window. What does the user see?
What does presenter.lend("r1", "sam") give back for a reference book?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python