Home โ€บ Curriculum โ€บ Desktop Apps with Tkinter
Updated for Python 3.12+ ยท November 2026

๐Ÿ–ฅ๏ธ Desktop Apps with Tkinter
in Python

Learn Tkinter step by step: windows, widgets, pack and grid, events, StringVar, Entry and Listbox, plus a full to-do app and runnable model and event-loop demos.

Intermediate 8 lessonsโ‰ˆ 48 min read by Glenn Pansensoy

What this lesson is about

Tkinter is the graphical toolkit that ships with Python. With it you can open a window, put buttons, text boxes and lists inside it, and react when someone clicks or types. It is used for small internal tools, teaching programs, file renamers, data-entry forms and quick front ends for scripts that would otherwise need a command line.

The most important thing to understand is that a GUI program works differently from the scripts you have written so far. A normal script runs from the top to the bottom and ends. A GUI program builds its widgets, then calls mainloop(), which waits for events such as clicks and key presses and calls your functions when they happen. You stop telling the computer what to do next and start telling it what to do when something happens. That idea is called event-driven programming, and it is the same idea behind web pages, mobile apps and games.

A window cannot be opened inside a web page, so the Tkinter code on this page is marked as run on your computer, and I syntax-checked it but I will not claim output I have not seen. To let you experiment right here, the examples you can press Run on teach the logic behind the interface with the standard library alone: a to-do model that notifies observers, a StringVar-style variable, a layout calculator and a tiny event loop. We finish by joining these ideas into a complete to-do application you can copy.

What you will learn

  • โœ“Create a root window and start the event loop with mainloop()
  • โœ“Add Label, Button, Entry and Listbox widgets and configure them
  • โœ“Arrange widgets with pack and grid and know when to use which
  • โœ“Connect user actions to functions with command= and bind()
  • โœ“Use StringVar so widgets and code share one piece of state
  • โœ“Read and change the contents of an Entry and a Listbox
  • โœ“Separate your data model from your interface so it can be tested
  • โœ“Assemble a complete to-do app with add, delete, complete and save

Why programmers should learn this

  • โ˜…Tkinter needs no installation on most systems, so a script with a window can be shared with someone who has never opened a terminal.
  • โ˜…Small desktop tools such as batch renamers, report generators and data-entry forms are often easier to use with buttons than with command-line flags.
  • โ˜…Event-driven thinking carries over to web front ends, mobile apps, game loops and asynchronous servers, so this one lesson pays off in many places.
  • โ˜…Splitting a program into a model and a view is a core design habit, and a to-do app is a small, friendly place to practise it.
  • โ˜…A visible program is motivating: seeing your own window respond to a click is a great confidence boost for a beginner.

Your first window and the event loop

Every Tkinter program starts with a root window, created with tk.Tk(). You can then set its title and size, add widgets to it, and finally call root.mainloop(). That last call is not decoration: it starts the event loop, which keeps the window alive, repaints it and waits for the user. Code written after mainloop() does not run until the window is closed.

A widget is any visible element: a Label shows text, a Button can be clicked, an Entry is a one-line text box and a Listbox shows a list of choices. You create a widget by passing its parent as the first argument, for example ttk.Label(root, text='Hello'). Creating the widget does not show it. It appears only after you place it with a geometry manager such as pack() or grid(), which is the subject of the next section.

I import tkinter as tk for the classic widgets and from tkinter import ttk for the themed ones. The themed widgets look more native on every platform, so I use them whenever a ttk version exists. The example below is the smallest useful program: a label, a button that changes the label, and the event loop. Save it as a file and run it with Python on your own machine.

first_window.pyrun on your computer
import tkinter as tk
from tkinter import ttk

def on_click():
    label.config(text="You clicked the button!")

root = tk.Tk()
root.title("My first window")
root.geometry("320x160")

label = ttk.Label(root, text="Hello, Tkinter")
label.pack(pady=20)

button = ttk.Button(root, text="Click me", command=on_click)
button.pack()

root.mainloop()

Line by line

  1. 1-2Import the classic module as tk and the themed widgets as ttk.
  2. 4-5A callback function. Tkinter will call it when the button is pressed. It changes the label text with config.
  3. 7-9Create the root window, set a title and give it a size of 320 by 160 pixels.
  4. 11-12Make a label inside the root window and place it with pack, adding vertical padding.
  5. 14-15Make a button, pass the function name (without parentheses) as command, and pack it.
  6. 17Start the event loop. The program waits here until the window closes.
โš ๏ธ

