Solve Problems by Coding Solutions - A Complete solution for python programming
Book Tracker
import sqlite3
from tkinter import Tk, Label, Entry, Button, ttk, messagebox
# Database setup
def setup_database():
conn = sqlite3.connect('books.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
author TEXT NOT NULL,
status TEXT NOT NULL
)
""")
conn.commit()
conn.close()
# Add book
def add_book(title, author, status):
if not title or not author or not status:
messagebox.showerror("Error", "All fields are required.")
return
conn = sqlite3.connect('books.db')
cursor = conn.cursor()
cursor.execute("INSERT INTO books (title, author, status) VALUES (?, ?, ?)", (title, author, status))
conn.commit()
conn.close()
messagebox.showinfo("Success", "Book added successfully!")
refresh_list()
# Get books
def get_books():
conn = sqlite3.connect('books.db')
cursor = conn.cursor()
cursor.execute("SELECT id, title, author, status FROM books")
books = cursor.fetchall()
conn.close()
return books
# Update book status
def update_status(book_id, new_status):
conn = sqlite3.connect('books.db')
cursor = conn.cursor()
cursor.execute("UPDATE books SET status = ? WHERE id = ?", (new_status, book_id))
conn.commit()
conn.close()
messagebox.showinfo("Success", "Book status updated successfully!")
refresh_list()
# Delete book
def delete_book(book_id):
conn = sqlite3.connect('books.db')
cursor = conn.cursor()
cursor.execute("DELETE FROM books WHERE id = ?", (book_id,))
conn.commit()
conn.close()
messagebox.showinfo("Success", "Book deleted successfully!")
refresh_list()
# Refresh the book list in the GUI
def refresh_list():
for row in tree.get_children():
tree.delete(row)
books = get_books()
for book in books:
tree.insert("", "end", values=book)
# GUI setup
def setup_gui():
global tree
root = Tk()
root.title("Book Tracker")
# Labels and input fields
Label(root, text="Title:").grid(row=0, column=0, padx=5, pady=5)
title_entry = Entry(root)
title_entry.grid(row=0, column=1, padx=5, pady=5)
Label(root, text="Author:").grid(row=1, column=0, padx=5, pady=5)
author_entry = Entry(root)
author_entry.grid(row=1, column=1, padx=5, pady=5)
Label(root, text="Status:").grid(row=2, column=0, padx=5, pady=5)
status_combobox = ttk.Combobox(root, values=["To Read", "Reading", "Finished"])
status_combobox.grid(row=2, column=1, padx=5, pady=5)
# Buttons
Button(root, text="Add Book", command=lambda: add_book(title_entry.get(), author_entry.get(), status_combobox.get())).grid(row=3, column=0, columnspan=2, pady=10)
# Book list
columns = ("ID", "Title", "Author", "Status")
tree = ttk.Treeview(root, columns=columns, show="headings")
for col in columns:
tree.heading(col, text=col)
tree.column(col, width=150)
tree.grid(row=4, column=0, columnspan=2, padx=5, pady=5)
# Actions
Button(root, text="Update Status", command=lambda: update_status(tree.item(tree.focus())['values'][0], status_combobox.get())).grid(row=5, column=0, pady=10)
Button(root, text="Delete Book", command=lambda: delete_book(tree.item(tree.focus())['values'][0])).grid(row=5, column=1, pady=10)
refresh_list()
root.mainloop()
if __name__ == "__main__":
setup_database()
setup_gui()
Python is TIOBE's programming language of the year 2024!
Pomodoro Timer
import tkinter as tk
from tkinter import messagebox
import time
# Constants
WORK_MIN = 25 # Work duration in minutes
SHORT_BREAK_MIN = 5 # Short break duration in minutes
LONG_BREAK_MIN = 15 # Long break duration in minutes
CYCLES = 4 # Number of work sessions before a long break
class PomodoroTimer:
def __init__(self):
self.root = tk.Tk()
self.root.title("Pomodoro Timer")
self.timer_running = False
self.current_cycle = 0
self.time_left = 0
# UI Setup
self.label = tk.Label(self.root, text="Pomodoro Timer", font=("Arial", 20))
self.label.pack(pady=10)
self.time_label = tk.Label(self.root, text="00:00", font=("Arial", 40))
self.time_label.pack(pady=10)
self.start_button = tk.Button(self.root, text="Start", font=("Arial", 15), command=self.start_timer)
self.start_button.pack(side="left", padx=10)
self.reset_button = tk.Button(self.root, text="Reset", font=("Arial", 15), command=self.reset_timer)
self.reset_button.pack(side="right", padx=10)
def start_timer(self):
if not self.timer_running:
self.current_cycle += 1
if self.current_cycle % (CYCLES + 1) == 0:
self.time_left = LONG_BREAK_MIN * 60
self.label.config(text="Long Break", fg="blue")
elif self.current_cycle % 2 == 0:
self.time_left = SHORT_BREAK_MIN * 60
self.label.config(text="Short Break", fg="green")
else:
self.time_left = WORK_MIN * 60
self.label.config(text="Work", fg="red")
self.timer_running = True
self.countdown()
def countdown(self):
if self.time_left > 0:
mins, secs = divmod(self.time_left, 60)
self.time_label.config(text=f"{mins:02}:{secs:02}")
self.time_left -= 1
self.root.after(1000, self.countdown)
else:
self.timer_running = False
self.time_label.config(text="00:00")
if self.current_cycle % 2 != 0:
messagebox.showinfo("Time's up!", "Time for a break!")
else:
messagebox.showinfo("Time's up!", "Time to work!")
def reset_timer(self):
self.timer_running = False
self.current_cycle = 0
self.time_left = 0
self.label.config(text="Pomodoro Timer", fg="black")
self.time_label.config(text="00:00")
def run(self):
self.root.mainloop()
# Run the Pomodoro Timer
if __name__ == "__main__":
PomodoroTimer().run()
News Aggregator
your_newsapi_key in the code with your actual API key.
import requests
API_KEY = "your_newsapi_key" # Replace with your NewsAPI key
BASE_URL = "https://newsapi.org/v2/"
def fetch_top_headlines(country="us", category="general", page_size=5):
"""
Fetch top news headlines from NewsAPI.
Args:
country (str): Country code for news (default is 'us').
category (str): Category of news (default is 'general').
page_size (int): Number of headlines to fetch (default is 5).
Returns:
list: A list of dictionaries containing news headlines and details.
"""
url = f"{BASE_URL}top-headlines"
params = {
"apiKey": API_KEY,
"country": country,
"category": category,
"pageSize": page_size,
}
try:
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data.get("articles", [])
except requests.exceptions.RequestException as e:
print(f"Error fetching news: {e}")
return []
def display_headlines(articles):
"""
Display news headlines in a user-friendly format.
Args:
articles (list): List of news articles.
"""
if not articles:
print("No news articles found.")
return
print("\n--- Latest News Headlines ---")
for idx, article in enumerate(articles, 1):
print(f"\n{idx}. {article['title']}")
print(f" Source: {article['source']['name']}")
print(f" URL: {article['url']}")
def main():
print("Welcome to the News Aggregator!")
country = input("Enter the country code for news (e.g., 'us' for USA, 'in' for India): ").strip()
category = input("Enter the category of news (e.g., 'business', 'entertainment', 'sports'): ").strip()
num_articles = input("How many articles would you like to fetch? (default is 5): ").strip()
# Default values if input is empty
country = country if country else "us"
category = category if category else "general"
num_articles = int(num_articles) if num_articles.isdigit() else 5
print("\nFetching top headlines...")
articles = fetch_top_headlines(country=country, category=category, page_size=num_articles)
display_headlines(articles)
if __name__ == "__main__":
main()