Live values and tables
Last updated
A search box should search as you type, and the catalogue should be a table you can pick a row from. In this lesson you'll bind a box to a StringVar that tells you when it changes, and fill a ttk.Treeview table from the presenter, without the rows doubling up.
By the end of this lesson you can
- Bind an entry to a
StringVar, and react to changes withtrace_add - Explain the Observer pattern a variable trace follows
- Fill a
ttk.Treeviewtable from the presenter, and read the selected row - Empty a table before filling it again
Values that tell you when they change
A search box should run the search each time a letter is typed. The box could be asked over and over, but there's a better way: let the value tell you when it changes.
That's the Observer pattern, one of the classic design patterns (lesson 4.16 met others). An object keeps a list of observers, functions to call, and calls each one whenever it changes. Here's a pretend version in plain Python. Press Run:
searched never asks for the text. It's registered once with trace_add, and each set calls it. tkinter's StringVar works the same way, with the same method name: trace_add("write", callback) calls callback every time the value is written. (tkinter's version passes the callback three arguments about the variable, which most programs ignore with *args.)
A live search box
Now the real thing. Save this as search.py and run it:
import tkinter as tk from tkinter import ttk TITLES = ["Dune", "Emma", "Middlemarch", "Rivers of Ice"] class SearchWindow(ttk.Frame): def __init__(self, root: tk.Misc) -> None: super().__init__(root, padding=12) self.search = tk.StringVar() self.found = tk.StringVar() ttk.Entry(self, textvariable=self.search).pack(fill="x") ttk.Label(self, textvariable=self.found).pack(anchor="w", pady=(8, 0)) self.search.trace_add("write", self.searched) self.searched() def searched(self, *args: object) -> None: text = self.search.get().lower() matches = [title for title in TITLES if text in title.lower()] self.found.set(", ".join(matches) or "Nothing matches.") root = tk.Tk() root.title("Search") SearchWindow(root).pack(fill="both", expand=True) root.mainloop()
Type m, then i: the label changes with each letter.
search.py after typing m.textvariable=self.searchcouples the entry to the variable. Typing in the box writes the variable, andself.search.set(...)would change the box.- The label is coupled to
self.foundthe same way, sosearchedonly sets a variable, and the label shows it. self.searched()at the end of__init__fills the label once at the start, before anything's typed.
The wrong way. Keep the search text in a plain attribute instead:
class SearchWindow(ttk.Frame): def __init__(self, root: tk.Misc) -> None: super().__init__(root, padding=12) self.search = "" ttk.Entry(self).pack(fill="x") ...
There's no error. The box shows what you type, but self.search is still "": the box keeps its own text, and nothing copies it into the attribute or tells your code it changed. A plain str can't be observed. Only a tkinter variable can be coupled to a widget.
The catalogue as a table
tkinter's table is ttk.Treeview. It can show a tree, like folders, but with show="headings" it's a plain table with column headings. Here's how the reference builds one:
library_gui/tk_app.py, lines 27–41def 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)
columns=names the columns.headinggives each its title, andcolumnits width.selectmode="browse"lets the user pick one row at a time.- The first lines make each row as tall as a line of text, plus a little. Without them, letters like y and g are cut off on high-resolution screens, where text is drawn bigger but rows aren't.
And here's how it fills it from the presenter:
library_gui/tk_app.py, lines 55–67def 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)
Each row gets iid=row.item_id, its own id in the table. So when the user picks a row, self.table.selection() gives back ("b1",), the item's id, ready to hand to presenter.lend. The window never has to look the item up.
Fill it twice
The wrong way. refresh starts by deleting every row. Leave that out, and fill a table a second time. Save this as twice.py and press Refresh:
import tkinter as tk from tkinter import ttk ROWS = [("b1", "Dune"), ("b2", "Emma")] root = tk.Tk() table = ttk.Treeview(root, columns=["title"], show="headings") table.heading("title", text="Title") table.pack() def refresh() -> None: for item_id, title in ROWS: table.insert("", "end", iid=item_id, values=[title]) refresh() ttk.Button(root, text="Refresh", command=refresh).pack() root.mainloop()
Exception in Tkinter callback Traceback (most recent call last): ... File "twice.py", line 14, in refresh table.insert("", "end", iid=item_id, values=[title]) ... _tkinter.TclError: Item b1 already exists
Every row id must be unique, and b1 is already there. Without iid=, it would be worse: Treeview would make up new ids, there'd be no error, and every search would add the whole catalogue again under the old rows.
The fix is the reference's first two lines of refresh: delete every row with delete(*self.table.get_children()), then insert them all again. The reference also remembers which row was picked, and picks it again if it's still there, so a search doesn't lose the user's place.
Emptying and refilling is the simplest way to keep a table right: whatever changed, the table shows the presenter's rows exactly. For a few thousand rows it's quick enough.
Check
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.