tkinter and CustomTkinter · lesson 2 of 8
Parts in this lesson
Aclass CounterWindow(ttk.Frame)4.5: a subclass
Bsuper().__init__(root)4.6: extending
Ccommand=self.lenda method, not a call
DCountWindow(root, library)handed what it needs

The window is a class

Last updated

A window holds widgets, and it has things it does when they're clicked: that's data and methods, so it's a class. In this lesson you'll write a window as a subclass of a tkinter frame, hand a button a method to call, and give the window the library it shows instead of letting it make its own.

By the end of this lesson you can

  • Write a window as a subclass of ttk.Frame that keeps its widgets as attributes
  • Pass a method to command=, and explain why brackets break it
  • Hand a window the objects it needs through __init__
  • Run a window from a package with python -m

A window that remembers

Lesson T.1's window was a list of statements. That's fine for two widgets, but a real window has dozens, and its buttons need to reach the others: Lend must change the label that shows the count. A class keeps them together.

Save this as counter.py and run it:

import tkinter as tk
from tkinter import ttk


class CounterWindow(ttk.Frame):
    """A window that counts how many items have been lent today."""

    def __init__(self, root: tk.Misc) -> None:
        super().__init__(root, padding=20)
        self._count = 0
        self._label = ttk.Label(self, text="Nothing lent yet")
        self._label.pack(pady=(0, 10))
        ttk.Button(self, text="Lend one", command=self.lend).pack()

    def lend(self) -> None:
        self._count += 1
        self._label.configure(text=f"Lent today: {self._count}")


root = tk.Tk()
root.title("Library desk")
CounterWindow(root).pack()
root.mainloop()

Press Lend one a few times and watch the label count.

A window saying Lent today: 3 above a Lend one button
counter.py after three clicks.
  • CounterWindow is a ttk.Frame (lesson 4.5): a plain rectangle that holds other widgets. Everything a frame can do, the window can do, like .pack().
  • __init__ extends the frame's own (lesson 4.6): super().__init__(root, padding=20) makes the frame, then the rest adds the widgets to it, with self as their parent.
  • The label is kept as self._label, so lend can change it later. It starts with _ because it's for this class only (lesson 4.2). The button isn't kept, because nothing needs it again.
  • configure(text=...) changes a widget's options after it's made.

_count is the window's own data, and lend is its own behaviour. Outside code makes a CounterWindow and packs it; it never touches the label.

A method, not a call

command=self.lend hands the button the method itself, so the button can call it later, on each click. Brackets would call it now.

The wrong way. Change the button's line to this, with brackets, and run it:

ttk.Button(self, text="Lend one", command=self.lend()).pack()

There's no error, but the window opens already saying Lent today: 1, and the button does nothing. self.lend() ran once, while the window was being built, and its result, None, became the command. A button with no command does nothing when clicked.

Here's the same mistake with a pretend button, so you can see it step by step. Press Run:

Step 2 code button.py
Edit the code, then run it again

lend() runs before the window is even open, and wrong.command is None. Functions and methods are objects (lesson 3.1): without brackets you pass the object, and with brackets you pass what it returns.

Which line gives a button a method to call on each click?

Hand the window its library

The window should show the real library. It could make its own Library inside __init__, but then nothing outside could choose which library, and a test couldn't give it a small one with a fixed date. That's the reason the capstone hands the library its clock and the menu its storage (lessons C.4 and C.7): an object is given what it needs instead of making it.

In your project folder, next to library/, make a package for the windows:

The project folder
your project folder
├── library/          the capstone's package
├── library_gui/      new: the windows
│   ├── __init__.py   empty
│   └── count.py
└── tests/

Save this as library_gui/count.py:

import tkinter as tk
from tkinter import ttk

from library import sample
from library.desk import Library


class CountWindow(ttk.Frame):
    """Shows how many items the library holds. It's handed the library it shows."""

    def __init__(self, root: tk.Misc, library: Library) -> None:
        super().__init__(root, padding=20)
        self._library = library
        count = len(library.catalogue)
        ttk.Label(self, text=f"The library holds {count} items.").pack()


def main() -> None:
    library = Library()
    sample.fill(library)
    root = tk.Tk()
    root.title("Library desk")
    CountWindow(root, library).pack()
    root.mainloop()


if __name__ == "__main__":
    main()

Run it as a module, from the project folder, as the capstone runs python -m library:

Terminal
python -m library_gui.count

main() makes the library and fills it, then hands it to the window. The window only shows what it's given. Lesson T.4 puts one more class between them, so the window doesn't need to know the library at all.

Check

Why does CounterWindow keep the label as self._label?
A button made with command=self.lend() does nothing when clicked. Why?
Why is CountWindow handed a Library instead of making its own?

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