tkinter and CustomTkinter · lesson 8 of 8
Parts in this lesson
ALibraryPresenterT.4: the middle layer
Bclass DeskWindow(ttk.Frame)T.2: the window is a class
Cttk.Treeview + StringVarT.5: the table and the search
Dttk.Notebooktabs, for the overdue list
Ectk.CTkTabviewT.7: the same in CustomTkinter

Project: the library window

Last updated

Time to put the module together. You'll build the whole library desk window on your computer: a live search, the catalogue as a table, lend and return with a member picked from a list, and refusals shown in the window. Then you'll add an overdue list of your own, and move the finished window to CustomTkinter.

By the end of this lesson you can

  • Plan a window as classes, with a presenter between it and the library
  • Build the desk window in tkinter from the pieces of T.1 to T.6
  • Add a feature through every layer: presenter, test, then window
  • Move the finished window to CustomTkinter without changing the presenter

Plan it

Here's what the finished window does:

  • A search box, and under it the catalogue as a table, with each item's state and due date. Typing searches straight away.
  • A drop-down of members, and Lend and Return buttons. Double-clicking a row lends it too.
  • A status line that says what happened. A refusal also opens a dialog.
  • Everything is saved to library.json after every change, through the capstone's JsonStorage.

And here are the classes, in their layers:

LayerClassFrom
ModelLibrary, Catalogue, Member, Loan, JsonStoragethe capstone, unchanged
PresenterLibraryPresenter, Row, Messagelesson T.4
ViewDeskWindow, a ttk.Framethis lesson

main() puts them together: it loads the library, makes the presenter with the library and the storage, and hands the presenter to the window. Your project folder will end up like this:

The project folder
your project folder
├── library/             the capstone, unchanged
├── library_gui/
│   ├── __init__.py
│   ├── presenter.py     T.4
│   ├── tk_app.py        this lesson
│   └── ctk_app.py       this lesson
├── tests/
│   └── test_presenter.py
└── pyproject.toml

Try writing tk_app.py yourself before you read the reference's in step 2. Everything it needs is in lessons T.1 to T.6.

The desk window

Here's the reference's window, all of it:

How the reference does it library_gui/tk_app.py
"""The library desk in tkinter: a search box, the catalogue as a table, lend and return.

Run it from the folder that holds library/ and library_gui/:  python -m library_gui.tk_app
"""
import tkinter as tk
from tkinter import font, messagebox, ttk

from library import sample
from library.storage import JsonStorage
from library_gui.presenter import LibraryPresenter, Message

COLUMNS = (("title", "Title", 220), ("kind", "Kind", 80), ("state", "State", 150), ("due", "Due", 90))


class DeskWindow(ttk.Frame):
    def __init__(self, root: tk.Misc, presenter: LibraryPresenter) -> None:
        super().__init__(root, padding=12)
        self.presenter = presenter
        self.search = tk.StringVar()
        self.member = tk.StringVar()
        self.status = tk.StringVar(value="Choose an item, then lend it or take it back.")
        self.names = {name: member_id for member_id, name in presenter.members()}
        self.build()
        self.search.trace_add("write", lambda *args: self.refresh())
        self.refresh()

    def build(self) -> None:
        # Rows as tall as the text, so letters aren't cut off on high-resolution screens.
        line = font.nametofont("TkDefaultFont").metrics("linespace")
        ttk.Style(self).configure("Treeview", rowheight=line + 6)
        ttk.Label(self, text="Search").grid(row=0, column=0, sticky="w")
        ttk.Entry(self, textvariable=self.search).grid(
            row=0, column=1, columnspan=3, sticky="ew", padx=(8, 0)
        )
        self.table = ttk.Treeview(
            self, columns=[c[0] for c in COLUMNS], show="headings", selectmode="browse", height=10
        )
        for name, heading, width in COLUMNS:
            self.table.heading(name, text=heading)
            self.table.column(name, width=width)
        self.table.grid(row=1, column=0, columnspan=4, sticky="nsew", pady=8)
        self.table.bind("<Double-1>", lambda event: self.lend())
        ttk.Label(self, text="Member").grid(row=2, column=0, sticky="w")
        ttk.Combobox(self, textvariable=self.member, values=list(self.names), state="readonly").grid(
            row=2, column=1, sticky="ew", padx=8
        )
        ttk.Button(self, text="Lend", command=self.lend).grid(row=2, column=2)
        ttk.Button(self, text="Return", command=self.give_back).grid(row=2, column=3, padx=(8, 0))
        ttk.Label(self, textvariable=self.status).grid(
            row=3, column=0, columnspan=4, sticky="w", pady=(8, 0)
        )
        self.columnconfigure(1, weight=1)
        self.rowconfigure(1, weight=1)

    def chosen_item(self) -> str:
        chosen = self.table.selection()
        return chosen[0] if chosen else ""

    def refresh(self) -> None:
        """Empties the table and fills it again from the presenter."""
        chosen = self.chosen_item()
        self.table.delete(*self.table.get_children())
        for row in self.presenter.rows(self.search.get()):
            values = (row.title, row.kind, row.state, row.due)
            self.table.insert("", "end", iid=row.item_id, values=values)
        if self.table.exists(chosen):
            self.table.selection_set(chosen)

    def lend(self) -> None:
        member_id = self.names.get(self.member.get(), "")
        self.show(self.presenter.lend(self.chosen_item(), member_id))

    def give_back(self) -> None:
        self.show(self.presenter.give_back(self.chosen_item()))

    def show(self, message: Message) -> None:
        self.status.set(message.text)
        if not message.ok:
            messagebox.showwarning("Library", message.text, parent=self)
        self.refresh()


