Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 40 ยท Packaging and Patterns

Separating Logic from the GUI: Models, Views and Testing

Split a Tkinter app into model, view and presenter, test the logic with unittest without opening a window, and use fake views and injected dependencies.

Most Tkinter bugs live in the logic, not in the widgets: a wrong total, a bad date, a double delete. If that logic is tangled up with entry.get() and label.config(), the only way to test it is to start the program and click. That is slow, so people stop testing, and bugs stay.

The remedy is separation. Move rules and data into plain classes that never import Tkinter, and keep the GUI as a thin layer that shows data and forwards user actions. This lesson uses a to-do list to show the model-view-presenter pattern, how to test without a window, and how to deal with the code that cannot be separated. All runnable blocks are real Python tests; only the window code is read-only.

The problem: logic inside callbacks

Python
def add_task():
    text = entry.get().strip()
    if not text:
        messagebox.showwarning("Empty", "Type a task first.")
        return
    if text.lower() in [t.lower() for t in listbox.get(0, "end")]:
        messagebox.showinfo("Duplicate", "Already in the list.")
        return
    listbox.insert("end", text)
    entry.delete(0, "end")
    counter.config(text=f"{listbox.size()} tasks")

This function reads a widget, validates, talks to the user, updates a listbox and updates a label. To test "duplicates are rejected, ignoring case" you would have to build a window. Everything except the first and last lines is logic you can test on its own.

Step 1: the model

The model holds the data and rules. It raises exceptions or returns results; it never shows dialogs.

Python
class DuplicateTask(ValueError):
    pass

class TaskList:
    def __init__(self):
        self.tasks = []                      # list of dicts: {"text", "done"}

    def add(self, text):
        text = text.strip()
        if not text:
            raise ValueError("empty")
        if any(t["text"].lower() == text.lower() for t in self.tasks):
            raise DuplicateTask(text)
        self.tasks.append({"text": text, "done": False})

    def toggle(self, index):
        self.tasks[index]["done"] = not self.tasks[index]["done"]

    def remove(self, index):
        del self.tasks[index]

    def remaining(self):
        return sum(not t["done"] for t in self.tasks)

It has no import tkinter. You can use it from a command-line tool, a web app or a test.

Step 2: tests that need no window

Python's unittest ships with the language. This block defines the model and runs real tests against it (in the Pyodide runner, we call the test runner explicitly instead of python -m unittest).

Python Run: unit tests for the task model

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 see four ok lines. Each test starts from a fresh model in setUp, so the order of tests does not matter. This is the core payoff: the rules can be checked in milliseconds, and you can add a regression test for every bug you fix.

Step 3: the presenter and the view

The view is the Tkinter code. It exposes a few tiny operations (get_input, show_tasks, show_error) and forwards button presses. The presenter holds the glue: it calls the model and tells the view what to display.

Python
class TaskPresenter:
    def __init__(self, model, view):
        self.model, self.view = model, view
        view.on_add = self.add            # the view calls this when the button is pressed

    def add(self):
        try:
            self.model.add(self.view.get_input())
        except DuplicateTask:
            self.view.show_error("Already in the list.")
        except ValueError:
            self.view.show_error("Type a task first.")
        else:
            self.view.clear_input()
        self.view.show_tasks(self.model.tasks, self.model.remaining())

The real view is a Frame with an entry, a listbox and a label; get_input returns self.entry.get(), show_error calls messagebox.showwarning, show_tasks rebuilds the listbox. It contains no rules. Because the presenter talks to the view only through these methods, a fake view can stand in for it in tests.

Python Run: the presenter tested with a fake view

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 whole add-task flow, including both error paths, ran without a window. When something breaks in the real window, you know which half to look at.

Who does what

Model Data and rules, no Tkinter
View Widgets, shows data, forwards clicks
Presenter Calls the model, updates the view

Tests target the model and the presenter.

1 / 2

Injecting dependencies

Anything that touches the outside world should be passed in, not hard-coded: the file path, the clock, the dialog function, the database. Then a test can substitute a harmless version.

Python
class Exporter:
    def __init__(self, tasks, write_file, ask_path, today):
        self.tasks, self.write_file, self.ask_path, self.today = tasks, write_file, ask_path, today

    def export(self):
        path = self.ask_path()
        if not path:
            return False
        lines = [f"Tasks on {self.today()}"] + [f"- {t['text']}" for t in self.tasks]
        self.write_file(path, "\n".join(lines))
        return True

In the app you pass filedialog.asksaveasfilename, a function that writes the file and datetime.date.today. In a test you pass a lambda returning a fixed path, a function that appends to a list, and a lambda returning a fixed date.

Python Run: dependency injection with fakes

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.

Testing the GUI itself

Some behavior can only be checked with real widgets: that a button exists, that a menu command is wired. Options:

  • Smoke tests: create the app, call root.update(), check that nothing raises, and destroy it. Needs a display; on Linux CI use a virtual one such as xvfb-run.
  • Event simulation: widget.invoke() presses a button, event_generate("<Key-a>") simulates a key, entry.insert(0, "x") fills a field. Call root.update_idletasks() before asserting.
  • Skip when no display: unittest.skipIf on tkinter.TclError from tk.Tk().

Because the separated code is already tested, these GUI tests can stay few and shallow.

Common mistakes

  • Making the model import tkinter for StringVar. Use plain attributes; let the view own the variables.
  • A model method that shows a messagebox. Raise an exception and let the presenter decide how to tell the user.
  • Presenter logic copied into the view "just this once".
  • Testing through the GUI only. A test that needs a window is a test that does not run on most servers.
  • Mocking everything. Plain fake objects, like FakeView above, read better than complex mock set-ups.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these belongs in the model?

    Rules and data live in the model; widget calls and dialogs belong to the view.
  2. 2. What is the benefit of a fake view in tests?

    The presenter only talks to the view through a few methods, so a recording stand-in is enough.
  3. 3. Why pass ask_path and today as parameters to the Exporter?

    Injected dependencies make behavior deterministic and independent of the real file system and user.
  4. 4. How should the model report a validation error?

    The model stays free of any UI; the presenter chooses how to show the problem.

Summary

  • Keep rules and data in plain classes; keep widgets in thin view classes; glue them with a presenter.
  • Test the model and presenter with unittest and a fake view; no window needed.
  • Inject file dialogs, clocks and storage so tests can control them.
  • Keep GUI tests few: smoke tests and a handful of invoke() checks.
  • The model raises exceptions; the view decides how to display them.

Next: Threads and Background Work