Personal Finance Tracker

 import tkinter as tk

from tkinter import ttk, messagebox

import sqlite3

import matplotlib.pyplot as plt


# Database Setup

conn = sqlite3.connect("finance_tracker.db")

cursor = conn.cursor()

cursor.execute("""

    CREATE TABLE IF NOT EXISTS transactions (

        id INTEGER PRIMARY KEY AUTOINCREMENT,

        date TEXT,

        category TEXT,

        amount REAL,

        type TEXT

    )

""")

conn.commit()


class FinanceTracker:

    def __init__(self, root):

        self.root = root

        self.root.title("Personal Finance Tracker šŸ’°")

        self.root.geometry("600x500")


        # UI Components

        tk.Label(root, text="Date (YYYY-MM-DD):").grid(row=0, column=0, padx=10, pady=5, sticky="w")

        self.date_entry = tk.Entry(root, width=30)

        self.date_entry.grid(row=0, column=1, padx=10, pady=5)


        tk.Label(root, text="Category:").grid(row=1, column=0, padx=10, pady=5, sticky="w")

        self.category_entry = tk.Entry(root, width=30)

        self.category_entry.grid(row=1, column=1, padx=10, pady=5)


        tk.Label(root, text="Amount:").grid(row=2, column=0, padx=10, pady=5, sticky="w")

        self.amount_entry = tk.Entry(root, width=30)

        self.amount_entry.grid(row=2, column=1, padx=10, pady=5)


        tk.Label(root, text="Transaction Type:").grid(row=3, column=0, padx=10, pady=5, sticky="w")

        self.type_var = tk.StringVar(value="Expense")  

        self.type_dropdown = ttk.Combobox(root, textvariable=self.type_var, values=["Expense", "Income"], width=28)

        self.type_dropdown.grid(row=3, column=1, padx=10, pady=5)

        self.type_dropdown.current(0)


        # Buttons - Expanded Width

        tk.Button(root, text="Add Transaction", command=self.add_transaction, width=20).grid(row=4, column=0, columnspan=2, pady=10)

        tk.Button(root, text="Show Transactions", command=self.show_transactions, width=20).grid(row=5, column=0, columnspan=2, pady=5)

        tk.Button(root, text="View Report", command=self.view_report, width=20).grid(row=6, column=0, columnspan=2, pady=5)


        # Transaction List Display

        self.tree = ttk.Treeview(root, columns=("ID", "Date", "Category", "Amount", "Type"), show="headings")

        self.tree.heading("ID", text="ID")

        self.tree.heading("Date", text="Date")

        self.tree.heading("Category", text="Category")

        self.tree.heading("Amount", text="Amount")

        self.tree.heading("Type", text="Type")

        self.tree.column("ID", width=30)

        self.tree.column("Date", width=100)

        self.tree.column("Category", width=100)

        self.tree.column("Amount", width=80)

        self.tree.column("Type", width=80)

        self.tree.grid(row=7, column=0, columnspan=2, padx=10, pady=10)


    def add_transaction(self):

        date = self.date_entry.get()

        category = self.category_entry.get()

        amount = self.amount_entry.get()

        trans_type = self.type_var.get()


        if not date or not category or not amount or not trans_type:

            messagebox.showerror("Error", "All fields are required!")

            return

        

        try:

            amount = float(amount)

            cursor.execute("INSERT INTO transactions (date, category, amount, type) VALUES (?, ?, ?, ?)", 

                           (date, category, amount, trans_type))

            conn.commit()

            messagebox.showinfo("Success", "Transaction added successfully!")

            self.clear_entries()

        except ValueError:

            messagebox.showerror("Error", "Amount must be a number!")


    def show_transactions(self):

        for item in self.tree.get_children():

            self.tree.delete(item)


        cursor.execute("SELECT * FROM transactions")

        for row in cursor.fetchall():

            self.tree.insert("", "end", values=row)


    def view_report(self):

        cursor.execute("SELECT category, SUM(amount) FROM transactions WHERE type='Expense' GROUP BY category")

        data = cursor.fetchall()


        if not data:

            messagebox.showinfo("Report", "No expenses recorded.")

            return


        categories, amounts = zip(*data)

        plt.figure(figsize=(6, 6))

        plt.pie(amounts, labels=categories, autopct="%1.1f%%", startangle=140)

        plt.title("Expense Breakdown")

        plt.show()


    def clear_entries(self):

        self.date_entry.delete(0, tk.END)

        self.category_entry.delete(0, tk.END)

        self.amount_entry.delete(0, tk.END)

        self.type_var.set("Expense")


