Python Programs
Python Programs
Configuring Options
import tkinter as tk
from tkinter import ttk
# 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!")
# Entry Widget
entry_label = tk.Label(root, text="Enter your name:")
entry_label.pack()
# 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)
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()
# Resizing Widgets
resize_label = tk.Label(root, text="Resize the window and see widget
adjustments.")
resize_label.pack(pady=10)
# Close Button
close_button = tk.Button(root, text="Close", command=root.destroy, bg="red",
fg="white")
close_button.pack(pady=20)
import tkinter as tk
btn1.pack(side="left", padx=5)
btn2.pack(side="left", padx=5)
btn3.pack(side="left", padx=5)
Output
3) Implement a program based on Text Processing, Searching for Files
import os
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()
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
Searching for the word 'Python' in the text files within directory:
D:\Users\LENOVO\Desktop\MCA
def parse_html(html_content):
"""
Demonstrates HTML parsing by extracting the title, links, and text content.
"""
soup = BeautifulSoup(html_content, 'html.parser')
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>
"""
if __name__ == "__main__":
main()
Ouitput
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.
# 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
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}")
#Rename
from pathlib import Path
# Rename file
copied_file.rename(renamed_file)
Output
import shutil
from pathlib import Path
# Move file
shutil.move(str(renamed_file), move_folder / renamed_file.name)
Output
#Remove File
from pathlib import Path
Output
import dbm
# 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
import sqlite3
# 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)
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()
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')