Write command=on_click, not command=on_click(). With the parentheses you call the function immediately and give Tkinter its return value (None) instead of the function.

Laying out widgets with pack and grid

A geometry manager decides where each widget goes and how big it is. The two you will use most are pack and grid. pack stacks widgets one after another against a side of the window: top to bottom by default, or left to right with side='left'. It is perfect for toolbars and simple vertical layouts. grid places widgets in rows and columns like a spreadsheet, which is the natural fit for forms where labels line up above input boxes.

There is one rule you must remember: never mix pack and grid inside the same parent container, because the two managers will fight over the space and your program may freeze. If you need both, put a Frame inside the window, and let each frame use its own manager. Frames are invisible boxes that group widgets, and thinking in nested frames is how larger layouts are built.

Two options control resizing. sticky (grid) or fill (pack) says how a widget stretches inside its cell, and weight on columnconfigure and rowconfigure says which columns and rows grow when the window is enlarged. Without a weight, a column keeps its natural size, so a text box will not follow the window edge. The form below uses grid, and after it you can run a pure-Python model that works out how a grid is sized, so the idea of rows and columns taking the largest widget is clear.

grid_form.pyrun on your computer
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("Sign-up form")

form = ttk.Frame(root, padding=12)
form.grid(row=0, column=0, sticky="nsew")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

ttk.Label(form, text="Name").grid(row=0, column=0, sticky="w", pady=4)
name_entry = ttk.Entry(form, width=28)
name_entry.grid(row=0, column=1, sticky="ew", padx=(8, 0))

ttk.Label(form, text="Email").grid(row=1, column=0, sticky="w", pady=4)
email_entry = ttk.Entry(form, width=28)
email_entry.grid(row=1, column=1, sticky="ew", padx=(8, 0))

ttk.Button(form, text="Submit").grid(row=2, column=1, sticky="e", pady=(10, 0))
form.columnconfigure(1, weight=1)

root.mainloop()

Line by line

  1. 4-5Create the window and give it a title.
  2. 7-10Put a padded frame in the window using grid, and give the window's only row and column a weight so the frame grows with the window.
  3. 12-14Row 0: a label in column 0 aligned to the west edge (sticky='w') and an entry in column 1 that stretches east-west with sticky='ew'.
  4. 16-18Row 1 repeats the pattern for an email field.
  5. 20-21A submit button in column 1 aligned to the east, then a weight on column 1 so the entry boxes stretch when the window is resized.
  6. 23Start the event loop.
Model: how grid sizes columns and rows
# A tiny model of how grid decides column widths and row heights.
widgets = {
    (0, 0): ("Name label", 40, 18),
    (0, 1): ("Name entry", 200, 22),
    (1, 0): ("Email label", 46, 18),
    (1, 1): ("Email entry", 200, 22),
    (2, 1): ("Submit", 80, 26),
}

def grid_sizes(items):
    cols, rows = {}, {}
    for (r, c), (_, w, h) in items.items():
        cols[c] = max(cols.get(c, 0), w)
        rows[r] = max(rows.get(r, 0), h)
    return cols, rows

cols, rows = grid_sizes(widgets)
print("column widths:", dict(sorted(cols.items())))
print("row heights:  ", dict(sorted(rows.items())))
print("natural window size:", sum(cols.values()), "x", sum(rows.values()))

def distribute(extra, weights):
    total = sum(weights.values())
    return {k: round(extra * w / total) if total else 0 for k, w in weights.items()}

print("extra 100px with weights {0:0, 1:1}:", distribute(100, {0: 0, 1: 1}))
print("extra 90px with weights {0:1, 1:2}:", distribute(90, {0: 1, 1: 2}))
Expected output
column widths: {0: 46, 1: 200}
row heights:   {0: 22, 1: 22, 2: 26}
natural window size: 246 x 70
extra 100px with weights {0:0, 1:1}: {0: 0, 1: 100}
extra 90px with weights {0:1, 1:2}: {0: 30, 1: 60}

Line by line

  1. 1-8Describe widgets by their (row, column) cell and a pixel width and height. The numbers are invented for the demonstration.
  2. 10-15A grid column is as wide as its widest widget and a row is as tall as its tallest, so we take the maximum per column and per row.
  3. 17-20Print the sizes and the natural size of the window, which is the sum of all columns by the sum of all rows.
  4. 22-24Extra space from a resized window is shared out in proportion to each column's weight. A weight of 0 gets none.
  5. 26-27With weights 0 and 1 the second column takes everything. With weights 1 and 2 it gets two thirds.
๐Ÿ’ก

