On this page
  1. tkinter
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Thread-Safe Background Updates with root.after() & queue.Queue
  7. Gotchas & Boundaries
  8. Common Functions

tkinter

Prev: timeit | Up: stdlib_module | Next: token
Rel: wave, colorsys, gettext, locale, turtle
Ref: docs.python.org — tkinter
Tags: #public #python3 #stdlib


Import

import tkinter

Overview

Python's built-in cross-platform desktop GUI toolkit wrapping Tcl/Tk (Tk, ttk, Canvas, Text, StringVar, messagebox, filedialog). Reach for tkinter + tkinter.ttk for lightweight desktop utilities, prototypes, and zero-dependency desktop apps (such as custom terminals or local tools) without shipping Electron or Qt.

Quick Start

import tkinter as tk
from tkinter import ttk

def build_app() -> tk.Tk:
    root = tk.Tk()
    root.title("Counter")
    count = tk.IntVar(value=0)
    ttk.Label(root, textvariable=count, padding=12).pack()
    ttk.Button(root, text="Increment", command=lambda: count.set(count.get() + 1)).pack()
    return root

# Run on a desktop display:
# build_app().mainloop()
assert hasattr(tk, "Tk") and hasattr(ttk, "Button")

Implementation Walkthrough

1. Thread-Safe Background Updates with root.after() & queue.Queue

Never mutate Tk widgets from a worker thread—push updates into a queue.Queue and poll it on the main UI thread with root.after():

import queue
import tkinter as tk

def poll_queue(root: tk.Tk, q: queue.Queue[str], var: tk.StringVar) -> None:
    try:
        while True:
            var.set(q.get_nowait())
    except queue.Empty:
        pass
    root.after(50, poll_queue, root, q, var)

Gotchas & Boundaries

Common Functions

Linked from

Related notes