# Run the application

if __name__ == "__main__":

    root = tk.Tk()

    app = FinanceTracker(root)

    root.mainloop()

Real-Time Weather Dashboard

 Get an API Key from OpenWeather


import tkinter as tk

from tkinter import messagebox

import requests


# OpenWeather API Key (Replace with your own key)

API_KEY = "YOUR_OPENWEATHER_API_KEY"

BASE_URL = "http://api.openweathermap.org/data/2.5/weather"


# Function to fetch weather data

def get_weather():

    city = city_entry.get()

    if not city:

        messagebox.showerror("Error", "Please enter a city name!")

        return


    params = {"q": city, "appid": API_KEY, "units": "metric"}

    response = requests.get(BASE_URL, params=params)


    if response.status_code == 200:

        data = response.json()

        weather = data["weather"][0]["description"].capitalize()

        temp = data["main"]["temp"]

        humidity = data["main"]["humidity"]

        

        result_label.config(text=f"šŸŒ City: {city}\n🌔️ Temperature: {temp}°C\nšŸ’§ Humidity: {humidity}%\n☁️ Condition: {weather}")

    else:

        messagebox.showerror("Error", "City not found! Please try again.")


# GUI setup

root = tk.Tk()

root.title("Real-Time Weather Dashboard")

root.geometry("400x350")


tk.Label(root, text="Enter City Name:", font=("Arial", 14)).pack(pady=10)

city_entry = tk.Entry(root, font=("Arial", 12), width=25)

city_entry.pack(pady=5)


tk.Button(root, text="Get Weather", font=("Arial", 12), command=get_weather).pack(pady=10)


result_label = tk.Label(root, text="", font=("Arial", 14), justify="left")

result_label.pack(pady=20)


# Run GUI

root.mainloop()


Online Python Compiler šŸ’»

 pip install flask


app.py

from flask import Flask, render_template, request, jsonify
import subprocess

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/run", methods=["POST"])
def run_code():
    code = request.json.get("code", "")

    try:
        # Run the code in a restricted subprocess
        result = subprocess.run(
            ["python", "-c", code],
            capture_output=True,
            text=True,
            timeout=5
        )
        output = result.stdout if result.stdout else result.stderr
    except Exception as e:
        output = str(e)

    return jsonify({"output": output})

if __name__ == "__main__":
    app.run(debug=True)


templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Python Compiler</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; }
        #editor { width: 80%; height: 300px; margin: auto; border: 1px solid #ddd; }
        #output { white-space: pre-wrap; background: #f4f4f4; padding: 10px; margin-top: 10px; width: 80%; }
    </style>
</head>
<body>
    <h1>Online Python Compiler šŸ’»</h1>
    <div id="editor">print("Hello, World!")</div>
    <button onclick="runCode()">Run Code</button>
    <pre id="output">Output will appear here...</pre>

    <script>
        var editor = ace.edit("editor");
        editor.setTheme("ace/theme/monokai");
        editor.session.setMode("ace/mode/python");

        function runCode() {
            let code = editor.getValue();
            fetch("/run", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ code: code })
            })
            .then(response => response.json())
            .then(data => document.getElementById("output").innerText = data.output);
        }
    </script>
</body>
</html>


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()