When a layout looks wrong, give the frames a temporary background colour. It shows you instantly which container is taking the space.

Events, callbacks and bind

A callback is a function you give to Tkinter so that it can call you back later. The command= option of a button is the simplest kind. For everything else, such as key presses, mouse movement, focus changes or window resizing, you use widget.bind(sequence, function). The sequence is a short string in angle brackets, like <Return>, <Button-1> (left click), <KeyPress> or <Configure>.

A function bound with bind receives one argument, an event object that describes what happened. Useful attributes include event.x and event.y for the mouse position, event.char and event.keysym for the key pressed, and event.widget for the widget that received it. A command callback receives nothing, so a function that works for both a click and a key press is usually written as def handler(event=None).

Events travel through a binding hierarchy: first the widget, then its class, then the toplevel window, then all widgets, and you can stop the chain by returning the string 'break'. You rarely need this on day one, but it explains why a shortcut bound on the root window works even when a child widget has the focus. The static block shows several bindings in a real window. The runnable block that follows builds a little event loop from a queue and a dictionary of handlers, so you can see what mainloop() is actually doing.

events.pyrun on your computer
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("Events")
status = tk.StringVar(value="Move the mouse or press a key")
ttk.Label(root, textvariable=status, padding=20).pack()

def on_click(event):
    status.set(f"Clicked at x={event.x}, y={event.y}")

def on_key(event):
    status.set(f"Key pressed: {event.keysym!r}")

def on_enter(event=None):
    status.set("You pressed Enter")

root.bind("<Button-1>", on_click)
root.bind("<KeyPress>", on_key)
root.bind("<Return>", on_enter)

root.mainloop()

Line by line

  1. 1-4Import, create the window and set a title.
  2. 5-6A StringVar holds the text shown in the label. The label watches it through textvariable.
  3. 8-9A handler for left clicks. Because it is bound, it receives an event with the mouse position.
  4. 11-12A handler for any key. event.keysym is the key's name, such as a or space.
  5. 14-15A handler for Enter. The default event=None means it also works as a button command.
  6. 17-19Bind each sequence to its handler on the root window. When several bindings match, the most specific one runs, here <Return> rather than the generic key one, on the same widget.
Model: an event loop from a queue
from collections import deque

class MiniLoop:
    """What mainloop() does, without a window."""
    def __init__(self):
        self.queue = deque()
        self.handlers = {}
        self.log = []
        self.running = True

    def bind(self, name, func):
        self.handlers.setdefault(name, []).append(func)

    def post(self, name, **data):
        self.queue.append((name, data))

    def run(self):
        while self.running and self.queue:
            name, data = self.queue.popleft()
            for func in self.handlers.get(name, []):
                func(**data)
            if not self.handlers.get(name):
                self.log.append(f"ignored {name}")

loop = MiniLoop()
clicks = []

def handle_click(x, y):
    clicks.append((x, y))
    loop.log.append(f"click at {x},{y}")

def handle_key(key):
    loop.log.append(f"key {key}")
    if key == "Escape":
        loop.running = False

loop.bind("click", handle_click)
loop.bind("key", handle_key)

loop.post("click", x=10, y=20)
loop.post("key", key="a")
loop.post("resize", w=800, h=600)
loop.post("key", key="Escape")
loop.post("click", x=99, y=99)

loop.run()
print("\n".join(loop.log))
print("clicks handled:", clicks)
print("events left in queue:", len(loop.queue))
Expected output
click at 10,20
key a
ignored resize
key Escape
clicks handled: [(10, 20)]
events left in queue: 1

Line by line

  1. 3-9A small class with a queue of waiting events, a table of handlers per event name, a log and a running flag.
  2. 11-12bind registers a function under an event name, just as widget.bind does.
  3. 14-15post is what the operating system does when something happens: it puts an event on the queue.
  4. 17-23run is the loop. It takes the oldest event, calls every handler registered for it, and notes events nobody listens for.
  5. 26-35Two handlers. The key handler stops the loop when it sees Escape, like closing the window.
  6. 37-47Register the handlers, post five events including one nobody handles, run the loop and print the results.

Look at the final line of output: the last click is still waiting in the queue because the loop stopped at Escape. A real window behaves the same way. Once you call destroy(), events that have not been handled are simply discarded.

StringVar and sharing state with widgets

Tkinter has special variable classes: StringVar, IntVar, DoubleVar and BooleanVar. You attach one to a widget with textvariable= (or variable= for checkbuttons and radiobuttons), and then the widget and your code share a single value. Call var.set('text') and the label updates by itself. Call var.get() and you read what the user typed. You do not need to touch the widget directly.

