Unit V: Python Packages & GUI Programming
NumPy, Pandas, Matplotlib, and Tkinter GUI Development
Python Packages
Packages are collections of modules that extend Python's functionality. Python has a rich ecosystem of packages for various purposes.
Installing Packages
# Install packages using pip (Python Package Installer)
# Basic installation
# pip install numpy
# pip install pandas
# pip install matplotlib
# Install specific version
# pip install numpy==1.21.0
# Install multiple packages
# pip install numpy pandas matplotlib
# Upgrade package
# pip install --upgrade numpy
# List installed packages
# pip list
# Uninstall package
# pip uninstall numpy
Importing Packages
# Different ways to import
# Import entire module
import numpy
arr = numpy.array([1, 2, 3])
# Import with alias (common practice)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
arr = np.array([1, 2, 3])
# Import specific functions
from numpy import array, zeros, ones
arr = array([1, 2, 3])
# Import everything (not recommended)
from numpy import *
arr = array([1, 2, 3])
Note
Before running the code examples below, make sure you have installed the required packages using pip.
NumPy - Numerical Python
NumPy is the fundamental package for numerical computing in Python. It provides support for large, multi-dimensional arrays and matrices.
Creating Arrays
import numpy as np
# Creating arrays from lists
arr1 = np.array([1, 2, 3, 4, 5])
print("1D Array:", arr1)
# 2D Array (matrix)
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print("2D Array:\n", arr2)
# Special arrays
zeros = np.zeros((3, 4)) # 3x4 array of zeros
print("Zeros:\n", zeros)
ones = np.ones((2, 3)) # 2x3 array of ones
print("Ones:\n", ones)
identity = np.eye(3) # 3x3 identity matrix
print("Identity:\n", identity)
# Range arrays
range_arr = np.arange(0, 10, 2) # Start, stop, step
print("Range:", range_arr) # [0 2 4 6 8]
# Evenly spaced values
linspace = np.linspace(0, 1, 5) # 5 values from 0 to 1
print("Linspace:", linspace) # [0. 0.25 0.5 0.75 1. ]
# Random arrays
random_arr = np.random.rand(3, 3) # 3x3 random values (0-1)
print("Random:\n", random_arr)
random_int = np.random.randint(1, 100, size=(3, 3)) # Random integers
print("Random Integers:\n", random_int)
Array Attributes and Indexing
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# Array attributes
print("Shape:", arr.shape) # (3, 4) - 3 rows, 4 columns
print("Dimensions:", arr.ndim) # 2
print("Size:", arr.size) # 12 (total elements)
print("Data type:", arr.dtype) # int64
# Indexing
print("\nIndexing:")
print("Element [0,0]:", arr[0, 0]) # 1
print("Element [1,2]:", arr[1, 2]) # 7
print("Last element:", arr[-1, -1]) # 12
# Slicing
print("\nSlicing:")
print("First row:", arr[0]) # [1 2 3 4]
print("First column:", arr[:, 0]) # [1 5 9]
print("Subarray:", arr[0:2, 1:3]) # [[2 3] [6 7]]
# Boolean indexing
print("\nBoolean indexing:")
print("Elements > 5:", arr[arr > 5]) # [6 7 8 9 10 11 12]
# Reshape
reshaped = arr.reshape(4, 3)
print("\nReshaped (4x3):\n", reshaped)
# Flatten
flat = arr.flatten()
print("Flattened:", flat) # [1 2 3 4 5 6 7 8 9 10 11 12]
Array Operations
import numpy as np
# Arithmetic operations (element-wise)
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
print("Addition:", a + b) # [6 8 10 12]
print("Subtraction:", a - b) # [-4 -4 -4 -4]
print("Multiplication:", a * b) # [5 12 21 32]
print("Division:", b / a) # [5. 3. 2.33... 2.]
print("Power:", a ** 2) # [1 4 9 16]
# Scalar operations
print("\nScalar operations:")
print("a + 10:", a + 10) # [11 12 13 14]
print("a * 2:", a * 2) # [2 4 6 8]
# Mathematical functions
print("\nMath functions:")
print("Square root:", np.sqrt(a)) # [1. 1.41... 1.73... 2.]
print("Exponential:", np.exp(a)) # [2.72 7.39 20.09 54.60]
print("Logarithm:", np.log(a)) # [0. 0.69 1.10 1.39]
print("Sin:", np.sin(a))
# Aggregate functions
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("\nAggregate functions:")
print("Sum:", np.sum(arr)) # 21
print("Mean:", np.mean(arr)) # 3.5
print("Max:", np.max(arr)) # 6
print("Min:", np.min(arr)) # 1
print("Std Dev:", np.std(arr)) # 1.707...
# Axis-wise operations
print("\nAxis operations:")
print("Sum (rows):", np.sum(arr, axis=1)) # [6 15]
print("Sum (columns):", np.sum(arr, axis=0)) # [5 7 9]
print("Mean (rows):", np.mean(arr, axis=1)) # [2. 5.]
# Matrix operations
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print("\nMatrix operations:")
print("Matrix multiply:\n", np.dot(A, B)) # or A @ B
print("Transpose:\n", A.T)
print("Determinant:", np.linalg.det(A))
Pandas - Data Analysis
Pandas is a powerful data manipulation and analysis library. It provides DataFrame and Series data structures for handling structured data.
Series and DataFrame
import pandas as pd
import numpy as np
# Series - 1D labeled array
s = pd.Series([10, 20, 30, 40, 50])
print("Series:")
print(s)
# Series with custom index
s = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
print("\nSeries with index:")
print(s)
print("Access 'b':", s['b']) # 20
# DataFrame - 2D labeled data structure
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 28],
'City': ['New York', 'Boston', 'Chicago', 'Seattle'],
'Salary': [50000, 60000, 75000, 55000]
}
df = pd.DataFrame(data)
print("\nDataFrame:")
print(df)
# DataFrame from list of lists
data = [
['Alice', 25, 'New York'],
['Bob', 30, 'Boston'],
['Charlie', 35, 'Chicago']
]
df = pd.DataFrame(data, columns=['Name', 'Age', 'City'])
print("\nFrom list:")
print(df)
Reading and Writing Data
import pandas as pd
# Create sample DataFrame
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Score': [85, 92, 78]
})
# Save to CSV
df.to_csv('students.csv', index=False)
print("Saved to CSV")
# Read from CSV
df_read = pd.read_csv('students.csv')
print("\nRead from CSV:")
print(df_read)
# Save to Excel (requires openpyxl)
# df.to_excel('students.xlsx', index=False)
# Read from Excel
# df_excel = pd.read_excel('students.xlsx')
# Read from JSON
# df_json = pd.read_json('data.json')
# Display first/last rows
print("\nFirst 2 rows:")
print(df.head(2))
print("\nLast 2 rows:")
print(df.tail(2))
# DataFrame info
print("\nInfo:")
print(df.info())
print("\nStatistics:")
print(df.describe())
Data Selection and Filtering
import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [25, 30, 35, 28, 32],
'City': ['NYC', 'Boston', 'NYC', 'Seattle', 'Boston'],
'Salary': [50000, 60000, 75000, 55000, 65000]
})
# Column selection
print("Names:", df['Name'].tolist())
print("\nMultiple columns:")
print(df[['Name', 'Age']])
# Row selection with iloc (index-based)
print("\nFirst row:")
print(df.iloc[0])
print("\nRows 1-3:")
print(df.iloc[1:4])
# Row selection with loc (label-based)
df.index = ['a', 'b', 'c', 'd', 'e']
print("\nRow 'b':")
print(df.loc['b'])
# Conditional filtering
print("\nAge > 28:")
print(df[df['Age'] > 28])
print("\nNYC residents:")
print(df[df['City'] == 'NYC'])
# Multiple conditions
print("\nAge > 25 AND Salary > 55000:")
print(df[(df['Age'] > 25) & (df['Salary'] > 55000)])
# Query method (alternative)
print("\nUsing query:")
print(df.query('Age > 30'))
Data Manipulation
import pandas as pd
import numpy as np
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, None, 28],
'Salary': [50000, 60000, 75000, 55000],
'Department': ['IT', 'HR', 'IT', 'Finance']
})
# Adding new column
df['Bonus'] = df['Salary'] * 0.1
print("With Bonus column:")
print(df)
# Modifying column
df['Age'] = df['Age'].fillna(df['Age'].mean())
print("\nFilled missing age:")
print(df)
# Dropping columns
df_dropped = df.drop('Bonus', axis=1)
print("\nDropped Bonus:")
print(df_dropped)
# Sorting
print("\nSorted by Age:")
print(df.sort_values('Age'))
print("\nSorted by multiple columns:")
print(df.sort_values(['Department', 'Salary'], ascending=[True, False]))
# Grouping
print("\nGrouped by Department:")
print(df.groupby('Department')['Salary'].mean())
# Aggregation
print("\nMultiple aggregations:")
print(df.groupby('Department').agg({
'Salary': ['mean', 'sum'],
'Age': 'mean'
}))
# Apply function
df['Salary_Category'] = df['Salary'].apply(
lambda x: 'High' if x > 55000 else 'Low'
)
print("\nWith category:")
print(df)
Matplotlib - Data Visualization
Matplotlib is the most popular plotting library for Python. It provides a MATLAB-like interface for creating visualizations.
Basic Plotting
import matplotlib.pyplot as plt
import numpy as np
# Simple line plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.title('Simple Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
# Line plot with styling
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.figure(figsize=(10, 6))
plt.plot(x, y1, 'b-', label='sin(x)', linewidth=2)
plt.plot(x, y2, 'r--', label='cos(x)', linewidth=2)
plt.title('Trigonometric Functions')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
Visual Output - Line Plot
Blue solid line = sin(x), Red dashed line = cos(x), both oscillating between -1 and 1
Different Plot Types
import matplotlib.pyplot as plt
import numpy as np
# Bar Chart
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]
plt.figure(figsize=(8, 5))
plt.bar(categories, values, color='steelblue')
plt.title('Bar Chart')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
# Pie Chart
sizes = [30, 25, 20, 15, 10]
labels = ['Python', 'JavaScript', 'Java', 'C++', 'Other']
explode = (0.1, 0, 0, 0, 0) # Explode first slice
plt.figure(figsize=(8, 8))
plt.pie(sizes, labels=labels, explode=explode, autopct='%1.1f%%',
shadow=True, startangle=90)
plt.title('Programming Language Usage')
plt.show()
# Scatter Plot
np.random.seed(42)
x = np.random.randn(100)
y = 2*x + np.random.randn(100)
plt.figure(figsize=(8, 6))
plt.scatter(x, y, c='blue', alpha=0.6)
plt.title('Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
# Histogram
data = np.random.randn(1000)
plt.figure(figsize=(8, 6))
plt.hist(data, bins=30, color='green', alpha=0.7, edgecolor='black')
plt.title('Histogram')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
Visual Output - Plot Types
Vertical bars compare categories
Slices show proportions
Dots show correlation
Normal distribution (bell curve)
Subplots and Advanced Features
import matplotlib.pyplot as plt
import numpy as np
# Multiple subplots
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Subplot 1: Line plot
x = np.linspace(0, 10, 100)
axes[0, 0].plot(x, np.sin(x), 'b-')
axes[0, 0].set_title('Sine Wave')
axes[0, 0].set_xlabel('x')
axes[0, 0].set_ylabel('sin(x)')
# Subplot 2: Bar chart
categories = ['A', 'B', 'C', 'D']
values = [25, 40, 30, 55]
axes[0, 1].bar(categories, values, color='orange')
axes[0, 1].set_title('Bar Chart')
# Subplot 3: Scatter plot
x = np.random.randn(50)
y = x + np.random.randn(50)
axes[1, 0].scatter(x, y, c='green', alpha=0.6)
axes[1, 0].set_title('Scatter Plot')
# Subplot 4: Pie chart
sizes = [35, 30, 20, 15]
axes[1, 1].pie(sizes, labels=categories, autopct='%1.1f%%')
axes[1, 1].set_title('Pie Chart')
plt.tight_layout()
plt.savefig('subplots.png', dpi=300) # Save figure
plt.show()
# Customizing plot appearance
plt.style.use('seaborn-v0_8-darkgrid') # Use a style
x = np.linspace(0, 10, 100)
plt.figure(figsize=(10, 6))
plt.plot(x, np.sin(x), 'b-', label='sin', linewidth=2)
plt.plot(x, np.cos(x), 'r--', label='cos', linewidth=2)
plt.title('Customized Plot', fontsize=16, fontweight='bold')
plt.xlabel('X-axis', fontsize=12)
plt.ylabel('Y-axis', fontsize=12)
plt.legend(loc='upper right', fontsize=10)
plt.xlim(0, 10)
plt.ylim(-1.5, 1.5)
plt.grid(True, alpha=0.3)
plt.show()
Visual Output - Subplots (2×2 Grid)
plt.tight_layout() adjusts spacing to prevent overlap. plt.savefig('file.png', dpi=300) saves as high-quality image.
Key Matplotlib Functions Summary
| Function | What It Does | Example |
|---|---|---|
plt.plot(x, y) | Draws a line connecting points | Line charts, trends |
plt.bar(x, height) | Creates vertical bars | Comparing categories |
plt.pie(sizes) | Creates circular pie chart | Showing proportions |
plt.scatter(x, y) | Plots individual points | Showing relationships |
plt.hist(data) | Shows data distribution | Frequency analysis |
plt.figure(figsize) | Sets figure size (width, height) | figsize=(10, 6) |
plt.subplot(rows, cols, n) | Creates grid of plots | Multiple charts together |
plt.title() | Adds title to plot | Chart heading |
plt.xlabel() / ylabel() | Labels for axes | Axis descriptions |
plt.legend() | Shows legend box | Identify multiple lines |
plt.show() | Displays the plot window | Required to see output |
plt.savefig('name.png') | Saves plot as image file | Export for reports |
Tkinter - GUI Programming
Tkinter is Python's standard GUI (Graphical User Interface) library. It provides a fast and easy way to create GUI applications.
Basic Window
import tkinter as tk
# Create main window
root = tk.Tk()
# Window properties
root.title("My First GUI App")
root.geometry("400x300") # Width x Height
root.resizable(True, True) # Allow resize
# Configure background color
root.configure(bg='lightblue')
# Add a label
label = tk.Label(root, text="Hello, Tkinter!",
font=("Arial", 24),
bg='lightblue')
label.pack(pady=50)
# Start the event loop
root.mainloop()
Visual Output - Basic Tkinter Window
Window with title bar (minimize, maximize, close buttons), light blue background, and centered label text
Window Configuration
import tkinter as tk
root = tk.Tk()
# Window title
root.title("Configured Window")
# Window size and position
# Format: "widthxheight+x_position+y_position"
root.geometry("500x400+100+100")
# Minimum and maximum size
root.minsize(300, 200)
root.maxsize(800, 600)
# Icon (if available)
# root.iconbitmap('icon.ico')
# Full screen mode
# root.attributes('-fullscreen', True)
# Always on top
# root.attributes('-topmost', True)
# Transparency (0.0 = invisible, 1.0 = opaque)
root.attributes('-alpha', 0.95)
# Disable/enable window controls
# root.resizable(False, False) # Disable resize
# Handle window close
def on_close():
print("Window closing...")
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_close)
root.mainloop()
Visual Output - Window Configuration
geometry("500x400+100+100") positions window 100px from left edge and 100px from top of screen
Tkinter Widgets
Widgets are the building blocks of a GUI application. Tkinter provides various widgets for different purposes.
Common Widgets
| Widget | Purpose |
|---|---|
| Label | Display text or images |
| Button | Clickable button |
| Entry | Single-line text input |
| Text | Multi-line text input |
| Frame | Container for other widgets |
| Checkbutton | Checkbox |
| Radiobutton | Radio button |
| Listbox | List of items |
| Combobox | Dropdown list |
| Scale | Slider |
| Canvas | Drawing area |
| Menu | Menu bar |
Labels and Buttons
import tkinter as tk
root = tk.Tk()
root.title("Labels and Buttons")
root.geometry("400x300")
# Label widget
label = tk.Label(root,
text="Welcome to Tkinter!",
font=("Arial", 18, "bold"),
fg="blue",
bg="lightyellow",
padx=20, pady=10)
label.pack(pady=20)
# Variable to update label
click_count = tk.IntVar(value=0)
def button_click():
count = click_count.get() + 1
click_count.set(count)
result_label.config(text=f"Button clicked {count} times!")
# Button widget
button = tk.Button(root,
text="Click Me!",
command=button_click,
font=("Arial", 14),
bg="green", fg="white",
padx=20, pady=10,
activebackground="darkgreen")
button.pack(pady=10)
# Result label
result_label = tk.Label(root, text="Button not clicked yet",
font=("Arial", 12))
result_label.pack(pady=10)
# Quit button
quit_button = tk.Button(root, text="Quit",
command=root.destroy,
bg="red", fg="white")
quit_button.pack(pady=20)
root.mainloop()
Visual Output - Labels & Buttons
Yellow label at top, green button increments counter, red button closes window
Entry and Text Widgets
import tkinter as tk
root = tk.Tk()
root.title("Input Widgets")
root.geometry("450x400")
# Single-line Entry
tk.Label(root, text="Name:", font=("Arial", 12)).pack(pady=(20, 5))
name_entry = tk.Entry(root, font=("Arial", 12), width=30)
name_entry.pack(pady=5)
name_entry.insert(0, "Enter your name") # Default text
# Password Entry
tk.Label(root, text="Password:", font=("Arial", 12)).pack(pady=(10, 5))
password_entry = tk.Entry(root, font=("Arial", 12), width=30, show="*")
password_entry.pack(pady=5)
# Multi-line Text widget
tk.Label(root, text="Message:", font=("Arial", 12)).pack(pady=(10, 5))
text_widget = tk.Text(root, height=5, width=35, font=("Arial", 11))
text_widget.pack(pady=5)
text_widget.insert("1.0", "Enter your message here...")
def submit():
name = name_entry.get()
password = password_entry.get()
message = text_widget.get("1.0", tk.END).strip()
result = f"Name: {name}\nMessage: {message}"
output_label.config(text=result)
def clear():
name_entry.delete(0, tk.END)
password_entry.delete(0, tk.END)
text_widget.delete("1.0", tk.END)
# Buttons
button_frame = tk.Frame(root)
button_frame.pack(pady=10)
submit_btn = tk.Button(button_frame, text="Submit", command=submit,
bg="blue", fg="white", padx=20)
submit_btn.pack(side=tk.LEFT, padx=10)
clear_btn = tk.Button(button_frame, text="Clear", command=clear,
bg="gray", fg="white", padx=20)
clear_btn.pack(side=tk.LEFT, padx=10)
# Output label
output_label = tk.Label(root, text="", font=("Arial", 10),
justify=tk.LEFT)
output_label.pack(pady=10)
root.mainloop()
Visual Output - Entry & Text Widgets
Form with text entry (single line), password field (shows •••), and multi-line text area
Layout Managers
import tkinter as tk
# pack() - Simple layout
def pack_demo():
win = tk.Toplevel()
win.title("Pack Demo")
win.geometry("300x200")
tk.Label(win, text="Top", bg="red", fg="white").pack(fill=tk.X)
tk.Label(win, text="Bottom", bg="blue", fg="white").pack(side=tk.BOTTOM, fill=tk.X)
tk.Label(win, text="Left", bg="green", fg="white").pack(side=tk.LEFT, fill=tk.Y)
tk.Label(win, text="Right", bg="yellow").pack(side=tk.RIGHT, fill=tk.Y)
tk.Label(win, text="Center", bg="purple", fg="white").pack(expand=True, fill=tk.BOTH)
# grid() - Table-like layout
def grid_demo():
win = tk.Toplevel()
win.title("Grid Demo")
tk.Label(win, text="Username:").grid(row=0, column=0, padx=10, pady=10, sticky="e")
tk.Entry(win).grid(row=0, column=1, padx=10, pady=10)
tk.Label(win, text="Password:").grid(row=1, column=0, padx=10, pady=10, sticky="e")
tk.Entry(win, show="*").grid(row=1, column=1, padx=10, pady=10)
tk.Button(win, text="Login").grid(row=2, column=0, columnspan=2, pady=20)
# place() - Absolute positioning
def place_demo():
win = tk.Toplevel()
win.title("Place Demo")
win.geometry("300x200")
tk.Button(win, text="Button 1").place(x=50, y=50)
tk.Button(win, text="Button 2").place(x=150, y=100)
tk.Button(win, text="Centered", width=10).place(relx=0.5, rely=0.5, anchor=tk.CENTER)
# Main window
root = tk.Tk()
root.title("Layout Managers")
root.geometry("300x200")
tk.Button(root, text="Pack Demo", command=pack_demo, width=20).pack(pady=20)
tk.Button(root, text="Grid Demo", command=grid_demo, width=20).pack(pady=10)
tk.Button(root, text="Place Demo", command=place_demo, width=20).pack(pady=10)
root.mainloop()
Visual Output - Layout Managers
pack() - Stack widgets
grid() - Table layout
place() - Exact position
Checkboxes and Radio Buttons
import tkinter as tk
root = tk.Tk()
root.title("Selection Widgets")
root.geometry("400x350")
# Checkbuttons
tk.Label(root, text="Select your hobbies:", font=("Arial", 12, "bold")).pack(pady=10)
hobby1 = tk.BooleanVar()
hobby2 = tk.BooleanVar()
hobby3 = tk.BooleanVar()
tk.Checkbutton(root, text="Reading", variable=hobby1,
font=("Arial", 11)).pack(anchor="w", padx=50)
tk.Checkbutton(root, text="Gaming", variable=hobby2,
font=("Arial", 11)).pack(anchor="w", padx=50)
tk.Checkbutton(root, text="Sports", variable=hobby3,
font=("Arial", 11)).pack(anchor="w", padx=50)
# Separator
tk.Frame(root, height=2, bg="gray").pack(fill="x", pady=20)
# Radio buttons
tk.Label(root, text="Select your gender:", font=("Arial", 12, "bold")).pack(pady=10)
gender = tk.StringVar(value="")
tk.Radiobutton(root, text="Male", variable=gender, value="Male",
font=("Arial", 11)).pack(anchor="w", padx=50)
tk.Radiobutton(root, text="Female", variable=gender, value="Female",
font=("Arial", 11)).pack(anchor="w", padx=50)
tk.Radiobutton(root, text="Other", variable=gender, value="Other",
font=("Arial", 11)).pack(anchor="w", padx=50)
def show_selection():
hobbies = []
if hobby1.get(): hobbies.append("Reading")
if hobby2.get(): hobbies.append("Gaming")
if hobby3.get(): hobbies.append("Sports")
result = f"Hobbies: {', '.join(hobbies) or 'None'}\nGender: {gender.get() or 'Not selected'}"
result_label.config(text=result)
tk.Button(root, text="Show Selection", command=show_selection,
bg="blue", fg="white", padx=20).pack(pady=20)
result_label = tk.Label(root, text="", font=("Arial", 10))
result_label.pack()
root.mainloop()
Visual Output - Checkboxes & Radio Buttons
☑ Checkboxes allow multiple selections, ◉ Radio buttons allow only one selection
Tkinter Complete Examples
Example 1: Simple Calculator
import tkinter as tk
class Calculator:
def __init__(self, root):
self.root = root
self.root.title("Calculator")
self.root.geometry("300x400")
self.root.resizable(False, False)
self.expression = ""
# Display
self.display = tk.Entry(root, font=("Arial", 24),
justify="right", bd=10)
self.display.grid(row=0, column=0, columnspan=4,
sticky="nsew", padx=5, pady=5)
# Button layout
buttons = [
('C', 1, 0), ('±', 1, 1), ('%', 1, 2), ('/', 1, 3),
('7', 2, 0), ('8', 2, 1), ('9', 2, 2), ('*', 2, 3),
('4', 3, 0), ('5', 3, 1), ('6', 3, 2), ('-', 3, 3),
('1', 4, 0), ('2', 4, 1), ('3', 4, 2), ('+', 4, 3),
('0', 5, 0, 2), ('.', 5, 2), ('=', 5, 3)
]
for btn in buttons:
text = btn[0]
row = btn[1]
col = btn[2]
colspan = btn[3] if len(btn) > 3 else 1
button = tk.Button(root, text=text, font=("Arial", 18),
command=lambda t=text: self.click(t))
button.grid(row=row, column=col, columnspan=colspan,
sticky="nsew", padx=2, pady=2)
# Configure grid weights
for i in range(6):
root.grid_rowconfigure(i, weight=1)
for i in range(4):
root.grid_columnconfigure(i, weight=1)
def click(self, char):
if char == 'C':
self.expression = ""
elif char == '=':
try:
self.expression = str(eval(self.expression))
except:
self.expression = "Error"
elif char == '±':
try:
self.expression = str(-float(self.expression))
except:
pass
elif char == '%':
try:
self.expression = str(float(self.expression) / 100)
except:
pass
else:
self.expression += char
self.display.delete(0, tk.END)
self.display.insert(0, self.expression)
root = tk.Tk()
app = Calculator(root)
root.mainloop()
Visual Output - Calculator App
Dark theme calculator with number pad, operators (orange), and wide "0" button using columnspan
Example 2: To-Do List Application
import tkinter as tk
from tkinter import messagebox
class TodoApp:
def __init__(self, root):
self.root = root
self.root.title("To-Do List")
self.root.geometry("400x500")
# Title
title = tk.Label(root, text="My To-Do List",
font=("Arial", 20, "bold"))
title.pack(pady=20)
# Input frame
input_frame = tk.Frame(root)
input_frame.pack(pady=10)
self.task_entry = tk.Entry(input_frame, font=("Arial", 14),
width=25)
self.task_entry.pack(side=tk.LEFT, padx=5)
add_btn = tk.Button(input_frame, text="Add",
command=self.add_task,
bg="green", fg="white",
font=("Arial", 12))
add_btn.pack(side=tk.LEFT)
# Listbox with scrollbar
list_frame = tk.Frame(root)
list_frame.pack(pady=20, fill=tk.BOTH, expand=True, padx=20)
scrollbar = tk.Scrollbar(list_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.task_list = tk.Listbox(list_frame, font=("Arial", 14),
height=10, selectmode=tk.SINGLE,
yscrollcommand=scrollbar.set)
self.task_list.pack(fill=tk.BOTH, expand=True)
scrollbar.config(command=self.task_list.yview)
# Buttons frame
btn_frame = tk.Frame(root)
btn_frame.pack(pady=10)
complete_btn = tk.Button(btn_frame, text="Mark Complete",
command=self.mark_complete,
bg="blue", fg="white",
font=("Arial", 11))
complete_btn.pack(side=tk.LEFT, padx=5)
delete_btn = tk.Button(btn_frame, text="Delete",
command=self.delete_task,
bg="red", fg="white",
font=("Arial", 11))
delete_btn.pack(side=tk.LEFT, padx=5)
clear_btn = tk.Button(btn_frame, text="Clear All",
command=self.clear_all,
bg="gray", fg="white",
font=("Arial", 11))
clear_btn.pack(side=tk.LEFT, padx=5)
# Status bar
self.status = tk.Label(root, text="Tasks: 0",
font=("Arial", 10))
self.status.pack(pady=10)
def add_task(self):
task = self.task_entry.get().strip()
if task:
self.task_list.insert(tk.END, f"☐ {task}")
self.task_entry.delete(0, tk.END)
self.update_status()
else:
messagebox.showwarning("Warning", "Please enter a task!")
def mark_complete(self):
try:
index = self.task_list.curselection()[0]
task = self.task_list.get(index)
if task.startswith("☐"):
self.task_list.delete(index)
self.task_list.insert(index, task.replace("☐", "✓"))
self.task_list.itemconfig(index, fg="green")
except IndexError:
messagebox.showinfo("Info", "Please select a task!")
def delete_task(self):
try:
index = self.task_list.curselection()[0]
self.task_list.delete(index)
self.update_status()
except IndexError:
messagebox.showinfo("Info", "Please select a task!")
def clear_all(self):
if messagebox.askyesno("Confirm", "Delete all tasks?"):
self.task_list.delete(0, tk.END)
self.update_status()
def update_status(self):
count = self.task_list.size()
self.status.config(text=f"Tasks: {count}")
root = tk.Tk()
app = TodoApp(root)
root.mainloop()
Visual Output - To-Do List App
Task list with ✓ completed (green) and ☐ pending items, scrollbar, and action buttons
Example 3: Temperature Converter
import tkinter as tk
from tkinter import ttk
class TemperatureConverter:
def __init__(self, root):
self.root = root
self.root.title("Temperature Converter")
self.root.geometry("350x250")
# Title
tk.Label(root, text="Temperature Converter",
font=("Arial", 16, "bold")).pack(pady=20)
# Input frame
input_frame = tk.Frame(root)
input_frame.pack(pady=10)
self.temp_var = tk.StringVar()
temp_entry = tk.Entry(input_frame, textvariable=self.temp_var,
font=("Arial", 14), width=15)
temp_entry.pack(side=tk.LEFT, padx=5)
self.unit_var = tk.StringVar(value="Celsius")
unit_combo = ttk.Combobox(input_frame, textvariable=self.unit_var,
values=["Celsius", "Fahrenheit", "Kelvin"],
state="readonly", width=12)
unit_combo.pack(side=tk.LEFT)
# Convert button
tk.Button(root, text="Convert", command=self.convert,
bg="blue", fg="white", font=("Arial", 12),
padx=30).pack(pady=20)
# Results
self.result_label = tk.Label(root, text="", font=("Arial", 12))
self.result_label.pack(pady=10)
def convert(self):
try:
temp = float(self.temp_var.get())
unit = self.unit_var.get()
# Convert to Celsius first
if unit == "Celsius":
celsius = temp
elif unit == "Fahrenheit":
celsius = (temp - 32) * 5/9
else: # Kelvin
celsius = temp - 273.15
# Convert from Celsius to all units
fahrenheit = (celsius * 9/5) + 32
kelvin = celsius + 273.15
result = f"Celsius: {celsius:.2f}°C\n"
result += f"Fahrenheit: {fahrenheit:.2f}°F\n"
result += f"Kelvin: {kelvin:.2f}K"
self.result_label.config(text=result)
except ValueError:
self.result_label.config(text="Please enter a valid number!")
root = tk.Tk()
app = TemperatureConverter(root)
root.mainloop()
Visual Output - Temperature Converter
Input field with dropdown selector, converts to all 3 temperature units at once
Tkinter Widgets Summary
| Widget | Purpose | Key Properties |
|---|---|---|
tk.Tk() | Main application window | title(), geometry(), mainloop() |
tk.Label() | Display text/images | text, font, fg, bg |
tk.Button() | Clickable button | text, command, bg, fg |
tk.Entry() | Single-line text input | get(), insert(), delete() |
tk.Text() | Multi-line text area | height, width, insert("1.0", text) |
tk.Frame() | Container for grouping | bg, padx, pady |
tk.Checkbutton() | Checkbox (multi-select) | variable=BooleanVar() |
tk.Radiobutton() | Radio button (single-select) | variable=StringVar(), value |
tk.Listbox() | Scrollable item list | insert(), delete(), get() |
ttk.Combobox() | Dropdown menu | values=["a","b"], state="readonly" |
Layout Methods Comparison
| Method | Use Case | Example |
|---|---|---|
pack() | Simple vertical/horizontal stacking | widget.pack(side=tk.LEFT, pady=10) |
grid() | Table-like rows and columns | widget.grid(row=0, column=1, columnspan=2) |
place() | Exact pixel positioning | widget.place(x=100, y=50) or relx=0.5 |
Python Programming with IDE
An IDE (Integrated Development Environment) provides tools for efficient coding, debugging, and project management.
Popular Python IDEs
| IDE | Description | Best For |
|---|---|---|
| VS Code | Free, lightweight, extensible | General development |
| PyCharm | Full-featured Python IDE | Professional development |
| IDLE | Python's built-in IDE | Learning & small scripts |
| Jupyter Notebook | Interactive notebooks | Data science & learning |
| Spyder | Scientific Python IDE | Data science & engineering |
| Thonny | Beginner-friendly IDE | Learning Python |
IDE Features
- Syntax Highlighting: Colors different parts of code for readability
- Auto-completion: Suggests code as you type
- Debugging: Step through code, set breakpoints
- Integrated Terminal: Run commands without leaving IDE
- Version Control: Git integration
- Code Navigation: Jump to definitions, find references
- Linting: Automatic error checking
- Extensions: Add functionality with plugins
VS Code Setup for Python
# 1. Install VS Code from https://code.visualstudio.com
# 2. Install Python extension
# - Open Extensions (Ctrl+Shift+X)
# - Search "Python"
# - Install Microsoft's Python extension
# 3. Select Python interpreter
# - Ctrl+Shift+P → "Python: Select Interpreter"
# - Choose your Python installation
# 4. Create a Python file
# - Create new file with .py extension
# - Write your code
# 5. Run Python code
# - Right-click → Run Python File in Terminal
# - Or press F5 to debug
# 6. Useful extensions:
# - Pylint (linting)
# - Python Docstring Generator
# - Jupyter (for notebooks)
# - Code Runner
# 7. settings.json (optional)
{
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.formatting.provider": "black",
"editor.formatOnSave": true
}
Recommendation
For beginners, start with VS Code or Thonny. As you advance, consider PyCharm for larger projects. For data science, Jupyter Notebook is excellent for experimentation.
Running Python Programs
# Method 1: Command Line
# Open terminal/command prompt
# python filename.py
# Method 2: IDE Run Button
# Click the "Run" button or press F5
# Method 3: Interactive Mode
# Type 'python' in terminal to open interpreter
# >>> print("Hello")
# Hello
# >>> exit()
# Method 4: Python IDLE
# Open IDLE → File → New File → Write code → Run
# Method 5: Jupyter Notebook
# jupyter notebook
# Create new notebook → Write code in cells → Run cells