1) Implement a program creating Types of GUI Widgets, Resizing, and
Configuring Options
import tkinter as tk
from tkinter import ttk
# Create the main window
root = tk.Tk()
root.title("GUI Widgets Example")
root.geometry("600x600") # Set the window size
# Label Widget
label = tk.Label(root, text="Welcome to GUI Widgets", font=("Arial", 16),
fg="blue")
label.pack(pady=10) # Add padding for better layout
# Button Widget
def on_button_click():
label.config(text="Button Clicked!")
button = tk.Button(root, text="Click Me!", command=on_button_click,
bg="lightgreen")
button.pack(pady=10)
# Entry Widget
entry_label = tk.Label(root, text="Enter your name:")
entry_label.pack()
entry = tk.Entry(root, width=30)
entry.pack(pady=5)
# Dropdown Menu (Combobox)
dropdown_label = tk.Label(root, text="Choose your favorite language:")
dropdown_label.pack()
languages = ["Python", "Java", "C++", "JavaScript"]
dropdown = ttk.Combobox(root, values=languages)
dropdown.pack(pady=5)
# Checkbox Widget
checkbox_var = tk.BooleanVar()
checkbox = tk.Checkbutton(root, text="I agree to the terms and conditions",
variable=checkbox_var)
checkbox.pack(pady=10)
# Radio Button Widget
radio_label = tk.Label(root, text="Select your gender:")
radio_label.pack()
gender_var = tk.StringVar(value="None")
radio1 = tk.Radiobutton(root, text="Male", variable=gender_var, value="Male")
radio2 = tk.Radiobutton(root, text="Female", variable=gender_var,
value="Female")
radio1.pack()
radio2.pack()
# Text Widget
text_label = tk.Label(root, text="Enter your feedback:")
text_label.pack()
text = tk.Text(root, height=5, width=40, bg="pink")
text.pack(pady=5)
# Resizing Widgets
resize_label = tk.Label(root, text="Resize the window and see widget
adjustments.")
resize_label.pack(pady=10)
# Slider Widget (Scale)
slider_label = tk.Label(root, text="Set your age:")
slider_label.pack()
slider = tk.Scale(root, from_=0, to=100, orient="horizontal")
slider.pack(pady=5)
# Close Button
close_button = tk.Button(root, text="Close", command=root.destroy, bg="red",
fg="white")
close_button.pack(pady=20)
# Run the application
root.mainloop()
Output
2) Implement a program Creating Layouts, Packing Order, Controlling
Widget Appearances.
import tkinter as tk
# Create the main window
root = tk.Tk()
root.title("Layouts, Packing Order, and Widget Appearance")
root.geometry("500x500") # Set window size
# Header Label - Appearance customization
header = tk.Label(
root,
text="Welcome to Layouts Demo",
font=("Helvetica", 16, "bold"),
bg="navy",
fg="white",
padx=10,
pady=10
)
header.pack(fill="x") # Pack at the top, fill horizontally
# Frame 1: Packing Order Demonstration
frame1 = tk.Frame(root, bg="lightgray", pady=10)
frame1.pack(fill="x", padx=10, pady=10)
btn1 = tk.Button(frame1, text="Button 1", bg="red", fg="white", width=12)
btn2 = tk.Button(frame1, text="Button 2", bg="green", fg="white", width=12)
btn3 = tk.Button(frame1, text="Button 3", bg="blue", fg="white", width=12)
btn1.pack(side="left", padx=5)
btn2.pack(side="left", padx=5)
btn3.pack(side="left", padx=5)
# Frame 2: Grid Layout Demonstration
frame2 = tk.Frame(root, bg="white", pady=10)
frame2.pack(fill="x", padx=10, pady=10)
label1 = tk.Label(frame2, text="Row 0, Col 0", bg="cyan", width=15)
label2 = tk.Label(frame2, text="Row 0, Col 1", bg="magenta", width=15)
label3 = tk.Label(frame2, text="Row 1, Col 0", bg="yellow", width=15)
label4 = tk.Label(frame2, text="Row 1, Col 1", bg="orange", width=15)
label1.grid(row=0, column=0, padx=5, pady=5)
label2.grid(row=0, column=1, padx=5, pady=5)
label3.grid(row=1, column=0, padx=5, pady=5)
label4.grid(row=1, column=1, padx=5, pady=5)
# Frame 3: Place Layout Demonstration
frame3 = tk.Frame(root, bg="lightblue", pady=20)
frame3.pack(fill="both", expand=True, padx=10, pady=10)
resizable_button = tk.Button(frame3, text="Centered Button", bg="purple",
fg="white", font=("Arial", 12))
resizable_button.place(relx=0.5, rely=0.5, anchor="center")
# Footer Button - Close Application
footer_button = tk.Button(root, text="Exit", command=root.destroy,
bg="black", fg="white")
footer_button.pack(pady=10)
# Run the application
root.mainloop()
Output
3) Implement a program based on Text Processing, Searching for Files
import os
# User inputs directory path and the search word
directory_path = input("Enter the directory path to search for text files: ")
search_word = input("Enter the word/phrase to search for in the text files: ")
# Check if the provided directory exists
if os.path.isdir(directory_path):
print(f"\nSearching for the word '{search_word}' in the text files within
directory: {directory_path}\n")
# Loop through all the files in the specified directory
for filename in os.listdir(directory_path):
# Check if the file is a text file (i.e., ends with .txt)
if filename.endswith(".txt"):
file_path = os.path.join(directory_path, filename)
try:
# Open the text file for reading
with open(file_path, 'r', encoding='utf-8') as file:
# Read the content of the file
file_content = file.read()
# Perform a case-insensitive search for the search word
if search_word.lower() in file_content.lower(): # Case-insensitive
search
print(f"Found '{search_word}' in file: {filename}")
else:
print(f"'{search_word}' not found in file: {filename}")
except Exception as e:
# Handle errors such as file access issues
print(f"Error reading file {filename}: {e}")
else:
print("The provided directory path does not exist.")
Output
Enter the directory path to search for text files:
D:\Users\LENOVO\Desktop\MCA
Enter the word/phrase to search for in the text files: Python
Searching for the word 'Python' in the text files within directory:
D:\Users\LENOVO\Desktop\MCA
Found 'Python' in file: File1.txt
'Python' not found in file: File2.txt
Found 'Python' in file: File3.txt
4) Implement a program to demonstrate HTML Parsing.
from bs4 import BeautifulSoup
def parse_html(html_content):
"""
Demonstrates HTML parsing by extracting the title, links, and text content.
"""
soup = BeautifulSoup(html_content, 'html.parser')
# Extract and display the title
title = soup.title.string if soup.title else "No title found"
print(f"Title: {title}")
# Extract and display all links
print("\nLinks found:")
for link in soup.find_all('a', href=True):
print(f" {link.text.strip()} -> {link['href']}")
# Extract and display paragraph texts
print("\nParagraphs:")
for para in soup.find_all('p'):
print(f" {para.text.strip()}")
# Extract and display all headings (h1, h2, h3, etc.)
print("\nHeadings:")
for i in range(1, 7): # h1 to h6
for heading in soup.find_all(f"h{i}"):
print(f" {heading.name}: {heading.text.strip()}")
def main():
# Input: HTML content (could also be read from a file)
html_content = """
<html>
<head>
<title>HTML Parsing Example</title>
</head>
<body>
<h1>Main Heading</h1>
<p>This is a paragraph of text.</p>
<a href="https://example.com">Visit Example</a>
<h2>Subheading</h2>
<p>Another paragraph with <a href="https://another.com">another
link</a>.</p>
</body>
</html>
"""
# Parse the HTML content
parse_html(html_content)
if __name__ == "__main__":
main()
Ouitput
Title: HTML Parsing Example
Links found:
Visit Example -> https://example.com
another link -> https://another.com
Paragraphs:
This is a paragraph of text.
Another paragraph with another link.
Headings:
h1: Main Heading
h2: Subheading
5) Implement a program based on paths and directories, file
information, naming, moving, copying, and removing files.
#file information and copying
import shutil
from pathlib import Path
# Define paths
src_folder = Path("source_folder")
dst_folder = Path("destination_folder")
src_file = src_folder / "sample_file.txt"
# Ensure source folder and file exist; create them if they don't
src_folder.mkdir(parents=True, exist_ok=True)
if not src_file.exists():
src_file.write_text("This is a sample file.") # Create a sample file
# Display file and folder information before copying
print(f"\nSource Folder Information:")
print(f"Path: {src_folder}")
print(f"Is it a directory? {'Yes' if src_folder.is_dir() else 'No'}")
print(f"Files in Source Folder: {[file.name for file in src_folder.iterdir()]}")
if src_file.exists():
print(f"\nSource File Information:")
print(f"Path: {src_file}")
print(f"Size: {src_file.stat().st_size} bytes")
print(f"Last Modified: {src_file.stat().st_mtime}")
# Ensure destination folder exists
dst_folder.mkdir(parents=True, exist_ok=True)
# Copy file and folder
shutil.copy(src_file, dst_folder) # Copy file to destination folder
shutil.copytree(src_folder, dst_folder / "copied_source_folder",
dirs_exist_ok=True) # Copy folder
print("\nStep 1: File and folder copied successfully.")
Output
Source Folder Information:
Path: source_folder
Is it a directory? Yes
Files in Source Folder: ['sample_file.txt']
Source File Information:
Path: source_folder\sample_file.txt
Size: 22 bytes
Last Modified: 1732015300.9169207
Step 1: File and folder copied successfully.
#Rename
from pathlib import Path
# Define paths for renaming
dst_folder = Path("destination_folder")
copied_file = dst_folder / "sample_file.txt"
renamed_file = dst_folder / "renamed_sample_file.txt"
# Rename file
copied_file.rename(renamed_file)
print("Step 2: File renamed successfully.")
Output
Step 2: File renamed successfully.
#Move File
import shutil
from pathlib import Path
# Define paths for moving
dst_folder = Path("destination_folder")
move_folder = Path("move_destination_folder") # New folder for moving the
file
renamed_file = dst_folder / "renamed_sample_file.txt"
# Create new folder for moving if it doesn't exist
move_folder.mkdir(parents=True, exist_ok=True)
# Move file
shutil.move(str(renamed_file), move_folder / renamed_file.name)
print("Step 3: File moved to the new folder successfully.")
Output
Step 3: File moved to the new folder successfully.
#Remove File
from pathlib import Path
# Define paths for removal
move_folder = Path("move_destination_folder")
file_to_remove = move_folder / "renamed_sample_file.txt"
# Remove file
file_to_remove.unlink() # Delete the file
print("Step 4: File removed successfully.")
Output
Step 4: File removed successfully.
6) Implement a program based on using DBM - Creating and Accessing
Persistent Dictionaries.
import dbm
# Function to create and add key-value pairs to a DBM database
def create_dbm(db_name):
with dbm.open(db_name, 'c') as db:
# Adding key-value pairs
db['name'] = 'Alice'
db['age'] = '30'
db['city'] = 'New York'
print("Database created and entries added.")
# Function to read and access values from a DBM database
def access_dbm(db_name):
with dbm.open(db_name, 'r') as db:
# Access and display all key-value pairs
print("Contents of the DBM database:")
for key in db.keys():
print(f"{key.decode()}: {db[key].decode()}")
# Access specific values
print("\nAccessing specific values:")
name = db.get('name'.encode()).decode()
print(f"Name: {name}")
# Function to update a value in the DBM database
def update_dbm(db_name, key, value):
with dbm.open(db_name, 'w') as db:
db[key] = value
print(f"Updated {key.decode()} to {value.decode()}")
# Function to delete an entry in the DBM database
def delete_entry_dbm(db_name, key):
with dbm.open(db_name, 'w') as db:
del db[key]
print(f"Deleted entry with key: {key.decode()}")
# Main program
db_name = "sample_db"
create_dbm(db_name) # Create and populate DBM
access_dbm(db_name) # Access and display contents
# Update a value
update_dbm(db_name, b'city', b'Los Angeles')
access_dbm(db_name) # Verify update
# Delete an entry
delete_entry_dbm(db_name, b'age')
access_dbm(db_name) # Verify deletion
Output
Database created and entries added.
Contents of the DBM database:
name: Alice
city: New York
age: 30
Accessing specific values:
Name: Alice
Updated city to Los Angeles
Contents of the DBM database:
name: Alice
city: Los Angeles
age: 30
Accessing specific values:
Name: Alice
Deleted entry with key: age
Contents of the DBM database:
name: Alice
city: Los Angeles
Accessing specific values:
Name: Alice
7) Implement a program based on using Relational Database - Writing
SQL Statements, Defining Tables, Setting Up a Database.(
Transactions and Committing the Results.)
import sqlite3
# Step 1: Connect to SQLite database (or create one if it doesn't exist)
connection = sqlite3.connect("bca_students.db")
cursor = connection.cursor()
# Step 2: Define tables
def create_tables():
cursor.execute("""
CREATE TABLE IF NOT EXISTS Students (
student_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
department TEXT
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS Subjects (
subject_id INTEGER PRIMARY KEY,
subject_name TEXT NOT NULL,
credits INTEGER
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS Registrations (
registration_id INTEGER PRIMARY KEY AUTOINCREMENT,
student_id INTEGER,
subject_id INTEGER,
registration_date TEXT,
FOREIGN KEY(student_id) REFERENCES Students(student_id),
FOREIGN KEY(subject_id) REFERENCES Subjects(subject_id)
)
""")
print("Tables created successfully.")
# Step 3: Insert data
def insert_data():
try:
# Insert into Students table
cursor.execute("INSERT INTO Students (student_id, name, age,
department) VALUES (?, ?, ?, ?)",
(1, "John Doe", 20, "Computer Applications"))
cursor.execute("INSERT INTO Students (student_id, name, age,
department) VALUES (?, ?, ?, ?)",
(2, "Jane Smith", 21, "Computer Applications"))
# Insert into Subjects table
cursor.execute("INSERT INTO Subjects (subject_id, subject_name,
credits) VALUES (?, ?, ?)",
(101, "Database Management Systems", 4))
cursor.execute("INSERT INTO Subjects (subject_id, subject_name,
credits) VALUES (?, ?, ?)",
(102, "Operating Systems", 3))
# Insert into Registrations table
cursor.execute("INSERT INTO Registrations (student_id, subject_id,
registration_date) VALUES (?, ?, ?)",
(1, 101, "2024-11-21"))
cursor.execute("INSERT INTO Registrations (student_id, subject_id,
registration_date) VALUES (?, ?, ?)",
(2, 102, "2024-11-21"))
# Commit transaction
connection.commit()
print("Data inserted successfully and committed.")
except Exception as e:
# Rollback transaction in case of error
connection.rollback()
print("Error occurred during insertion:", e)
# Step 4: Display data
def display_data():
print("\nStudents Table:")
cursor.execute("SELECT * FROM Students")
for row in cursor.fetchall():
print(row)
print("\nSubjects Table:")
cursor.execute("SELECT * FROM Subjects")
for row in cursor.fetchall():
print(row)
print("\nRegistrations Table:")
cursor.execute("""
SELECT r.registration_id, s.name AS student_name, sub.subject_name,
r.registration_date
FROM Registrations r
JOIN Students s ON r.student_id = s.student_id
JOIN Subjects sub ON r.subject_id = sub.subject_id
""")
for row in cursor.fetchall():
print(row)
# Main Execution
create_tables()
insert_data()
display_data()
# Close the database connection
connection.close()
Output
Tables created successfully.
Error occurred during insertion: UNIQUE constraint failed: Students.student_id
Students Table:
(1, 'John Doe', 20, 'Computer Applications')
(2, 'Jane Smith', 21, 'Computer Applications')
Subjects Table:
(101, 'Database Management Systems', 4)
(102, 'Operating Systems', 3)
Registrations Table:
(1, 'John Doe', 'Database Management Systems', '2024-11-21')
(2, 'Jane Smith', 'Operating Systems', '2024-11-21')