That sharing is the same pattern as an observable value in other frameworks: whenever the value changes, anything interested is notified. You can add your own listener with var.trace_add('write', callback). This is how you build a live search box that filters as you type, or a label that shows the character count.

A plain Python variable cannot do this, because Tkinter has no way to know it changed. To see what a StringVar does behind the scenes, the block below builds a miniature one with a list of observers and uses it to mirror an entry box into a character counter, with no window needed.

stringvar_trace.pyrun on your computer
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("Live counter")

text = tk.StringVar()
count = tk.StringVar(value="0 characters")

def update(*args):
    count.set(f"{len(text.get())} characters")

text.trace_add("write", update)

ttk.Entry(root, textvariable=text, width=30).pack(padx=12, pady=(12, 4))
ttk.Label(root, textvariable=count).pack(pady=(0, 12))

root.mainloop()

Line by line

  1. 4-5Create the window.
  2. 7-8Two string variables: one for the entry, one for the label that reports the length.
  3. 10-11A callback. Tkinter passes three internal arguments to trace callbacks, so I accept and ignore them with *args.
  4. 13trace_add('write', ...) runs the callback every time the text variable changes, in other words on every keystroke.
  5. 15-16The entry writes into text, the label reads from count. We never touch the widgets again.
  6. 18Run the loop.
Model: a StringVar with observers
class Var:
    """A miniature StringVar: a value plus observers."""
    def __init__(self, value=""):
        self._value = value
        self._observers = []

    def get(self):
        return self._value

    def set(self, value):
        if value != self._value:
            self._value = value
            for callback in list(self._observers):
                callback(self)

    def trace(self, callback):
        self._observers.append(callback)

text = Var()
count = Var("0 characters")
history = []

def update(var):
    count.set(f"{len(var.get())} characters")

text.trace(update)
count.trace(lambda v: history.append(v.get()))

for typed in ["h", "he", "hel", "hel", "hello", "hell"]:
    text.set(typed)      # as if the user typed or deleted

print("final text:", text.get())
print("label shows:", count.get())
print("label updates:", history)
Expected output
final text: hell
label shows: 4 characters
label updates: ['1 characters', '2 characters', '3 characters', '5 characters', '4 characters']

Line by line

  1. 1-5A variable object stores its value and a list of observers (callbacks).
  2. 7-8get returns the stored value.
  3. 10-15set only notifies when the value really changes, then calls each observer with the variable.
  4. 17-18trace adds an observer, our version of trace_add.
  5. 20-26Two variables, a list that records what the label showed, and the update rule that copies the length across.
  6. 28-29Chain another observer on count that records each label text.
  7. 31-32Simulate six edits. The repeated hel does not change the value, so no notification fires.
  8. 34-36Print the results: the variable always ends consistent with the last edit.
๐Ÿ’ก

Keep a reference to your variable (assign it to a name). If the only reference to a StringVar disappears, it may be garbage collected and the widget will go blank.

Entry and Listbox: reading input and showing lists

The Entry widget is a single-line text box. entry.get() returns what is typed, entry.delete(0, tk.END) clears it and entry.insert(0, 'text') puts text in. The Listbox shows a list of strings. listbox.insert(tk.END, item) appends one, listbox.delete(index) removes one, and listbox.curselection() returns a tuple of the selected indexes, which is empty when nothing is selected. Always check that tuple before you use it, or you will get an IndexError the first time someone presses Delete with nothing chosen.

A Listbox only stores text. It has no idea what a task or a contact is, so the real data should live in your own list of Python objects and the Listbox is only a view of it. When the data changes you redraw the view: clear the Listbox and insert every item again. This is slightly wasteful, but it keeps the two from drifting out of step, which is the commonest bug in beginner GUIs.

Also notice the pattern for validating input before you act on it: read, strip, check that it is not empty, and only then add. The example is a small name-list manager. Run it locally and notice how the Delete key, the Add button and the Return key all lead to the same two functions. Reusing small functions is much easier to debug than three copies of the same code.

name_list.pyrun on your computer
import tkinter as tk
from tkinter import ttk, messagebox

names = []

def refresh():
    listbox.delete(0, tk.END)
    for name in names:
        listbox.insert(tk.END, name)

def add(event=None):
    name = entry.get().strip()
    if not name:
        messagebox.showinfo("Empty", "Type a name first.")
        return
    names.append(name)
    entry.delete(0, tk.END)
    refresh()

def remove(event=None):
    selection = listbox.curselection()
    if not selection:
        return
    del names[selection[0]]
    refresh()

