pip install flask
Solve Problems by Coding Solutions - A Complete solution for python programming
Online Python Compiler 💻
Flashcard App for Learning
import tkinter as tk
import json
import random
# File to store flashcards
FLASHCARDS_FILE = "flashcards.json"
class FlashcardApp:
def __init__(self, root):
self.root = root
self.root.title("Flashcard App")
self.root.geometry("400x300")
self.flashcards = self.load_flashcards()
self.current_flashcard = {}
# UI Elements
self.label = tk.Label(root, text="Press 'Next' to start!", font=("Arial", 14), wraplength=350)
self.label.pack(pady=20)
self.flip_button = tk.Button(root, text="Flip", command=self.flip_card)
self.flip_button.pack()
self.next_button = tk.Button(root, text="Next", command=self.next_card)
self.next_button.pack()
self.add_button = tk.Button(root, text="Add Flashcard", command=self.add_flashcard)
self.add_button.pack()
def load_flashcards(self):
try:
with open(FLASHCARDS_FILE, "r") as file:
return json.load(file)
except FileNotFoundError:
return []
def save_flashcards(self):
with open(FLASHCARDS_FILE, "w") as file:
json.dump(self.flashcards, file)
def next_card(self):
if not self.flashcards:
self.label.config(text="No flashcards available. Add some!")
else:
self.current_flashcard = random.choice(self.flashcards)
self.label.config(text=f"Q: {self.current_flashcard['question']}")
def flip_card(self):
if self.current_flashcard:
self.label.config(text=f"A: {self.current_flashcard['answer']}")
def add_flashcard(self):
add_window = tk.Toplevel(self.root)
add_window.title("Add Flashcard")
add_window.geometry("300x200")
tk.Label(add_window, text="Question:").pack()
question_entry = tk.Entry(add_window, width=40)
question_entry.pack()
tk.Label(add_window, text="Answer:").pack()
answer_entry = tk.Entry(add_window, width=40)
answer_entry.pack()
def save_new_flashcard():
question = question_entry.get()
answer = answer_entry.get()
if question and answer:
self.flashcards.append({"question": question, "answer": answer})
self.save_flashcards()
add_window.destroy()
save_button = tk.Button(add_window, text="Save", command=save_new_flashcard)
save_button.pack()
# Run the app
root = tk.Tk()
app = FlashcardApp(root)
root.mainloop()
Quiz Game with Leaderboard 🎮
import tkinter as tk
from tkinter import messagebox
import random
import json
# Load questions from a JSON file or use a dictionary
questions = [
{"question": "What keyword is used to define a function in Python?",
"options": ["func", "define", "def", "function"],
"answer": "def"},
{"question": "Which of the following is used to create a loop in Python?",
"options": ["for", "while", "do-while", "Both A and B"],
"answer": "Both A and B"},
{"question": "What is the correct way to open a file in read mode?",
"options": ["open('file.txt', 'r')", "open('file.txt', 'w')", "open('file.txt', 'rw')", "open('file.txt')"],
"answer": "open('file.txt', 'r')"},
{"question": "Which data structure follows the Last In, First Out (LIFO) principle?",
"options": ["Queue", "Stack", "List", "Dictionary"],
"answer": "Stack"},
{"question": "Which method is used to add an element to a list?",
"options": ["append()", "insert()", "extend()", "add()"],
"answer": "append()"},
{"question": "Which library is commonly used for data analysis in Python?",
"options": ["NumPy", "Pandas", "Matplotlib", "Seaborn"],
"answer": "Pandas"},
{"question": "Which symbol is used to comment a single line in Python?",
"options": ["//", "#", "/*", "--"],
"answer": "#"},
{"question": "What will be the output of `len(['Python', 'Java', 'C++'])`?",
"options": ["2", "3", "4", "Error"],
"answer": "3"},
{"question": "What does the `range(5)` function return?",
"options": ["[1,2,3,4,5]", "[0,1,2,3,4]", "(0,1,2,3,4)", "None"],
"answer": "[0,1,2,3,4]"},
{"question": "Which of the following is a mutable data type in Python?",
"options": ["Tuple", "String", "List", "Integer"],
"answer": "List"}
]
# Load leaderboard from file
def load_leaderboard():
try:
with open("leaderboard.json", "r") as f:
return json.load(f)
except FileNotFoundError:
return {}
# Save leaderboard to file
def save_leaderboard(leaderboard):
with open("leaderboard.json", "w") as f:
json.dump(leaderboard, f, indent=4)
class QuizGame:
def __init__(self, root):
self.root = root
self.root.title("Quiz Game with Leaderboard")
self.root.geometry("500x400")
self.score = 0
self.current_question = 0
self.username = ""
self.start_screen()
def start_screen(self):
"""Start screen to enter player's name."""
self.clear_window()
tk.Label(self.root, text="Enter Your Name:", font=("Arial", 14)).pack(pady=10)
self.name_entry = tk.Entry(self.root, font=("Arial", 12))
self.name_entry.pack(pady=5)
tk.Button(self.root, text="Start Quiz", command=self.start_quiz, font=("Arial", 12)).pack(pady=20)
def start_quiz(self):
"""Start the quiz after getting the user's name."""
self.username = self.name_entry.get()
if not self.username:
messagebox.showerror("Error", "Please enter your name!")
return
random.shuffle(questions)
self.score = 0
self.current_question = 0
self.show_question()
def show_question(self):
"""Display a question and answer options."""
self.clear_window()
if self.current_question < len(questions):
q_data = questions[self.current_question]
self.correct_answer = q_data["answer"]
tk.Label(self.root, text=f"Q{self.current_question + 1}: {q_data['question']}", font=("Arial", 14), wraplength=400).pack(pady=10)
self.answer_var = tk.StringVar()
for option in q_data["options"]:
tk.Radiobutton(self.root, text=option, variable=self.answer_var, value=option, font=("Arial", 12)).pack(anchor="w", padx=20)
tk.Button(self.root, text="Submit", command=self.check_answer, font=("Arial", 12)).pack(pady=10)
else:
self.show_result()
def check_answer(self):
"""Check the selected answer."""
selected_answer = self.answer_var.get()
if not selected_answer:
messagebox.showerror("Error", "Please select an answer!")
return
if selected_answer == self.correct_answer:
self.score += 1
self.current_question += 1
self.show_question()
def show_result(self):
"""Display the final score and update leaderboard."""
self.clear_window()
leaderboard = load_leaderboard()
leaderboard[self.username] = self.score
save_leaderboard(leaderboard)
tk.Label(self.root, text=f"Quiz Over! {self.username}, your score: {self.score}/{len(questions)}", font=("Arial", 14)).pack(pady=10)
tk.Button(self.root, text="View Leaderboard", command=self.show_leaderboard, font=("Arial", 12)).pack(pady=10)
tk.Button(self.root, text="Play Again", command=self.start_screen, font=("Arial", 12)).pack(pady=5)
tk.Button(self.root, text="Exit", command=self.root.quit, font=("Arial", 12)).pack(pady=5)
def show_leaderboard(self):
"""Display the leaderboard."""
self.clear_window()
leaderboard = load_leaderboard()
sorted_leaderboard = sorted(leaderboard.items(), key=lambda x: x[1], reverse=True)
tk.Label(self.root, text="🏆 Leaderboard 🏆", font=("Arial", 16, "bold")).pack(pady=10)
for rank, (player, high_score) in enumerate(sorted_leaderboard, start=1):
tk.Label(self.root, text=f"{rank}. {player} - {high_score}", font=("Arial", 12)).pack()
tk.Button(self.root, text="Back to Menu", command=self.start_screen, font=("Arial", 12)).pack(pady=10)
def clear_window(self):
"""Clear the window for new content."""
for widget in self.root.winfo_children():
widget.destroy()
# Run the application
if __name__ == "__main__":
root = tk.Tk()
app = QuizGame(root)
root.mainloop()
Habit Tracker
import sqlite3
import tkinter as tk
from tkinter import messagebox
# Database Setup
conn = sqlite3.connect("habits.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS habits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
status TEXT DEFAULT 'Pending'
)
""")
conn.commit()
# Function to add a new habit
def add_habit():
habit_name = habit_entry.get().strip()
if habit_name:
cursor.execute("INSERT INTO habits (name, status) VALUES (?, 'Pending')", (habit_name,))
conn.commit()
habit_entry.delete(0, tk.END)
load_habits()
else:
messagebox.showwarning("Warning", "Please enter a habit name!")
# Function to mark a habit as completed
def complete_habit(habit_id):
cursor.execute("UPDATE habits SET status = 'Completed' WHERE id = ?", (habit_id,))
conn.commit()
load_habits()
# Function to delete a habit
def delete_habit(habit_id):
cursor.execute("DELETE FROM habits WHERE id = ?", (habit_id,))
conn.commit()
load_habits()
# Function to load habits from the database
def load_habits():
habit_list.delete(0, tk.END)
cursor.execute("SELECT id, name, status FROM habits")
for habit in cursor.fetchall():
habit_id, name, status = habit
habit_list.insert(tk.END, f"{habit_id}. {name} - {status}")
# GUI Setup
root = tk.Tk()
root.title("Habit Tracker")
root.geometry("400x500")
tk.Label(root, text="Enter a New Habit:", font=("Arial", 12)).pack(pady=5)
habit_entry = tk.Entry(root, width=40)
habit_entry.pack(pady=5)
tk.Button(root, text="Add Habit", command=add_habit).pack(pady=5)
tk.Label(root, text="Your Habits:", font=("Arial", 12)).pack(pady=5)
habit_list = tk.Listbox(root, width=50, height=10)
habit_list.pack()
tk.Button(root, text="Mark as Completed", command=lambda: complete_habit(habit_list.get(tk.ACTIVE).split('.')[0])).pack(pady=5)
tk.Button(root, text="Delete Habit", command=lambda: delete_habit(habit_list.get(tk.ACTIVE).split('.')[0])).pack(pady=5)
load_habits()
root.mainloop()
Secure Notes App
import os
import tkinter as tk
from tkinter import messagebox, simpledialog
from cryptography.fernet import Fernet
# Generate a key file if it doesn’t exist
KEY_FILE = "secret.key"
NOTES_FILE = "secure_notes.txt"
def generate_key():
key = Fernet.generate_key()
with open(KEY_FILE, "wb") as key_file:
key_file.write(key)
def load_key():
if not os.path.exists(KEY_FILE):
generate_key()
with open(KEY_FILE, "rb") as key_file:
return key_file.read()
# Load encryption key
key = load_key()
cipher_suite = Fernet(key)
def encrypt_message(message):
return cipher_suite.encrypt(message.encode()).decode()
def decrypt_message(encrypted_message):
return cipher_suite.decrypt(encrypted_message.encode()).decode()
def save_note():
note = note_text.get("1.0", tk.END).strip()
if not note:
messagebox.showwarning("Warning", "Note cannot be empty!")
return
encrypted_note = encrypt_message(note)
with open(NOTES_FILE, "a") as file:
file.write(encrypted_note + "\n")
messagebox.showinfo("Success", "Note saved securely!")
note_text.delete("1.0", tk.END)
def load_notes():
if not os.path.exists(NOTES_FILE):
messagebox.showinfo("No Notes", "No saved notes found.")
return
with open(NOTES_FILE, "r") as file:
encrypted_notes = file.readlines()
if not encrypted_notes:
messagebox.showinfo("No Notes", "No saved notes found.")
return
password = simpledialog.askstring("Password", "Enter decryption password:", show="*")
if password: # Dummy check
try:
decrypted_notes = [decrypt_message(note.strip()) for note in encrypted_notes]
messagebox.showinfo("Your Notes", "\n\n".join(decrypted_notes))
except Exception as e:
messagebox.showerror("Error", "Failed to decrypt notes.")
else:
messagebox.showwarning("Warning", "Password cannot be empty!")
# GUI Setup
root = tk.Tk()
root.title("Secure Notes App")
root.geometry("400x400")
tk.Label(root, text="Enter your note:", font=("Arial", 12)).pack(pady=5)
note_text = tk.Text(root, height=8, width=40)
note_text.pack()
save_btn = tk.Button(root, text="Save Note", command=save_note)
save_btn.pack(pady=5)
load_btn = tk.Button(root, text="Load Notes", command=load_notes)
load_btn.pack(pady=5)
root.mainloop()