Python 11 – Building a GUI with Tkinter

Create windows, buttons, inputs, images, and message boxes using Python’s built-in Tkinter library.

Set up the window

Start every Tkinter app by creating a window (a Tk root), setting a title and size, then running the event loop with mainloop().

import tkinter as tk

window = tk.Tk()
window.title("My First GUI")
window.geometry("400x300")
window.configure(bg="lightblue")

window.mainloop()

Labels, entries & buttons

Use a Label to display text, an Entry for user input, and a Button to trigger actions.

import tkinter as tk

window = tk.Tk()
window.title("Greeting App")
window.geometry("360x240")
window.configure(bg="lavender")

label = tk.Label(window, text="Enter your name:", fg="midnight blue", bg="lavender", font=("Helvetica", 12))
entry = tk.Entry(window, width=22, font=("Helvetica", 12))
greeting = tk.Label(window, text="", fg="purple", bg="lavender", font=("Helvetica", 14))

def greet():
    name = entry.get().strip()
    greeting.config(text=f"Hello, {name}!" if name else "Please enter a name.")

button = tk.Button(window, text="Greet", fg="white", bg="seagreen", command=greet)

label.pack(pady=6)
entry.pack(pady=6)
button.pack(pady=6)
greeting.pack(pady=6)

window.mainloop()

Handling button clicks

Connect a function to a button via the command parameter. Inside that function, read values from widgets and update other widgets.

Images & message boxes

Use PhotoImage to load PNG/GIF files and messagebox to show alerts. Keep a reference to images (assign to a variable) so they don’t get garbage-collected.

import tkinter as tk
from tkinter import messagebox

window = tk.Tk()
window.title("Images & Messages")
window.geometry("360x360")
window.configure(bg="misty rose")

photo = tk.PhotoImage(file="example.png")   # Ensure example.png is in the same folder
img_label = tk.Label(window, image=photo, bg="misty rose")
img_label.pack(pady=10)

def show_message():
    messagebox.showinfo("Greeting", "Welcome to the GUI!")

btn = tk.Button(window, text="Show Message", command=show_message, bg="orange", fg="white")
btn.pack(pady=10)

window.mainloop()

Layout tips: pack vs grid

pack() is simple and stacks widgets. grid() places widgets in rows/columns—great for forms. Don’t mix them in the same container.

import tkinter as tk

window = tk.Tk()
window.title("Login Form")
window.configure(bg="white")
window.geometry("320x160")

tk.Label(window, text="Username:", bg="white").grid(row=0, column=0, padx=8, pady=6, sticky="e")
tk.Label(window, text="Password:", bg="white").grid(row=1, column=0, padx=8, pady=6, sticky="e")

username = tk.Entry(window, width=18)
password = tk.Entry(window, width=18, show="*")
username.grid(row=0, column=1, padx=8, pady=6)
password.grid(row=1, column=1, padx=8, pady=6)

def submit():
    print("Submitted:", username.get())

tk.Button(window, text="Submit", command=submit, bg="#4f46e5", fg="white").grid(row=2, column=0, columnspan=2, pady=10)

window.mainloop()

Practice task – Simple Calculator GUI

Build a tiny calculator that adds two numbers entered by the user and shows the result in a label. Handle invalid input gracefully.

import tkinter as tk

def calculate_sum():
    try:
        a = float(entry1.get())
        b = float(entry2.get())
        result_label.config(text=f"Sum: {a + b}")
    except ValueError:
        result_label.config(text="Please enter valid numbers.")

window = tk.Tk()
window.title("Simple Calculator")
window.geometry("300x200")
window.configure(bg="lightyellow")

tk.Label(window, text="First number:", bg="lightyellow").pack(pady=4)
entry1 = tk.Entry(window, font=("Helvetica", 12), width=12)
entry1.pack()

tk.Label(window, text="Second number:", bg="lightyellow").pack(pady=4)
entry2 = tk.Entry(window, font=("Helvetica", 12), width=12)
entry2.pack()

tk.Button(window, text="Add", command=calculate_sum, bg="skyblue").pack(pady=10)
result_label = tk.Label(window, text="", font=("Helvetica", 14), bg="lightyellow")
result_label.pack()

window.mainloop()
Tips:
  • Keep a global reference to images (e.g., photo variable) so they render correctly.
  • Use grid() for forms; use pack() for simple stacking layouts.
  • Never mix pack() and grid() in the same parent container.