root = tk.Tk()
root.title("Name list")
entry = ttk.Entry(root, width=26)
entry.grid(row=0, column=0, padx=8, pady=8)
ttk.Button(root, text="Add", command=add).grid(row=0, column=1, padx=(0, 8))
listbox = tk.Listbox(root, height=8)
listbox.grid(row=1, column=0, columnspan=2, sticky="nsew", padx=8)
ttk.Button(root, text="Delete selected", command=remove).grid(row=2, column=0, columnspan=2, pady=8)

entry.bind("<Return>", add)
listbox.bind("<Delete>", remove)
entry.focus()
root.mainloop()

Line by line

  1. 1-4Imports, including messagebox for pop-up dialogs, and our real data list.
  2. 6-9refresh redraws the Listbox from the data: clear everything, then insert each name.
  3. 11-18add reads the entry, strips spaces, shows a message if empty, otherwise stores the name, clears the entry and redraws.
  4. 20-25remove guards against an empty selection, then deletes the matching item from the list and redraws.
  5. 27-36Build the layout with grid: an entry and Add button on row 0, the Listbox on row 1 spanning two columns, the Delete button on row 2.
  6. 38-41Bind Return in the entry to add and Delete in the list to remove, put the cursor in the entry, and start the loop.
โ„น๏ธ

messagebox and filedialog are also part of the standard library. They give you ready-made dialogs for warnings, yes/no questions and choosing files.

Separate the model from the view: a testable TodoModel

Before we build the to-do app, I want to show you the habit that separates tidy GUI code from tangled GUI code. Put the data and rules in one class that knows nothing about Tkinter, and put the widgets in another. The first is called the model and the second the view. The model can be tested in a few lines, in a browser or in a test suite, because it needs no window.

To keep the view up to date without the model knowing about it, we use the observer pattern. The model keeps a list of callbacks. Whenever a task is added, removed or toggled, it calls each one. The view registers a callback that redraws the Listbox. If you later add a second view, such as a counter in the title bar, you register one more callback and change nothing else.

The model below is exactly the one used in the finished app in the next section, and you can press Run to see it work. It also includes a summary method and JSON export, which the app uses for saving. Notice that every rule, such as ignoring blank titles and trimming spaces, is in one place.

TodoModel with observers
import json
from dataclasses import dataclass, asdict

@dataclass
class Task:
    title: str
    done: bool = False

class TodoModel:
    def __init__(self):
        self.tasks = []
        self._observers = []

    def subscribe(self, callback):
        self._observers.append(callback)

    def _notify(self):
        for callback in self._observers:
            callback(self)

    def add(self, title):
        title = title.strip()
        if not title:
            return False
        self.tasks.append(Task(title))
        self._notify()
        return True

    def remove(self, index):
        if 0 <= index < len(self.tasks):
            del self.tasks[index]
            self._notify()
            return True
        return False

    def toggle(self, index):
        if 0 <= index < len(self.tasks):
            self.tasks[index].done = not self.tasks[index].done
            self._notify()
            return True
        return False

    def summary(self):
        done = sum(t.done for t in self.tasks)
        return f"{done} of {len(self.tasks)} done"

    def to_json(self):
        return json.dumps([asdict(t) for t in self.tasks], indent=2)

    def load_json(self, text):
        self.tasks = [Task(**item) for item in json.loads(text)]
        self._notify()

model = TodoModel()
seen = []
model.subscribe(lambda m: seen.append(m.summary()))

print(model.add("  Buy rice  "))
print(model.add("   "))
model.add("Write lesson")
model.add("Call the bank")
model.toggle(1)
print(model.toggle(9))
model.remove(0)

for i, t in enumerate(model.tasks):
    print(i, "[x]" if t.done else "[ ]", t.title)
print("observer saw:", seen)

saved = model.to_json()
copy = TodoModel()
copy.load_json(saved)
print("round trip equal:", copy.tasks == model.tasks)
print(saved)
Expected output
True
False
False
0 [x] Write lesson
1 [ ] Call the bank
observer saw: ['0 of 1 done', '0 of 2 done', '0 of 3 done', '1 of 3 done', '1 of 2 done']
round trip equal: True
[
  {
    "title": "Write lesson",
    "done": true
  },
  {
    "title": "Call the bank",
    "done": false
  }
]

