Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 149 ยท Beyond the Basics

Desktop GUIs with tkinter

Build desktop apps with tkinter. Create windows and widgets, lay them out with pack and grid, handle events, use variables and timers, and build a to-do app.

So far your programs have talked to people through the terminal: print() and input(), or command-line arguments. Many users, though, expect a window with buttons, text boxes and menus. Programs like that have a graphical user interface (GUI), and Python ships with a toolkit for building them: tkinter, the standard library's interface to the Tk GUI toolkit.

tkinter is not the flashiest toolkit, but it's always there (no installation on Windows and macOS), it's stable, and it's perfect for small tools: a file renamer for your team, a settings editor, a quiz app, a front end for a script. In this lesson you'll learn how GUI programs work (they're built around an event loop), create widgets, arrange them with layout managers, react to clicks and key presses, link widgets to variables, schedule timers, and put it all together in a small to-do app.

What runs here and what doesn't. tkinter needs a real screen, so it can't run in the in-browser editors on this page. The tkinter code is shown read-only: copy it into a .py file and run it on your computer. The live examples practice the ideas behind GUI programming (event loops, callbacks, observable variables and keeping logic separate from the UI) in plain Python.

Your first window

Here's a complete tkinter program. Save it as hello_gui.py and run it with python hello_gui.py:

Python
import tkinter as tk
from tkinter import ttk

def say_hello() -> None:
    greeting.config(text="Hello, tkinter!")

root = tk.Tk()                       # the main window
root.title("Hello")
root.geometry("280x120")             # width x height in pixels

greeting = ttk.Label(root, text="Press the button")
greeting.pack(pady=12)

ttk.Button(root, text="Greet", command=say_hello).pack()

root.mainloop()                      # show the window and wait for events

Every tkinter program follows this shape:

  1. Create the root window with tk.Tk(). A program has exactly one.
  2. Create widgets. The first argument is the parent, the widget that contains the new one.
  3. Place each widget with a layout manager (pack() here). A widget that is never placed never appears.
  4. Call mainloop(), which shows the window and runs until it's closed.

The command=say_hello argument passes the function itself, without parentheses. tkinter calls it later, each time the button is clicked. Writing command=say_hello() would call the function once, right away, and pass its return value (None) as the command: a classic first bug.

Is tkinter installed? Run python -m tkinter in a terminal. A small test window means you're ready. On Linux you may need the system package first (sudo apt install python3-tk on Debian and Ubuntu); with Homebrew's Python on macOS, run brew install python-tk.

How GUI programs work: the event loop

A terminal program runs from top to bottom, asking for input when it decides to. A GUI program turns this around: it sets up its window and then waits. The user decides what happens next by clicking, typing or resizing. Each action produces an event, and the event loop inside mainloop() takes events from a queue one by one and calls the functions you registered for them. These functions are called callbacks or event handlers.

This model has one big consequence: while a callback runs, the event loop can't do anything else. The window can't redraw, and no other click is handled. If a callback takes five seconds, the app freezes for five seconds. This live model of an event loop shows both ideas, using a pretend clock instead of real waiting:

Python A model of an event loop

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.

Look at the timestamps after the slow save: the click that happened at 1,500 ms was only handled at 4,200 ms, and the timer that was due at 2,000 ms ran late too. That's exactly what a frozen window feels like. The rules that follow from this:

  • Keep callbacks short. Do quick work and return.
  • Never call time.sleep() in a tkinter program. To do something later, use widget.after(ms, function), which schedules a callback without blocking.
  • Run slow work (downloads, big files, heavy calculations) in a background thread, and send the result back to the GUI thread. You'll see how at the end of this lesson.

Common widgets

tkinter has two families of widgets. The classic ones live in tkinter (tk.Button); the themed ones live in tkinter.ttk (ttk.Button) and look like native controls on Windows and macOS. Prefer ttk where a themed version exists.

Widget Use Key methods and options
ttk.Label text or an image text=, config(text=...)
ttk.Button a clickable button command=
ttk.Entry one line of text input get(), insert(), delete(), textvariable=, show="*"
tk.Text multi-line text get("1.0", "end-1c"), insert(), delete("1.0", "end")
ttk.Checkbutton an on/off option variable= (a BooleanVar)
ttk.Radiobutton one choice from a group variable=, value=
ttk.Combobox drop-down list values=, get()
ttk.Scale / ttk.Spinbox pick a number from_=, to=, variable=
tk.Listbox a list to select from insert("end", item), curselection(), delete(i)
ttk.Frame an invisible container that groups widgets the parent of other widgets
ttk.Progressbar progress indicator value=, maximum=, start()

Any option can be changed later with widget.config(option=value), and read with widget.cget("option"). Ready-made dialogs live in their own modules:

Python
from tkinter import messagebox, filedialog

messagebox.showinfo("Saved", "Your notes were saved.")
if messagebox.askyesno("Quit", "Discard unsaved changes?"):
    root.destroy()

path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
if path:                                     # an empty string means "cancelled"
    print("Opening", path)

More widgets: Scrollbar, Toplevel, Menubutton and PanedWindow

A few widgets don't fit in the table because they work together with others.

  • Scrollbar is never useful alone: connect it to a scrollable widget (Text, Listbox, Canvas, ttk.Treeview) in both directions. The widget's yscrollcommand tells the bar where the view is, and the bar's command scrolls the widget.
  • Toplevel is an extra window that belongs to the same program. It closes with the main window, it can be made modal with grab_set(), and transient(root) keeps it on top of its parent.
  • Menubutton is a button that opens a drop-down Menu when pressed. For a classic menu bar across the top of the window, build a Menu and pass it to root.config(menu=bar) instead.
  • PanedWindow holds panes separated by draggable sashes, like the panels in a code editor. Add panes with add().

This sketch uses all four. It needs a display, so it can't run in the browser:

Python
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("More widgets")

# PanedWindow: the user drags the sash to resize both sides
panes = tk.PanedWindow(root, orient="horizontal", sashrelief="raised")
panes.pack(fill="both", expand=True)

left = ttk.Frame(panes)
panes.add(left, minsize=120)

# Scrollbar wired to a Listbox (two-way link)
listbox = tk.Listbox(left)
bar = ttk.Scrollbar(left, orient="vertical", command=listbox.yview)
listbox.config(yscrollcommand=bar.set)
for number in range(1, 101):
    listbox.insert("end", f"Item {number}")
listbox.pack(side="left", fill="both", expand=True)
bar.pack(side="right", fill="y")

right = ttk.Label(panes, text="Right pane", anchor="center")
panes.add(right, minsize=120)

# Menubutton with a drop-down Menu
button = tk.Menubutton(root, text="Actions", relief="raised")
menu = tk.Menu(button, tearoff=False)
menu.add_command(label="Open dialog", command=lambda: open_dialog())
menu.add_separator()
menu.add_command(label="Quit", command=root.destroy)
button.config(menu=menu)
button.pack(side="bottom", anchor="w")

# Toplevel: a second window that stays above its parent
def open_dialog() -> None:
    dialog = tk.Toplevel(root)
    dialog.title("Dialog")
    dialog.transient(root)
    ttk.Label(dialog, text="I am a second window.").pack(padx=20, pady=20)
    ttk.Button(dialog, text="Close", command=dialog.destroy).pack(pady=(0, 20))
    dialog.grab_set()                 # block the main window until closed

root.mainloop()

Layout: pack and grid

A widget appears only after you place it with a layout manager. tkinter has three:

  • pack() stacks widgets one after another, top to bottom by default, or side by side with side="left". Great for simple rows and columns.
  • grid() puts widgets in rows and columns, like a table. Best for forms and most real layouts.
  • place() sets exact positions (x=, y=). Rarely the right choice, because it doesn't adapt to window size or font size.

Here's a small form with grid():

Python
import tkinter as tk
from tkinter import ttk

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

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

ttk.Label(form, text="Name:").grid(row=0, column=0, sticky="w", pady=4)
ttk.Entry(form).grid(row=0, column=1, sticky="ew", pady=4)
ttk.Label(form, text="Email:").grid(row=1, column=0, sticky="w", pady=4)
ttk.Entry(form).grid(row=1, column=1, sticky="ew", pady=4)
ttk.Button(form, text="Create account").grid(row=2, column=0, columnspan=2, pady=(8, 0))

form.columnconfigure(1, weight=1)    # column 1 takes any extra width
root.columnconfigure(0, weight=1)    # the frame grows with the window
root.rowconfigure(0, weight=1)
root.mainloop()

sticky says which sides of its cell a widget sticks to: "w" (west) aligns left, and "ew" stretches it horizontally. columnconfigure(..., weight=1) decides which column receives extra space when the window grows; without it, nothing stretches. padx and pady add space around a widget.

Don't mix pack() and grid() in the same container. The two managers fight over the same space, and tkinter raises a TclError instead of hanging forever. It is fine to use grid() inside one frame and pack() inside another; frames are how you combine them.

Events and bindings

command= covers the main action of buttons. For everything else (keys, mouse movement, double clicks, focus, resizing), use bind(). The handler receives an event object with details such as event.keysym (the key name), event.x and event.y (the mouse position) and event.widget:

Python
def on_key(event: tk.Event) -> None:
    status.config(text=f"You pressed {event.keysym}")

entry.bind("<Return>", lambda event: add_item())     # Enter key in the entry
root.bind("<Escape>", lambda event: root.destroy())  # anywhere in the window
root.bind("<Control-s>", lambda event: save())       # keyboard shortcut
listbox.bind("<Double-Button-1>", open_item)         # double click
canvas.bind("<B1-Motion>", draw)                     # drag with the left button
root.bind("<KeyPress>", on_key)
root.protocol("WM_DELETE_WINDOW", on_close)          # the window's close button

Bound handlers always receive the event argument, even when they don't need it; that's why the examples wrap add_item() and save() in a lambda event: ....

When you create widgets in a loop (a row of buttons, a keypad, a toolbar), there's a trap waiting in those lambdas. A lambda looks up the loop variable when it runs, not when it's created, so every button ends up using the last value. This live example builds the "commands" for a calculator keypad and calls them the way tkinter would:

Python The lambda-in-a-loop trap

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.

In a real app the loop would be ttk.Button(pad, text=key, command=lambda key=key: press(key)). The default-argument trick and functools.partial (see itertools and functools) both freeze the value at the moment each button is created.

Control variables: StringVar, IntVar and friends

tkinter can link a widget to a control variable: an object that holds a value and notifies everyone who cares when it changes. There are four kinds: tk.StringVar, tk.IntVar, tk.DoubleVar and tk.BooleanVar. You read them with .get(), write them with .set(), and connect them with options like textvariable= and variable=:

Python
name = tk.StringVar(value="")
ttk.Entry(root, textvariable=name).pack()            # typing updates the variable
ttk.Label(root, textvariable=name).pack()            # the label follows automatically

def on_change(*args) -> None:                        # receives (name, index, mode)
    count.set(f"{len(name.get())} characters")

count = tk.StringVar()
ttk.Label(root, textvariable=count).pack()
name.trace_add("write", on_change)                   # run on every change

Two widgets sharing one variable always show the same value, and trace_add() lets you react to every change, for example to validate input as the user types. This is the observer pattern, and it's easy to model in plain Python:

Python A model of tkinter's StringVar

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 entry, the preview label and the validator never call each other. Each one only talks to the shared variable, which keeps the code loosely connected and easy to change.

Timers with after()

root.after(ms, callback) asks the event loop to call callback once after at least ms milliseconds; it returns an id you can pass to after_cancel(). To repeat something, the callback schedules itself again. This clock updates every second without ever blocking:

Python
import time
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("Clock")
clock = ttk.Label(root, font=("Segoe UI", 32), padding=16)
clock.pack()

def update_clock() -> None:
    clock.config(text=time.strftime("%H:%M:%S"))
    root.after(1000, update_clock)        # run again in one second

update_clock()
root.mainloop()

The same pattern drives animations, auto-save, and polling for results from background work.

Project: a to-do app

Larger GUI programs stay manageable when you keep the logic (data and rules) separate from the interface (widgets and layout). The logic then works without a window, so you can test it with ordinary unit tests, and the GUI code becomes thin glue. Here's the logic of a to-do app as a plain class, running live:

Python The to-do logic, without a window

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 GUI only connects widgets to that class. Copy TodoList and Task into a file together with this code (the dataclasses import comes along), then run it:

Python
import tkinter as tk
from tkinter import ttk, messagebox

class TodoApp:
    def __init__(self, root: tk.Tk) -> None:
        self.todos = TodoList()
        root.title("To-do")
        root.minsize(320, 300)

        frame = ttk.Frame(root, padding=10)
        frame.grid(sticky="nsew")
        root.columnconfigure(0, weight=1)
        root.rowconfigure(0, weight=1)

        self.new_title = tk.StringVar()
        entry = ttk.Entry(frame, textvariable=self.new_title)
        entry.grid(row=0, column=0, sticky="ew")
        entry.bind("<Return>", lambda event: self.add())
        entry.focus()
        ttk.Button(frame, text="Add", command=self.add).grid(row=0, column=1, padx=(6, 0))

        self.listbox = tk.Listbox(frame, height=10, activestyle="none")
        self.listbox.grid(row=1, column=0, columnspan=2, sticky="nsew", pady=8)
        self.listbox.bind("<Double-Button-1>", lambda event: self.toggle())

        self.status = tk.StringVar()
        ttk.Label(frame, textvariable=self.status).grid(row=2, column=0, sticky="w")
        ttk.Button(frame, text="Clear done", command=self.clear_done).grid(row=2, column=1)

        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(1, weight=1)
        self.refresh()

    def add(self) -> None:
        try:
            self.todos.add(self.new_title.get())
        except ValueError as error:
            messagebox.showwarning("Can't add task", str(error))
            return
        self.new_title.set("")
        self.refresh()

    def toggle(self) -> None:
        selection = self.listbox.curselection()       # a tuple of selected indexes
        if selection:
            self.todos.toggle(selection[0])
            self.refresh()

    def clear_done(self) -> None:
        self.todos.remove_done()
        self.refresh()

    def refresh(self) -> None:
        self.listbox.delete(0, "end")
        for label in self.todos.labels():
            self.listbox.insert("end", label)
        self.status.set(self.todos.summary())

if __name__ == "__main__":
    root = tk.Tk()
    TodoApp(root)
    root.mainloop()

Notice the structure: the app is a class whose methods are the callbacks; every user action changes the model and then calls refresh() to redraw the list. To keep tasks between runs, add save() and load() methods to TodoList that use JSON, and call save() from a WM_DELETE_WINDOW handler.

Slow work and threads

To keep the window responsive during slow work, run it in a thread. There's one firm rule: only the main thread may touch widgets. The usual pattern is a queue.Queue: the worker puts results in it, and the GUI checks it regularly with after():

Python
import queue
import threading

results = queue.Queue()

def download_report() -> None:                # runs in a background thread
    data = fetch_big_report()                 # slow: network, disk, number crunching
    results.put(data)                         # no widget access here

def check_results() -> None:                  # runs in the GUI thread
    try:
        data = results.get_nowait()
    except queue.Empty:
        root.after(100, check_results)        # nothing yet, look again soon
        return
    progress.stop()
    status.config(text=f"Report ready: {len(data)} rows")

def start_download() -> None:
    progress.start()
    threading.Thread(target=download_report, daemon=True).start()
    root.after(100, check_results)

Beyond tkinter

tkinter is ideal for small, practical desktop tools. For bigger or more polished apps, Python has other options:

Toolkit Good for
PySide6 / PyQt6 Large, professional desktop apps (Qt): rich widgets, designer tool
wxPython Native-looking apps on each platform
Kivy Touch interfaces and mobile apps
Textual Rich, mouse-aware apps that run in the terminal
A web framework Apps people use in a browser (see Web Development with Flask and Django)

To give a tkinter app to people who don't have Python, a packaging tool such as PyInstaller can bundle your script and the Python runtime into a single program file (pyinstaller --onefile --windowed todo.py).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is wrong with ttk.Button(root, text="Save", command=save())?

    command needs the function itself, command=save. Adding parentheses calls it while the button is being created.
  2. 2. A button's callback downloads a file for 10 seconds. What does the user see?

    Callbacks run inside the single event loop. While one runs, no events are handled and the window can't redraw. Use a thread (and a queue plus after()) for slow work.
  3. 3. Buttons are created with for n in range(3): ttk.Button(root, text=str(n), command=lambda: print(n)). What does clicking button 0 print?

    The lambda reads n when it runs, after the loop finished with n == 2. Use lambda n=n: print(n) or functools.partial(print, n).
  4. 4. How should a tkinter app run a function every 5 seconds?

    after() schedules a callback without blocking the event loop. Rescheduling at the end of the callback makes it repeat.
  5. 5. Which layout manager suits a form with labels in one column and entries in the next?

    grid() arranges widgets in rows and columns. Mixing pack() and grid() in one container raises an error, and place() doesn't adapt to sizes.

Summary

  • tkinter is Python's built-in GUI toolkit: create tk.Tk(), add widgets with a parent, place them, then call mainloop().
  • GUI programs are event-driven: the event loop calls your callbacks, so keep them short and never use time.sleep().
  • Prefer themed ttk widgets; use messagebox and filedialog for standard dialogs.
  • Arrange widgets with grid() (rows and columns, sticky, columnconfigure) or pack(), but never both in one container.
  • command= handles a widget's main action; bind("<Return>", handler) handles any event and passes an event object.
  • In loops, capture values with lambda key=key: ... or functools.partial.
  • StringVar, IntVar and friends link widgets to values, and trace_add() reacts to changes.
  • after(ms, callback) schedules timers; slow work goes in a thread that hands results back through a queue.
  • Keep logic in plain, testable classes and let the GUI be thin glue.

Next: Writing Pythonic Code, a tour of the idioms that make Python code clear and natural.