Lesson 26 of 30
GUI Programming with Tkinter
Building desktop windows, labels, buttons, entry fields, and event loops.
Introduction to Tkinter
Tkinter is Python's built-in GUI library. It is included with Python — no pip install needed.
Your First Window
import tkinter as tk
root = tk.Tk()
root.title("My First GUI")
root.geometry("400x200")
label = tk.Label(root, text="Hello, Tkinter!", font=("Arial", 16))
label.pack(pady=20)
btn = tk.Button(root, text="Click Me",
command=lambda: label.config(text="Button clicked!"))
btn.pack()
root.mainloop()
Entry Widget and Event Handler
def greet():
name = entry.get()
result_label.config(text=f"Hello, {name}!")
root = tk.Tk()
root.title("Greeter")
tk.Label(root, text="Your name:").pack(pady=5)
entry = tk.Entry(root, width=25)
entry.pack(pady=5)
tk.Button(root, text="Greet", command=greet).pack(pady=5)
result_label = tk.Label(root, text="", font=("Arial", 14))
result_label.pack(pady=10)
root.mainloop()
Layout Managers
.pack()— simple top-down stacking..grid(row, column)— table-based positioning..place(x, y)— absolute pixel coordinates.