Line by line

  1. 1-6A Task is a tiny dataclass holding a title and a done flag, which makes it easy to convert to and from JSON.
  2. 8-15The model keeps the task list and a list of observers. subscribe adds a callback.
  3. 17-19_notify calls every observer with the model. The model never imports Tkinter.
  4. 21-34add trims spaces and refuses blank titles. remove and toggle check the index is valid. Each change that really happens triggers a notification and returns True.
  5. 36-52A summary string, plus JSON export and import with asdict, ready for saving to disk.
  6. 54-56Create a model and subscribe an observer that records the summary after each change.
  7. 58-66Exercise it: a padded title is stored, a blank one is refused, an out-of-range toggle returns False, and one task is removed.
  8. 68-72Print the remaining tasks and every summary the observer saw.
  9. 74-78Save to JSON, load into a fresh model and check the two are equal. Then print the JSON text.
๐Ÿ’ก

Because the model is plain Python, the same class works unchanged under a command-line interface or a web page. That is the real payoff of separating it from the window.

A complete to-do app

Now we join everything. The app has an entry to type a task, an Add button, a Listbox that shows tasks with a check mark for completed ones, buttons to toggle and delete, a status label showing how many are done, and automatic saving to a JSON file in the current folder. It uses the same TodoModel as before, so I only show the pieces that change: the view class and the start-up code.

The important line is the subscription in __init__: self.model.subscribe(self.refresh). After that, the view never changes the Listbox directly when the user acts. It tells the model (self.model.add(...)), the model notifies, and refresh redraws. This one-way flow makes bugs easy to find, because there is exactly one place that draws the list. One more thing: saving also runs from an observer, so every change is stored, and closing the window by accident loses nothing.

Run it with python todo_app.py. Try pressing Return in the entry, double-clicking a task to toggle it and selecting a task and pressing the Delete button. To extend it, you could add an Edit button, a filter for unfinished tasks, due dates or a dark theme with ttk.Style. Each of those is a small change in the view with the rules kept in the model, which is exactly why we separated them.

todo_app.pyrun on your computer
import json
import tkinter as tk
from dataclasses import dataclass, asdict
from pathlib import Path
from tkinter import ttk, messagebox

SAVE_FILE = Path("todo_tasks.json")


@dataclass
class Task:
    title: str
    done: bool = False


class TodoModel:
    def __init__(self):
        self.tasks = []
        self._observers = []

    def subscribe(self, callback):
        self._observers.append(callback)

    def _notify(self):
        for callback in self._observers:
            callback(self)

    def add(self, title):
        title = title.strip()
        if not title:
            return False
        self.tasks.append(Task(title))
        self._notify()
        return True

    def remove(self, index):
        if 0 <= index < len(self.tasks):
            del self.tasks[index]
            self._notify()

    def toggle(self, index):
        if 0 <= index < len(self.tasks):
            self.tasks[index].done = not self.tasks[index].done
            self._notify()

    def summary(self):
        done = sum(t.done for t in self.tasks)
        return f"{done} of {len(self.tasks)} done"

    def save(self, path):
        data = [asdict(t) for t in self.tasks]
        path.write_text(json.dumps(data, indent=2), encoding="utf-8")

    def load(self, path):
        if path.exists():
            items = json.loads(path.read_text(encoding="utf-8"))
            self.tasks = [Task(**item) for item in items]


class TodoApp:
    def __init__(self, root, model):
        self.root = root
        self.model = model
        root.title("To-do list")
        root.geometry("360x420")
        root.minsize(300, 320)

        self.new_title = tk.StringVar()
        self.status = tk.StringVar()

        top = ttk.Frame(root, padding=10)
        top.pack(fill="x")
        self.entry = ttk.Entry(top, textvariable=self.new_title)
        self.entry.pack(side="left", fill="x", expand=True)
        ttk.Button(top, text="Add", command=self.add).pack(side="left", padx=(6, 0))

        middle = ttk.Frame(root, padding=(10, 0))
        middle.pack(fill="both", expand=True)
        self.listbox = tk.Listbox(middle, activestyle="none")
        scroll = ttk.Scrollbar(middle, command=self.listbox.yview)
        self.listbox.config(yscrollcommand=scroll.set)
        self.listbox.pack(side="left", fill="both", expand=True)
        scroll.pack(side="right", fill="y")

        bottom = ttk.Frame(root, padding=10)
        bottom.pack(fill="x")
        ttk.Button(bottom, text="Toggle done", command=self.toggle).pack(side="left")
        ttk.Button(bottom, text="Delete", command=self.delete).pack(side="left", padx=6)
        ttk.Label(bottom, textvariable=self.status).pack(side="right")

        self.entry.bind("<Return>", self.add)
        self.listbox.bind("<Double-Button-1>", self.toggle)
        self.model.subscribe(self.refresh)
        self.model.subscribe(lambda m: m.save(SAVE_FILE))
        self.refresh(self.model)
        self.entry.focus()

    def selected(self):
        picked = self.listbox.curselection()
        return picked[0] if picked else None

    def add(self, event=None):
        if self.model.add(self.new_title.get()):
            self.new_title.set("")
        else:
            messagebox.showinfo("Nothing to add", "Please type a task first.")

    def toggle(self, event=None):
        index = self.selected()
        if index is not None:
            self.model.toggle(index)

    def delete(self):
        index = self.selected()
        if index is not None:
            self.model.remove(index)

    def refresh(self, model):
        self.listbox.delete(0, tk.END)
        for task in model.tasks:
            mark = "[x]" if task.done else "[ ]"
            self.listbox.insert(tk.END, f"{mark} {task.title}")
        self.status.set(model.summary())


