Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 40 ยท Packaging and Patterns

Structuring Tkinter Apps with Classes and Multiple Pages

Organize a Tkinter program with classes: subclass Tk and Frame, share state between pages, switch screens, use callbacks and virtual events, and lay out files.

Beginner Tkinter programs are a list of statements and global variables. That works for 50 lines. At 300 lines you cannot find anything, callbacks need global, and two windows cannot share a variable without confusion. The standard cure is object-oriented structure: one class for the application, one class per screen, and a clear place for state.

This lesson shows the class layout that most Tkinter programs settle on, how pages talk to each other, how to switch screens, and how to split a program into files. The window code is read-only; the stand-ins model the navigation and message flow so you can check the logic without a display.

From globals to a class

A script with globals:

Python
count = 0
def increment():
    global count
    count += 1
    label.config(text=str(count))

root = tk.Tk()
label = tk.Label(root, text="0")
label.pack()
tk.Button(root, text="+1", command=increment).pack()
root.mainloop()

The same program as a class:

Python
import tkinter as tk
from tkinter import ttk

class CounterApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Counter")
        self.count = tk.IntVar(value=0)
        self._build()

    def _build(self):
        ttk.Label(self, textvariable=self.count, font=("Segoe UI", 28)).pack(padx=40, pady=(20, 8))
        ttk.Button(self, text="+1", command=self.increment).pack(pady=(0, 20))

    def increment(self):
        self.count.set(self.count.get() + 1)

if __name__ == "__main__":
    CounterApp().mainloop()

A small window shows a large number and a "+1" button; each press adds one. What changed: the state (self.count) lives on the object, the callback is a method (so self is available), widgets are created in _build, and the program starts only when the file is run, not when it is imported (if __name__ == "__main__"). Using a StringVar/IntVar also means the label updates itself, no config call needed.

There are two usual ways to subclass:

  • Subclass tk.Tk (as above): the class is the window. Simple and common.
  • Subclass ttk.Frame and hold the root: class App(ttk.Frame) with def __init__(self, master). This makes the app embeddable in another window and easier to test. Both are fine; be consistent.

Do not run a long __init__ that builds hundreds of widgets inline. Split into _build_menu, _build_toolbar, _build_body, _bind_events. Each method then has one purpose.

One class per screen

A multi-screen app (login, list, details) uses one Frame subclass per screen, all stacked in the same place; showing one is a matter of raising it:

Python
class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Notes")
        self.geometry("420x300")
        self.session = {"user": None, "notes": []}     # shared data (not self.state: Tk has a state() method)
        container = ttk.Frame(self)
        container.pack(fill="both", expand=True)
        container.rowconfigure(0, weight=1)
        container.columnconfigure(0, weight=1)

        self.pages = {}
        for Page in (LoginPage, NotesPage):
            page = Page(container, controller=self)
            self.pages[Page.__name__] = page
            page.grid(row=0, column=0, sticky="nsew")  # all in the same cell
        self.show("LoginPage")

    def show(self, name):
        page = self.pages[name]
        page.tkraise()
        if hasattr(page, "on_show"):
            page.on_show()

class LoginPage(ttk.Frame):
    def __init__(self, parent, controller):
        super().__init__(parent, padding=20)
        self.controller = controller
        self.name = tk.StringVar()
        ttk.Label(self, text="Your name").pack(anchor="w")
        ttk.Entry(self, textvariable=self.name).pack(fill="x", pady=6)
        ttk.Button(self, text="Continue", command=self.login).pack(anchor="e")

    def login(self):
        self.controller.session["user"] = self.name.get().strip() or "guest"
        self.controller.show("NotesPage")

class NotesPage(ttk.Frame):
    def __init__(self, parent, controller):
        super().__init__(parent, padding=20)
        self.controller = controller
        self.greeting = ttk.Label(self)
        self.greeting.pack(anchor="w")

    def on_show(self):
        self.greeting.config(text=f"Hello, {self.controller.session['user']}!")

The window first shows a login form. Pressing Continue switches to the notes page, which greets the user by name. Both pages were created at start and placed in the same grid cell; tkraise() lifts one above the others. The page receives controller (the app) in its constructor, which is the dependency it uses to navigate and to read shared state. Pages never refer to each other directly, so adding a third page needs no change in the existing ones.

A typical Tkinter project

App Tk subclass: window, pages, state
Pages One Frame subclass each
Logic Plain Python, no widgets
Storage Files or SQLite

The GUI layer stays thin.

1 / 2

The block below is not Tkinter. It models the controller and pages with plain objects so you can see the order of calls, including a back stack.

Python Stand-in: page controller with a back stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Talking between pages

Pages should not reach into each other's widgets. There are three clean options.

1. Shared state on the controller. Simple data (controller.state, or a model object) that pages read in on_show.

2. Callbacks. A page receives functions it can call: NotesPage(parent, on_logout=self.logout). It does not need to know who implements them.

3. Virtual events. Tkinter lets you define custom events and generate them on any widget:

Python
self.event_generate("<<NoteSaved>>", when="tail")          # in a page
app.bind("<<NoteSaved>>", lambda e: self.refresh_status())  # in the app

Virtual events are named with double angle brackets. They travel through the normal event system, so they run in the main thread, which is also why they are the safe way to notify the GUI from a worker thread (Threads and Background Work).

A small observer (publish/subscribe) object is another option and the one that works best for tests. This stand-in implements one:

Python Stand-in: a tiny event bus between pages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Keep widgets and logic apart

The more a method mixes entry.get(), validation, file writing and label.config, the harder it is to test and change. Prefer this split:

  • Model/logic classes know nothing about Tkinter: they validate, calculate, store.
  • View classes (pages and widgets) create the controls and show data.
  • Glue methods (callbacks) read widgets, call the model, update the widgets.

The next lesson (Separating Logic from the GUI) takes this further with a model and tests.

Suggested file layout

TEXT
notes_app/
    __main__.py        # from notes_app.app import App; App().mainloop()
    app.py             # App(tk.Tk)
    pages/
        login.py
        notes.py
    models.py          # data classes, no tkinter imports
    storage.py         # load/save
    resources/         # icons, images

Run it with python -m notes_app. Pages import from models, never the other way around. Circular imports between pages are a sign that navigation goes through the controller instead of directly.

Common mistakes

  • Using a mutable global instead of attributes on the app or a model.
  • Calling Page().pack() in __init__ of the page itself; the parent decides placement.
  • Forgetting super().__init__() in a Tk or Frame subclass, which causes AttributeError: _w or similar.
  • Naming an attribute self.state in a Tk subclass: Tk.state() is a window method (maximize, iconify), so the assignment breaks it. Use self.data, self.session or a model object. The examples above use session for that reason.
  • Creating all pages at start when some are expensive; create on first show instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why subclass tk.Tk or ttk.Frame for an application?

    A class groups widgets, callbacks and state, avoiding global variables.
  2. 2. How does tkraise() help with multiple screens?

    All pages sit in the same cell; the raised one is visible.
  3. 3. Why should a page not call methods on another page's widgets?

    Decoupled pages can be changed or reused without breaking each other.
  4. 4. What is the purpose of if name == 'main': around the mainloop call?

    Imports (for example from tests) should not open a window.

Summary

  • Put state and callbacks in classes: an App (Tk subclass) plus one Frame subclass per screen.
  • Build the UI in small _build_* methods and start the program under if __name__ == "__main__".
  • Pages share data through a controller or model and communicate by callbacks or virtual events.
  • Keep logic in plain classes without Tkinter imports.
  • Avoid attribute names that clash with Tk methods, such as state.

Next: Separating Logic from the GUI