def main(path: str = "library.json") -> None:
    storage = JsonStorage(path)
    library = storage.load()
    if not len(library.catalogue):
        sample.fill(library)
    root = tk.Tk()
    root.title("Library desk")
    root.minsize(600, 380)
    window = DeskWindow(root, LibraryPresenter(library, storage))
    window.grid(row=0, column=0, sticky="nsew")
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)
    root.mainloop()


if __name__ == "__main__":
    main()
Terminal
python -m library_gui.tk_app
The tkinter desk: a search box, a table of six items with Emma selected and Dune out to Sam Okafor, a member drop-down, Lend and Return buttons, and a refusal message
The finished window on Windows 11, after lending Dune to Sam and trying to lend the Atlas.

Things to notice:

  • COLUMNS at the top keeps each column's name, heading and width together, so a new column is one more line.
  • self.names maps each member's name to their id. The drop-down shows names, and the presenter wants ids.
  • __init__ does three things in order: keep what it's given, build the widgets, then fill them. trace_add comes after build, so the first search doesn't run before the table exists.
  • Every method is short. refresh is the longest, and most of it is lesson T.5's empty-and-refill.

Try it out: lend Dune to Sam, try to lend the Atlas, search for austen, close the window and open it again. Dune is still on loan, because the presenter saved it.

Your own feature: overdue loans

Now add something the reference doesn't have: a list of overdue loans, with who has each one, how late it is and the fine so far. Add it the way every feature goes in, layer by layer, starting at the bottom.

The presenter. Add overdue(self) -> list[tuple[str, str, str, str]], one tuple per late loan: title, member's name, days late and the fine. The capstone's reports.overdue(library) (lesson C.8) already finds them, as (loan, days) pairs, and each member's policy works out the fine with fine_for(days).

The test. Before you write the method, write the test, in tests/test_presenter.py:

def test_overdue_rows(library, clock):
    presenter, _ = make(library)
    presenter.lend("d1", "sam")
    clock.advance(10)
    assert presenter.overdue() == [("Rivers of Ice", "Sam Okafor", "3 days", "$0.75")]

Run it, and watch it fail, because there's no overdue yet. Then write the method until it passes.

Terminal
pytest

The window. Put the catalogue and the overdue list in tabs, with ttk.Notebook. Each tab is a frame, and add gives it a title:

tabs = ttk.Notebook(self)
tabs.add(catalogue_frame, text="Catalogue")
tabs.add(overdue_frame, text="Overdue")
tabs.grid(row=1, column=0, columnspan=4, sticky="nsew")

The overdue tab needs a second Treeview and its own refresh. Call it after every lend and return, as well as when the window opens. To test it, give main() a FixedClock set weeks ahead.

Move it to CustomTkinter

Last, move your finished window to CustomTkinter, as lesson T.7 moved the reference's. Start from a copy, ctk_app.py, and change the view only:

  • ttk.Frame → ctk.CTkFrame, and each widget to its CTk partner.
  • The catalogue table → radio buttons in a CTkScrollableFrame, as the reference does.
  • ttk.Notebook → ctk.CTkTabview. Its tabs are made with .add("Overdue"), which returns the frame to put that tab's widgets in.
  • Add a CTkSwitch that flips set_appearance_mode between "light" and "dark".

Run pytest once more when you're done. You haven't touched presenter.py or its tests, so they should all still pass, and that's the point.

Finished

You've built a desktop window for the library, twice, and every rule still lives in the capstone's classes. Check your app against this list:

  • Searching changes the table as you type.
  • Lending a reference book, or a book that's out, shows a refusal in the window, and no traceback appears in the terminal.
  • Closing the window and opening it again keeps every loan.
  • pytest passes, with your new overdue test.
  • The CustomTkinter version does everything the tkinter one does.
You added the overdue list. Which file did you change first, and why?
Moving to CustomTkinter, did any test need to change?

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