Beginning GUI Programming in Python with `tkinter`
GUI programming is exciting and fun!
The tkinter
module that comes with the Python standard library is a GUI toolkit that we can use to create Graphical User Interfaces in our programs, portable across different operating systems.
There are 3rd party libraries that let you create GUI interfaces, but tkinter
is the one integrated with Python, so it’s the one we’re going to explain.
Let’s start the fun with a simple application that prints a label
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hello, World!", padx=10, pady=10)
label.pack()
root.mainloop()
Run the program from the terminal.
You will quickly see a window show up. This is how it looks like on macOS:
You will see it differently depending on your operating system.
You can resize the window, hide it, make it full screen too.
While the window is open, the Python process you started from the terminal is still active. Press the red (x) button to close the window, and you will see that the terminal program exists.
Contrary to most CLI (command line interface) applications, GUI applications are always waiting for user events, like mouse or keyboard events, and they only exit when closed explicitly.
Now that you saw the magic happen, let’s talk about the program. It’s just 5 lines of code, yet it opens up the GUI world to us.
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hello, World!", padx=10, pady=10)
label.pack()
root.mainloop()
We import the tkinter
module, and we rename it as tk
for convenience.
Then we initialize a top level window with tk.Tk()
.
We initialize a label with the tk.Label()
widget constructor, adding the root
top level widget as the first parameter and adding some other information like the text to show, and some padding.
Then we pack the label (we add it to its parent widget) and then we call root.mainloop()
to start the tkinter event loop, which will manage the application lifecycle.
If you prefer you can also individually import each item from tkinter
, so you don’t have to use a prefix every time:
from tkinter import Tk, Label
root = Tk()
label = Label(root, text="Hello, World!", padx=10, pady=10)
label.pack()
root.mainloop()
I mentioned widgets. Label is one widget, but we have a lot of them. Others we will use a lot are Text
, Entry
, Button
, StringVar
, Canvas
, Frame
, PhotoImage
, Scrollbar
, Menu
, and more!
Let’s build a simple program. The application starts and generates a random number. We’ll put an input box box where the user can enter a number, press a button, and we check if it’s the winning number!
We will use the Label
, Entry
and Button
widgets to create this UI:
When the Guess!
button is pressed we call a guess()
function that gets the value of the entry box, and checks if it’s equal to the random number we generated with random.randint()
.
If the number is correct we show a message with messagebox
, then we quit the app:
Here’s the full program:
from tkinter import Tk, Label, Entry, Button, messagebox
import random
n = random.randint(1,10)
print(n)
root = Tk()
label = Label(root, text="Guess a number between 1 and 10!", padx=10, pady=10)
label.pack()
ent = Entry(root)
ent.pack()
def guess():
try:
num = int(ent.get())
except ValueError:
print('Invalid value. Please enter a number')
else:
if num == n:
print('WON!')
messagebox.showinfo(title='You won!', message='You guessed the number!')
root.destroy()
else:
print('Wrong number ' + str(num))
messagebox.showerror(title='Wrong!', message='Try again!')
widget = Button(root, text='Guess!', command=guess)
widget.pack()
root.mainloop()
Those are just the basics of tkinter
. There’s a lot more to know about it, but I hope this got you started with GUI programming.
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025