def main():
    root = tk.Tk()
    model = TodoModel()
    model.load(SAVE_FILE)
    TodoApp(root, model)
    root.mainloop()


if __name__ == "__main__":
    main()

Line by line

  1. 1-7Imports, plus the name of the JSON file used for saving.
  2. 10-14The Task dataclass, same as before.
  3. 17-61The TodoModel: add, remove, toggle and summary rules, observers, and save and load for JSON on disk. No Tkinter code inside.
  4. 64-70The view class receives the window and a model, sets the title, size and a minimum size.
  5. 72-73Two StringVars: one for the new task text and one for the status line.
  6. 75-80Top row: an entry that stretches and an Add button, packed side by side inside a frame.
  7. 82-88Middle: a Listbox with a scrollbar wired both ways (yview and yscrollcommand).
  8. 90-94Bottom row: toggle and delete buttons on the left, the status label on the right.
  9. 96-102Bind Return and double-click, then subscribe two observers: one redraws the list and one saves to disk. Draw once at the start and focus the entry.
  10. 104-106Helper that returns the selected index or None.
  11. 108-112Add clears the entry on success, or explains the problem with a dialog.
  12. 114-123Toggle and delete act only if something is selected.
  13. 125-130refresh is the only place the Listbox is drawn. It also updates the status text.
  14. 133-138Start-up: create the window and model, load saved tasks, build the app, and start the loop.
  15. 141-142The usual guard so the file can also be imported without opening a window.
โš ๏ธ

The Tkinter code here was syntax-checked but not run in this web page. Try it on your computer and, if something differs on your system, check your Python version and that Tk is installed (some Linux distributions package it separately as python3-tk).

Simulating the whole app without a window

A good test of the separation is to drive the application logic without any window at all. Below I write a tiny fake view with the same job as TodoApp: it receives a notification and redraws a list of strings. I then feed it a script of user actions (typing, clicking Add, selecting an item, toggling it) and check the result. This is also how real projects test GUI behaviour: they do not click pixels, they call the same methods the widgets would call.

The script also shows a classic bug. After adding or deleting, the selection in a real Listbox is cleared by the redraw, so a user action that depends on the earlier selection will not work. The fake view tracks the selection as a number and resets it on every refresh to model this, and the final assertion proves our logic copes. Pay attention to how few lines it takes.

If you outgrow Tkinter, the same pattern carries to larger toolkits such as PyQt, Kivy and web front ends. The widgets change but the shape stays: a model with rules, a view that redraws on notification and handlers that translate input into model calls.

Driving the app logic with a fake view
from dataclasses import dataclass

@dataclass
class Task:
    title: str
    done: bool = False

class Model:
    def __init__(self):
        self.tasks, self.observers = [], []
    def subscribe(self, cb):
        self.observers.append(cb)
    def changed(self):
        for cb in self.observers:
            cb(self)
    def add(self, title):
        if title.strip():
            self.tasks.append(Task(title.strip()))
            self.changed()
            return True
        return False
    def toggle(self, i):
        self.tasks[i].done = not self.tasks[i].done
        self.changed()
    def remove(self, i):
        del self.tasks[i]
        self.changed()

class FakeView:
    """Same job as TodoApp: redraw on notification, handle 'clicks'."""
    def __init__(self, model):
        self.model = model
        self.lines = []
        self.selected = None
        self.typed = ""
        self.redraws = 0
        model.subscribe(self.refresh)

    def refresh(self, model):
        self.redraws += 1
        self.selected = None          # a real Listbox loses its selection too
        self.lines = [("[x] " if t.done else "[ ] ") + t.title for t in model.tasks]

    def type(self, text):
        self.typed = text
    def click_add(self):
        if self.model.add(self.typed):
            self.typed = ""
    def select(self, i):
        self.selected = i
    def click_toggle(self):
        if self.selected is not None:
            self.model.toggle(self.selected)
    def click_delete(self):
        if self.selected is not None:
            self.model.remove(self.selected)

