Project: the library app
Last updated
Time to put the module together. You'll build the whole library app in Flet on your computer: a live search, the catalogue as a table, lend and return with a member picked from a drop-down, and refusals shown in the app. Then you'll add an overdue list of your own in a second tab, and a switch for dark mode.
By the end of this lesson you can
- Plan an app as controls, with a presenter between it and the library
- Build the desk in Flet from the pieces of F.1 to F.5
- Add a feature through every layer: presenter, test, then control
- Run the same app in a browser
Plan it
Here's what the finished app 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. Tapping a row picks it.
- A status line that says what happened. A refusal also shows in a SnackBar.
- Everything is saved to
library.jsonafter every change, through the capstone'sJsonStorage.
And here are the classes, in their layers:
| Layer | Class | From |
|---|---|---|
| Model | Library, Catalogue, Member, Loan, JsonStorage | the capstone, unchanged |
| Presenter | LibraryPresenter, Row, Message | lesson F.3 |
| View | DeskView, a custom Column | this lesson |
main puts them together: it loads the library, makes the presenter with the library and the storage, and adds a DeskView holding the presenter. Your project folder will end up like this:
your project folder ├── library/ the capstone, unchanged ├── library_gui/ │ ├── __init__.py │ ├── presenter.py F.3 │ └── flet_app.py this lesson ├── tests/ │ └── test_presenter.py └── pyproject.toml
Try writing flet_app.py yourself before you read the reference's in step 2. Everything it needs is in lessons F.1 to F.5.
The desk
Here's the reference's app, all of it. It was checked with Flet 1.1.4 on Windows 11:
library_gui/flet_app.py"""The library desk in Flet: a search box, the catalogue as a table, lend and return. Needs Flet (Apache-2.0 licence) in your virtual environment: pip install "flet[all]" Run it from the folder that holds library/ and library_gui/: python -m library_gui.flet_app Checked by hand with Flet 1.1.4 on Windows 11. The course's automatic checks don't install packages, so they don't run it. """ from dataclasses import field import flet as ft from library import sample from library.storage import JsonStorage from library_gui.presenter import LibraryPresenter, Message, Row @ft.control class DeskView(ft.Column): """The whole desk as one control. Flet makes it a dataclass: fields need types.""" # Flet sends a control's fields to the screen. The presenter stays in Python, # so its field is marked "skip". presenter: LibraryPresenter | None = field(default=None, metadata={"skip": True}) def init(self) -> None: self.chosen = "" self.search = ft.TextField(label="Search", on_change=self.searched) self.member = ft.Dropdown( label="Member", options=[ft.DropdownOption(key=i, text=name) for i, name in self.presenter.members()], ) self.table = ft.DataTable( columns=[ft.DataColumn(label=ft.Text(name)) for name in ("Title", "Kind", "State", "Due")] ) self.status = ft.Text("Choose an item, then lend it or take it back.") self.controls = [ self.search, self.table, ft.Row( controls=[ self.member, ft.Button(content="Lend", on_click=self.lend), ft.Button(content="Return", on_click=self.give_back), ] ), self.status, ] self.refresh() def make_row(self, row: Row) -> ft.DataRow: return ft.DataRow( cells=[ft.DataCell(ft.Text(v)) for v in (row.title, row.kind, row.state, row.due)], selected=row.item_id == self.chosen, on_select_change=lambda e: self.choose(row.item_id), ) def refresh(self) -> None: self.table.rows = [self.make_row(row) for row in self.presenter.rows(self.search.value)] def choose(self, item_id: str) -> None: self.chosen = item_id self.refresh() def searched(self, e: ft.Event[ft.TextField]) -> None: self.refresh() def lend(self, e: ft.Event[ft.Button]) -> None: self.show(self.presenter.lend(self.chosen, self.member.value or "")) def give_back(self, e: ft.Event[ft.Button]) -> None: self.show(self.presenter.give_back(self.chosen)) def show(self, message: Message) -> None: self.status.value = message.text if not message.ok: self.page.show_dialog(ft.SnackBar(ft.Text(message.text))) self.refresh() def main(page: ft.Page) -> None: storage = JsonStorage("library.json") library = storage.load() if not len(library.catalogue): sample.fill(library) page.title = "Library desk" page.window.width = 760 page.window.height = 640 page.theme = ft.Theme(color_scheme_seed=ft.Colors.GREEN) page.add(DeskView(presenter=LibraryPresenter(library, storage))) if __name__ == "__main__": ft.run(main)
python -m library_gui.flet_app
Light
DarkThings to notice:
- The desk is one class.
mainis a few lines, and doesn't know anything about tables or buttons. initbuilds the controls in the order they appear on the screen, then fills the table once.- The search box's
on_changecallssearchedon every letter, so the table follows the typing, as a tkintertrace_addwould. self.member.valueis the key of the chosenDropdownOption, the member's id, while the user sees their name.or ""turns "nothing chosen" into an empty id, which the presenter turns into a message.
Try it out: lend Dune to Sam, try to lend the Atlas, search for austen, close the app 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.
pytest
The app. Put the catalogue and the overdue list in tabs. In Flet 1, ft.Tabs holds a TabBar of tab names and a TabBarView of what each tab shows, in the same order:
ft.Tabs( length=2, content=ft.Column( controls=[ ft.TabBar(tabs=[ft.Tab(label="Catalogue"), ft.Tab(label="Overdue")]), ft.TabBarView(controls=[catalogue, overdue], expand=True), ] ), )
Make the overdue list a custom control of its own, OverdueView, with a DataTable and a refresh method, as DeskView has. The desk and the overdue list both need to refresh after a lend or return, so hand one to the other, or give both to a small parent control that tells each to refresh. To test it, give main a FixedClock set weeks ahead.
Dark mode, and the browser
Add a ft.Switch labelled Dark mode above the tabs. Its on_change handler sets page.theme_mode to ft.ThemeMode.DARK or ft.ThemeMode.LIGHT (lesson F.2), from the switch's value, which is True when it's on.
Then try the app in a browser. The flet command came with flet[all] in F.1, and flet run --web serves the same app as a web page and opens it:
python -m pip show flet flet run --web library_gui/flet_app.py
Nothing in your code changes: the same controls are drawn by Flutter in the browser instead of a desktop window. If your Flet version names the option differently, flet run --help lists them. To share the app with people who don't have Python, Flet's documentation has a section on publishing, which packages it for each system.
Finished
You've built a modern app for the library, 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 app, and no traceback appears in the terminal.
- Closing the app and opening it again keeps every loan.
- The overdue tab lists late loans with their fines.
pytestpasses, with your newoverduetest.- The dark mode switch works, and the app runs in a browser.
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.