Building Desktop Apps with tkinter
Turn your Python skills into windows, buttons and interactive tools
tkinter is Python's built-in toolkit for graphical user interfaces (GUIs). You describe a window and the widgets inside it, attach ordinary Python functions as event callbacks, and hand control to an event loop that waits for clicks and keystrokes. No installation, no framework to learn first: tkinter ships with Python.
- create a main window with
tkinter.Tk()and start it withmainloop(), - place
Label,ButtonandEntrywidgets on it, - wire a button to a Python function using
command=, - read and display text with
Entry.get()andStringVar, - arrange widgets with the
packandgridlayout managers, - assemble a small interactive app such as a unit converter or a click counter.
1. The root window and the event loop
A tkinter program always starts with one root window, created by calling tkinter.Tk(). This object is the top-level window and the parent of every widget you add. At the very end you call its mainloop() method, which hands control to tkinter's event loop: an endless cycle that waits for the operating system to report events (a click, a key, a resize), dispatches each one to the right callback, redraws the screen, and repeats until the window is closed.
import tkinter as tk
root = tk.Tk() # create the main window
root.title("My First App") # text in the title bar
root.geometry("300x120") # width x height in pixels
label = tk.Label(root, text="Hello, desktop!")
label.pack(padx=20, pady=20) # put it on the window
root.mainloop() # start the event loop (blocks here)
Notice that mainloop() is the last line. It blocks: the program pauses there and only continues past it once the user closes the window. Everything interactive must therefore be set up before that call and driven by callbacks during it.