UNIT-IV
1. Introduction to GUI Programming
✅ What is GUI?
GUI (Graphical User Interface) allows users to interact with applications using graphical
elements like:
Buttons
Textboxes
Labels
Menus
Windows
✅ Real-Time Examples:
Calculator
Login Forms
Notepad
Paint Application
Web Browsers (Google Chrome, Firefox)
✅ Why GUI?
Easier for end-users (compared to command-line)
Visually appealing
Reduces the need to memorize commands
2. GUI Libraries in Python
Library Description Best For
Tkinter Built-in, simple and easy to learn Beginners, small projects
PyQt Powerful, based on Qt framework Complex, commercial-grade software
Kivy Supports multi-touch, mobile development Android/iOS cross-platform apps
wxPython Native look and feel for desktop apps Traditional desktop applications
For this course, we will use Tkinter, as it's simple and comes pre-installed with Python.
3. Getting Started with Tkinter
✅ Basic Tkinter Code Structure:
import tkinter as tk
root = [Link]() # Create main window
[Link]("My Window") # Set title
[Link]("300x200") # Set width x height
[Link]() # Display the GUI
✅ Key Functions:
Tk() - Initializes the main GUI window
title() - Sets window title
geometry("WxH") - Sets size (Width x Height)
mainloop() - Keeps the GUI running until user closes it
4. Common Tkinter Widgets (GUI Elements)
Widget Purpose
Label Display text or images
Button Create clickable buttons
Entry Single-line text input
Text Multi-line text input
Checkbutton Checkbox for multiple options
Select only one from many
Radiobutton
options
Listbox Show list of items
Scale Slider for selecting a value
Spinbox Input from fixed set of values
Container to group other
Frame
widgets
✅ Example: Using Multiple Widgets
import tkinter as tk
root = [Link]()
[Link]("Widgets Example")
[Link](root, text="Name").pack()
[Link](root).pack()
[Link](root, text="Gender").pack()
[Link](root, text="Male", value=1).pack()
[Link](root, text="Female", value=2).pack()
[Link](root, text="Submit").pack()
[Link]()
5. Layout Management in Tkinter
✅ What is Layout Management?
It controls how widgets are arranged in the window. Tkinter supports:
pack() – Auto positions vertically/horizontally
grid() – Positions widgets in a grid of rows/columns
place() – Positions widgets using x, y coordinates
🧩 Using pack() Layout
import tkinter as tk
root = [Link]()
[Link](root, text="Top").pack()
[Link](root, text="Bottom").pack(side="bottom")
[Link](root, text="Left").pack(side="left")
[Link](root, text="Right").pack(side="right")
[Link]()
✅ pack() Parameters:
side='top'/'bottom'/'left'/'right'
fill='x' or 'y' – expands widget
expand=True – takes extra space
🧩 Using grid() Layout
import tkinter as tk
root = [Link]()
[Link](root, text="Username").grid(row=0, column=0)
[Link](root).grid(row=0, column=1)
[Link](root, text="Password").grid(row=1, column=0)
[Link](root).grid(row=1, column=1)
[Link](root, text="Login").grid(row=2, column=1)
[Link]()
✅ grid() Parameters:
row, column – position in grid
rowspan, columnspan – span across rows/cols
sticky="e/w/n/s" – alignment inside grid cell
🧩 Using place() Layout
import tkinter as tk
root = [Link]()
[Link]("300x200")
[Link](root, text="Hello at (50,40)").place(x=50, y=40)
[Link]()
✅ place() Parameters:
x, y – exact coordinates
Good for precise positioning
1. Main-Window-Style Programs
✅ What is a Main-Window-Style Program?
A Main-Window-Style Program is a GUI application that contains:
A primary window (main window)
Menu bar (File, Edit, etc.)
Toolbar
Status bar
Central content area
These are typical in applications like:
Text editors (Notepad, Word)
Web browsers (Chrome, Firefox)
IDEs (VS Code, PyCharm)
2. Creating a Main Window in Tkinter
✅ Steps:
1. Import tkinter
2. Create the main window using Tk()
3. Add components: Menu, widgets, status bar, etc.
4. Call mainloop() to keep it running
✅ Example: Basic Main Window
import tkinter as tk
# Create main window
root = [Link]()
[Link]("Main Window")
[Link]("400x300")
# Add a label
label = [Link](root, text="Welcome to Main Window!", font=("Arial", 14))
[Link](pady=20)
# Run the window
[Link]()
✅ Adding Menu Bar to Main Window
import tkinter as tk
def open_file():
print("Open clicked")
root = [Link]()
[Link]("Main Window with Menu")
[Link]("400x300")
# Create a menu bar
menu_bar = [Link](root)
# Create a File menu
file_menu = [Link](menu_bar, tearoff=0)
file_menu.add_command(label="Open", command=open_file)
file_menu.add_command(label="Exit", command=[Link])
# Add File menu to the menu bar
menu_bar.add_cascade(label="File", menu=file_menu)
# Set menu to the window
[Link](menu=menu_bar)
[Link]()
3. Creating a Custom Dialog
✅ What is a Dialog?
A Dialog Box is a pop-up window used to:
Show information
Get input
Confirm actions (Yes/No)
Types:
Predefined dialogs (like messagebox, filedialog)
Custom dialogs (built by creating a new Toplevel window)
✅ Example: Custom Dialog Using Toplevel
import tkinter as tk
def open_dialog():
dialog = [Link](root)
[Link]("Custom Dialog")
[Link]("250x150")
[Link](dialog, text="This is a dialog").pack(pady=10)
[Link](dialog, text="Close", command=[Link]).pack(pady=10)
root = [Link]()
[Link]("Main Window")
[Link]("400x300")
[Link](root, text="Open Dialog", command=open_dialog).pack(pady=50)
[Link]()
✅ Summary of Key Concepts
Concept Description
Tk() Creates main application window
Toplevel() Creates a new pop-up dialog window
Menu Used to build a menu bar
Label, Button Common widgets in main or dialog windows
mainloop() Starts the GUI event loop
✅ Real-Time Use Cases
Feature Real-Time Example
Main Window Notepad main editor area
Menu Bar File, Edit menus in WordPad
Custom Dialog "Save before exit?" prompt
PACK: from tkinter import *
w = Tk()
[Link]("Pack Window")
[Link]("400x300")
l = Label(w, text="NAME", width=20, height=3, bg="green", fg="yellow")
[Link](side=TOP)
l1 = Label(w, text="AGE", width=20, height=3, bg="green", fg="yellow")
[Link](side=RIGHT)
l2 = Label(w, text="ROLLNO", width=20, height=3, bg="green", fg="yellow")
[Link](side=LEFT)
l3 = Label(w, text="FREE", width=20, height=3, bg="green", fg="yellow")
[Link](side=BOTTOM)
[Link]()
REAL TIME: from tkinter import *
# Function to be called when login button is clicked
def login1():
username = entry_user.get()
password = entry_pass.get()
if username == "admin" and password == "1234":
result_label.config(text="Login Successful!", fg="green")
else:
result_label.config(text="Login Failed. Try again.", fg="red")
# Main window
w = Tk()
[Link]("Login Form")
[Link]("300x200")
# Username label and entry
label_user = Label(w, text="Username:")
label_user.pack(pady=5)
entry_user = Entry(w)
entry_user.pack(pady=5)
# Password label and entry
label_pass = Label(w, text="Password:")
label_pass.pack(pady=5)
entry_pass = Entry(w, show="*")
entry_pass.pack(pady=5)
# Login button
btn_login = Button(w, text="Login", command=login1, bg="blue", fg="white")
btn_login.pack(pady=10)
# Result message label
result_label = Label(w, text="")
result_label.pack(pady=5)
# Run the window
[Link]()
grid: from tkinter import *
# Create main window
w = Tk()
[Link]("Grid Layout with Sticky")
[Link]("400x300")
# NAME Label - Aligned to Left (West)
l = Label(w, text="NAME", width=20, height=3, bg="green", fg="yellow")
[Link](row=0, column=0, sticky=W, padx=10, pady=5)
# AGE Label - Aligned to Right (East)
l1 = Label(w, text="AGE", width=20, height=3, bg="green", fg="yellow")
[Link](row=1, column=1, sticky=E, padx=10, pady=5)
# ROLLNO Label - Aligned to Top (North)
l2 = Label(w, text="ROLLNO", width=20, height=3, bg="green", fg="yellow")
[Link](row=2, column=2, sticky=N, padx=10, pady=5)
# FREE Label - Aligned to Bottom (South)
l3 = Label(w, text="FREE", width=20, height=3, bg="green", fg="yellow")
[Link](row=3, column=3, sticky=S, padx=10, pady=5)
# Run the main event loop
[Link]()
Real time(calculater):
from tkinter import *
# Function to handle button clicks
def click(btn_text):
current = [Link]()
[Link](0, END)
[Link](0, current + btn_text)
# Function to clear the entry
def clear():
[Link](0, END)
# Function to evaluate the expression
def evaluate():
try:
result = str(eval([Link]()))
[Link](0, END)
[Link](0, result)
except:
[Link](0, END)
[Link](0, "Error")
# Main window
root = Tk()
[Link]("Calculator")
[Link]("280x350")
# Entry box for input/output
entry = Entry(root, width=25, font=('Arial', 18), borderwidth=2, relief=RIDGE, justify='right')
[Link](row=0, column=0, columnspan=4, padx=10, pady=10)
# Button layout
buttons = [
('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3)
]
# Create and place buttons
for (text, row, col) in buttons:
action = evaluate if text == '=' else lambda t=text: click(t)
Button(root, text=text, width=5, height=2, font=('Arial', 14),
command=action).grid(row=row, column=col, padx=5, pady=5)
# Clear button
Button(root, text='C', width=22, height=2, font=('Arial', 14),
command=clear).grid(row=5, column=0, columnspan=4, padx=5, pady=10)
# Run the app
[Link]()
real time example two: from tkinter import *
# Function to display entered details
def submit():
name = entry_name.get()
age = entry_age.get()
course = entry_course.get()
result_label.config(
text=f"Name: {name}\nAge: {age}\nCourse: {course}", fg="blue"
)
# Create main window
w = Tk()
[Link]("Student Details Form")
[Link]("300x250")
# Labels and Entry fields
Label(w, text="Student Name:").grid(row=0, column=0, padx=10, pady=5, sticky=E)
entry_name = Entry(w)
entry_name.grid(row=0, column=1, padx=10, pady=5)
Label(w, text="Age:").grid(row=1, column=0, padx=10, pady=5, sticky=E)
entry_age = Entry(w)
entry_age.grid(row=1, column=1, padx=10, pady=5)
Label(w, text="Course:").grid(row=2, column=0, padx=10, pady=5, sticky=E)
entry_course = Entry(w)
entry_course.grid(row=2, column=1, padx=10, pady=5)
# Submit Button
Button(w, text="Submit", command=submit).grid(row=3, column=0, columnspan=2, pady=10)
# Label to show result
result_label = Label(w, text="", font=("Arial", 10))
result_label.grid(row=4, column=0, columnspan=2, pady=5)
# Start the GUI
[Link]()
place:
from tkinter import *
# Main window
w = Tk()
[Link]("Place Geometry Simple Example")
[Link]("300x200")
# Label for name
Label(w, text="Name:").place(x=30, y=30)
# Entry for name
Entry(w).place(x=100, y=30)
# Label for age
Label(w, text="Age:").place(x=30, y=70)
# Entry for age
Entry(w).place(x=100, y=70)
# Label for course
Label(w, text="Course:").place(x=30, y=110)
# Entry for course
Entry(w).place(x=100, y=110)
# Run the GUI
[Link]()
Real time: from tkinter import *
# Function to display name
def display_name():
name = entry_name.get()
label_result.config(text="Hello, " + name)
# Main window
w = Tk()
[Link]("Student Name Display")
[Link]("300x200")
# Label and Entry
Label(w, text="Enter your name:").place(x=30, y=30)
entry_name = Entry(w)
entry_name.place(x=140, y=30)
# Button to show name
Button(w, text="Submit", command=display_name).place(x=110, y=70)
# Label to display result
label_result = Label(w, text="")
label_result.place(x=90, y=110)
# Run GUI
[Link]()