/

Getting Started with GUI Programming in Python using `tkinter`

Getting Started with GUI Programming in Python using tkinter

GUI programming is a thrilling and enjoyable experience! In this blog post, we will explore the tkinter module, which is a GUI toolkit that comes bundled with Python. This makes it easy for us to create Graphical User Interfaces that are portable across different operating systems.

While there are other third-party libraries available for GUI programming, tkinter stands out as the integrated solution for Python. So, let’s dive right in and discover the power of tkinter!

To begin, let’s start with a simple application that prints a label:

1
2
3
4
5
6
import tkinter as tk

root = tk.Tk()
label = tk.Label(root, text="Hello, World!", padx=10, pady=10)
label.pack()
root.mainloop()

To run this program, execute it from the terminal. You will notice a window appearing, which might look slightly different depending on your operating system. You can resize the window, hide it, or even make it full screen. It’s important to note that unlike command line applications, GUI applications wait for user events, such as mouse or keyboard interactions. These applications only exit when explicitly closed.

Now, let’s take a closer look at the code. Despite being just five lines long, it paves the way to the world of GUI programming:

1
2
3
4
5
6
import tkinter as tk

root = tk.Tk()
label = tk.Label(root, text="Hello, World!", padx=10, pady=10)
label.pack()
root.mainloop()

In the code snippet above, we import the tkinter module and conveniently rename it as tk for brevity. Next, we initialize the top-level window using tk.Tk(). We then create a label using the tk.Label() widget constructor, passing the root top-level widget as the first parameter. Additionally, we customize the label with the desired text and padding. After packing the label (adding it to its parent widget), we call root.mainloop() to start the tkinter event loop, which manages the application’s lifecycle.

Alternatively, you have the option to individually import specific items from tkinter, eliminating the need for a prefix:

1
2
3
4
5
6
from tkinter import Tk, Label

root = Tk()
label = Label(root, text="Hello, World!", padx=10, pady=10)
label.pack()
root.mainloop()

In addition to labels, tkinter offers a wide range of widgets including Text, Entry, Button, StringVar, Canvas, Frame, PhotoImage, Scrollbar, Menu, and more! These widgets enable us to build more complex and interactive user interfaces.

Now, let’s create a simple program that generates a random number and allows the user to input their guess. We will utilize the Label, Entry, and Button widgets to create the following user interface:

When the user clicks the Guess! button, the program calls a guess() function that retrieves the value from the entry box. It then checks if the entered value matches the randomly generated number using random.randint(). If the numbers match, a message is displayed using messagebox, and the application is terminated. Otherwise, an error message is shown, and the user can try again.

Here’s the complete program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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()

These are just the basic concepts of tkinter. There’s much more to explore and learn, but I hope this article serves as a solid starting point for your GUI programming journey.

tags: [“tkinter”, “GUI programming”, “Python”, “labels”, “widgets”, “event loop”]