model = Model()
view = FakeView(model)

view.type("Water the plants"); view.click_add()
view.type("   ");              view.click_add()      # refused, no redraw
view.type("Pay the bill");     view.click_add()
view.type("Plan lesson");      view.click_add()

view.select(1); view.click_toggle()
view.click_toggle()                                  # selection was cleared: no effect
view.select(0); view.click_delete()

print("\n".join(view.lines))
print("redraws:", view.redraws)
assert view.lines == ["[x] Pay the bill", "[ ] Plan lesson"]
print("assertion passed")
Expected output
[x] Pay the bill
[ ] Plan lesson
redraws: 5
assertion passed

Line by line

  1. 1-5A task dataclass again.
  2. 7-25A compact model with the same rules as TodoModel: observers, add (rejecting blanks), toggle, remove.
  3. 27-37A fake view. It stores the lines a Listbox would show, the selected index, the typed text and a redraw counter, and subscribes to the model.
  4. 39-42refresh rebuilds the lines from the model and clears the selection, copying what a real redraw does.
  5. 44-58Methods that mirror the user's actions: type, click Add, select a row, toggle and delete.
  6. 60-61Create the model and view.
  7. 63-71Act as a user: add two tasks, try a blank one, add another, toggle the second, try toggling again with the selection lost, and delete the first.
  8. 73-77Print the visible lines and the redraw count, then assert the exact final state.
๐Ÿ’ก

If a test like this passes but the real window misbehaves, the problem is in the view's wiring, so you have narrowed the search to a small part of the code.

Common mistakes

โŒ Calling the function in command=

Writing command=on_click() runs the function once while building the window and gives Tkinter None. Pass the function itself, command=on_click, and use lambda: on_click(5) or functools.partial when you need arguments.

โŒ Mixing pack and grid in one container

Both managers try to arrange the same parent and can make the program hang without an error. Choose one manager per container and use nested Frame widgets when you need a mix.

โŒ Doing slow work inside a callback

While your callback runs, the event loop cannot repaint, so the window freezes. Keep callbacks short. For long jobs break the work into small pieces with root.after(ms, step), or run it in a worker thread and hand the result back safely.

โŒ Forgetting to keep references or check selections

A StringVar or image that is garbage collected makes a widget blank, and curselection() returns an empty tuple when nothing is selected. Store variables on self and always test the selection before using [0].

โŒ Putting business rules in the widgets

If validation, saving and counting live inside button handlers, you cannot test them and every new feature touches everything. Keep rules in a plain model class and let the view just display and forward user actions.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. What does root.mainloop() do?

Q2. Which is the correct way to attach a function to a button?

Q3. Which statement about geometry managers is true?

Q4. What does listbox.curselection() return when nothing is selected?

Q5. Why separate a model class from the Tkinter view?

Q6. A handler registered with widget.bind('<Key>', handler) receives what?

Frequently asked questions

Yes for small tools, learning and quick utilities. It is included with Python and easy to start. For a very polished or mobile-style interface, other toolkits exist, but the event-driven ideas you learn here transfer directly.

Usually a callback is doing slow work, or an infinite loop runs before mainloop(). Keep handlers quick, split long jobs with root.after, and never call time.sleep in a callback.

Prefer ttk widgets where they exist because they follow the system theme. Some classic widgets, such as Listbox, Canvas and Text, have no ttk equivalent and are still fine to use.

Package it with a tool such as PyInstaller, which bundles Python and your code into an executable. Check its current documentation for options, as they change between versions.

Tkinter needs the operating system's windowing system, which a browser page does not have. That is why the Run buttons on this page use plain-Python models of the logic, and the window code is for your own computer.

Key takeaways

  • โœ“A Tkinter program builds widgets, places them with a geometry manager and calls mainloop() to wait for events.
  • โœ“Use pack for simple stacks and grid for forms, one manager per container, with frames for nesting.
  • โœ“Callbacks are functions Tkinter calls for you: command=func for buttons and bind() for keys and mouse, which pass an event object.
  • โœ“StringVar and friends share state between widgets and code, and trace_add reacts to changes.
  • โœ“Keep real data in your own objects and treat Entry and Listbox as views that you redraw.
  • โœ“A model with observers plus a thin view gives you an app that is easy to extend, save and test.