Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 40 ยท Getting Started

Structuring Tkinter Programs with Classes

Organize Tkinter code with classes: subclass Tk or Frame, keep state in attributes, separate the model from the view, and split big windows into reusable parts.

Small examples put everything at the top level: a root, some widgets, some global variables and a few functions. That works for twenty lines. At two hundred lines, the functions share globals, widget names collide and nothing can be reused. The standard cure is to organize the program with classes. In Tkinter this is natural, because a widget is already an object and a window is a widget with children.

Why globals become a problem

Python
import tkinter as tk

count = 0

def add():
    global count
    count += 1
    label.config(text=str(count))

root = tk.Tk()
label = tk.Label(root, text="0")
label.pack()
tk.Button(root, text="Add", command=add).pack()
root.mainloop()

This is fine, but add can only work with the one global label. You cannot open two counters, test add without a window, or change the label's name without searching the whole file. A class fixes all three by turning those globals into attributes.

Pattern 1: subclass Tk

The most common layout subclasses tk.Tk. Build the widgets in __init__, keep the state on self, and make callbacks methods.

Python
import tkinter as tk

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

        self.label = tk.Label(self, text="0", font=("Segoe UI", 24))
        self.label.pack(padx=40, pady=(20, 10))

        tk.Button(self, text="Add", command=self.add).pack(pady=(0, 20))

    def add(self):
        self.count += 1
        self.label.config(text=str(self.count))

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

command=self.add passes a bound method: when Tk calls it, Python supplies self automatically. The if __name__ == "__main__": guard lets other files import the class without launching a window.

Pattern 2: subclass Frame

A Frame subclass is a reusable component. It does not own a window, so it can live in the main window, in a dialog or in a tab. Each frame builds only its own widgets and exposes a small interface.

Python
import tkinter as tk

class LabeledEntry(tk.Frame):
    """A label and an entry side by side, with a get/set interface."""
    def __init__(self, parent, caption, width=20):
        super().__init__(parent)
        self.var = tk.StringVar()
        tk.Label(self, text=caption, width=10, anchor="w").pack(side="left")
        tk.Entry(self, textvariable=self.var, width=width).pack(side="left")

    def get(self):
        return self.var.get()

    def set(self, value):
        self.var.set(value)

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Sign up")
        self.name = LabeledEntry(self, "Name")
        self.email = LabeledEntry(self, "Email")
        self.name.pack(padx=12, pady=6)
        self.email.pack(padx=12, pady=6)
        tk.Button(self, text="Show", command=self.show).pack(pady=8)

    def show(self):
        print(self.name.get(), self.email.get())

App().mainloop()

App has no idea how LabeledEntry is built, and LabeledEntry has no idea what App does with its text. That separation is what makes components reusable.

flowchart TB
  App["App (Tk)"] --> A["LabeledEntry: Name"]
  App --> B["LabeledEntry: Email"]
  App --> C["Button: Show"]
  A --> A1["Label"]
  A --> A2["Entry"]
  B --> B1["Label"]
  B --> B2["Entry"]

Each component hides its own children. The app talks to the components, not to the inner widgets.

Pattern 3: separate model and view

The best way to make a GUI testable is to keep the rules of your program out of the widget code. A model is a plain Python class with no Tkinter in it. The view (the window) only shows the model and forwards user actions to it.

The runnable stand-in below follows that idea. The "view" is a fake that records what it was told to show; the model is real logic you could drop into a real Tkinter window unchanged.

Python Stand-in: model and view kept apart

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.

You can test CounterModel with ordinary unit tests; no display needed. The real view would call self.label.config(text=...) inside refresh() and use messagebox.showwarning for the error.

Calling the parent correctly

Always call super().__init__() first in a subclass of any widget, before you create children. Forgetting it gives errors such as AttributeError: ... object has no attribute 'tk'. When subclassing Frame, pass the parent through and accept extra options:

Python
class Card(tk.Frame):
    def __init__(self, parent, title, **options):
        super().__init__(parent, **options)
        tk.Label(self, text=title, font=("Segoe UI", 12, "bold")).pack()

Avoid naming your own attributes like Tk methods. A subclass of Tk that defines self.title = "Counter" replaces the title() method and breaks self.title("..."). Similar traps: self.state, self.config, self.children, self.master, self.size. If in doubt, give your attribute a distinct name like self.player_name.

Communicating between components

Components should not reach into each other's widgets. Three clean options:

  1. Callbacks. The parent passes a function in: Toolbar(self, on_save=self.save).
  2. Shared variables. Both sides use the same StringVar or IntVar (Tkinter Variables).
  3. Virtual events. One component calls event_generate("<<Saved>>") and others bind to it (Bind and Events).

The callback style is simplest. Here it is in action without a display:

Python Stand-in: a component that takes a callback

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.

The toolbar knows nothing about the editor; it only calls what it was given. Swap the editor for another class and the toolbar keeps working.

A suggested project layout

For anything beyond one file:

Text
myapp/
  main.py          # creates the App and runs mainloop
  app.py           # the App(tk.Tk) class
  views/           # Frame subclasses
  models.py        # plain-Python logic and data
  assets/          # icons and images

Packaging and other patterns are covered in chapter 8. For now, remember the rule of thumb: widgets in classes, rules in plain Python.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a Frame subclass call super().init(parent) before creating child widgets?

    The parent initializer creates the underlying Tk widget. Children need it to exist first.
  2. 2. What does command=self.add pass to the button?

    self.add without parentheses is a bound method. Tk calls it on click, and self is supplied automatically.
  3. 3. In a subclass of tk.Tk, which assignment is dangerous?

    title is a method on Tk. Assigning a string to self.title replaces it, so self.title('...') later fails.
  4. 4. What is the main benefit of a plain-Python model class?

    Logic with no Tkinter imports can be unit-tested directly and reused with a different interface.

Summary

  • Turn globals into attributes by subclassing tk.Tk (the app) and tk.Frame (reusable components).
  • Call super().__init__() first; make callbacks methods and pass self.method as command.
  • Keep rules in a model class with no GUI imports; keep the widgets in the view.
  • Components talk through callbacks, shared variables or virtual events, not by reaching into each other.
  • Never shadow Tk method names such as title, state or config with your own attributes.

Next: Labels, Fonts and Colors