Python tkinter Introduction
In this page:
What is Tkinter?
Tkinter is Python's standard-library GUI toolkit, bundled with the interpreter itself rather than needing separate installation. Like turtle graphics, it requires a real graphical display to run, though browser-based environments such as Pyodide can render Tkinter windows directly in the page.
Example: What is Tkinter?
import tkinter
print(tkinter.TkVersion)
Creating a Window
Every Tkinter application starts by creating a root window instance via Tk(), which represents the main application window that all other widgets get placed inside.
Example: Creating a Window
import tkinter
root = tkinter.Tk()
print(type(root))
The Event Loop
A newly created Tkinter window closes immediately unless you call mainloop(), which starts the event loop that keeps the window open, redraws it, and listens continuously for user interactions like clicks and keypresses until the window is closed.
Example: The Event Loop
import tkinter
root = tkinter.Tk()
root.after(100, root.destroy) # auto-close so this demo doesn't hang
root.mainloop()
print("Event loop ended")
Adding Window Titles
title('My App') sets the text shown in the window's title bar, giving users a clear label identifying the application -- a small detail, but one that's easy to forget and leaves a window awkwardly unlabeled.
Example: Adding Window Titles
import tkinter
root = tkinter.Tk()
root.title("My App")
print(root.title())
Setting Window Dimensions
geometry(widthxheight) sets the window's initial pixel dimensions using a specific string format (like 400x300), letting you control how large the application window appears when it first opens rather than relying on a default size.
Example: Setting Window Dimensions
import tkinter
root = tkinter.Tk()
root.geometry("400x300")
print(root.geometry())
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects