Introduction
Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into the Python standard library. Tkinter has several strengths. It’s cross-platform, so the same code works on Windows, macOS, and Linux. Visual elements are rendered using native operating system elements, so applications built with Tkinter look like they belong on the platform where they’re run.
Although Tkinter is considered the de facto Python GUI framework, it’s not without criticism. One notable criticism is that GUIs built with Tkinter look outdated. If you want a shiny, modern interface, then Tkinter may not be what you’re looking for.
However, Tkinter is lightweight and relatively painless to use compared to other frameworks. This makes it a compelling choice for building GUI applications in Python, especially for applications where a modern sheen is unnecessary, and the top priority is to quickly build something that’s functional and cross-platform.
First Application
Let's create our first python GUI application. We are going to:
- import tkinter;
- open a window;
- create a label widget;
- add it to our window using the
pack()
method; - add the
mainloop()
method.
import tkinter as tk
window = tk.Tk()
label = tk.Label(text="Hello World")
label.pack()
window.mainloop()
Info
window.mainloop()
tells Python to run the Tkinter event loop. This method listens for events, such as button clicks or keypresses, and blocks any code that comes after it from running until you close the window where you called the method.- When you pack a widget into a window, Tkinter sizes the window as smaal as it can be while still fully encompassing the widget.