close
Itxperts

Expense Tracker Application using Python

This project involves creating an Expense Tracker Application using Python, where users can log their daily expenses, view their spending patterns, and manage budgets. We will use Tkinter for the graphical user interface (GUI) and SQLite for storing expense records.

1. Project Setup

Modules Required:

  • tkinter: For the graphical user interface.
  • sqlite3: For database management.

Install the necessary modules using:

pip install tkinter

2. Project Features

  1. Add Expenses: Users can log details like category, amount, and description of each expense.
  2. View Expenses: View a list of all logged expenses, filtered by date or category.
  3. Edit/Delete Expenses: Modify or remove specific expense records.
  4. Track Monthly Budget: Set a monthly budget and track the total expenses against it.
  5. View Total Expenses: Display total expenses over a selected period (e.g., weekly, monthly).
  6. Expense Summary: Visualize spending in different categories.

3. Database Design

We’ll use SQLite to create a table named expenses with the following fields:

  • id (INTEGER PRIMARY KEY AUTOINCREMENT)
  • date (TEXT)
  • category (TEXT)
  • amount (REAL)
  • description (TEXT)

4. Code Structure

A. Database Connection

import sqlite3

def connect_db():
    conn = sqlite3.connect('expense_tracker.db')
    c = conn.cursor()
    # Create Expenses Table
    c.execute('''CREATE TABLE IF NOT EXISTS expenses
                 (id INTEGER PRIMARY KEY AUTOINCREMENT,
                  date TEXT,
                  category TEXT,
                  amount REAL,
                  description TEXT)''')
    conn.commit()
    conn.close()

connect_db()

B. Add Expense Function

def add_expense(date, category, amount, description):
    conn = sqlite3.connect('expense_tracker.db')
    c = conn.cursor()
    c.execute("INSERT INTO expenses (date, category, amount, description) VALUES (?, ?, ?, ?)",
              (date, category, amount, description))
    conn.commit()
    conn.close()

C. View Expenses Function

def view_expenses():
    conn = sqlite3.connect('expense_tracker.db')
    c = conn.cursor()
    c.execute("SELECT * FROM expenses ORDER BY date DESC")
    rows = c.fetchall()
    conn.close()
    return rows

D. Edit Expense Function

def edit_expense(id, date, category, amount, description):
    conn = sqlite3.connect('expense_tracker.db')
    c = conn.cursor()
    c.execute("UPDATE expenses SET date=?, category=?, amount=?, description=? WHERE id=?",
              (date, category, amount, description, id))
    conn.commit()
    conn.close()

E. Delete Expense Function

def delete_expense(id):
    conn = sqlite3.connect('expense_tracker.db')
    c = conn.cursor()
    c.execute("DELETE FROM expenses WHERE id=?", (id,))
    conn.commit()
    conn.close()

5. GUI Design using Tkinter

Here is the implementation of the Expense Tracker interface using Tkinter for adding and viewing expenses.

A. Adding Expense GUI

from tkinter import *
from tkinter import messagebox
import sqlite3

# Function to Add Expense
def add_expense_gui():
    date = entry_date.get()
    category = entry_category.get()
    amount = entry_amount.get()
    description = entry_description.get()

    if date and category and amount:
        add_expense(date, category, float(amount), description)
        messagebox.showinfo("Success", "Expense added successfully!")
    else:
        messagebox.showerror("Error", "Please fill in all fields!")

# Main window setup
root = Tk()
root.title("Expense Tracker")
root.geometry("400x300")

# GUI Elements for Adding Expense
Label(root, text="Date (YYYY-MM-DD)").pack(pady=10)
entry_date = Entry(root)
entry_date.pack()

Label(root, text="Category").pack(pady=10)
entry_category = Entry(root)
entry_category.pack()

Label(root, text="Amount").pack(pady=10)
entry_amount = Entry(root)
entry_amount.pack()

Label(root, text="Description").pack(pady=10)
entry_description = Entry(root)
entry_description.pack()

Button(root, text="Add Expense", command=add_expense_gui).pack(pady=20)

root.mainloop()

B. Viewing Expenses GUI

def view_expenses_gui():
    expenses_window = Toplevel(root)
    expenses_window.title("View Expenses")
    expenses_window.geometry("600x400")

    expenses = view_expenses()

    text_area = Text(expenses_window)
    text_area.pack()

    for expense in expenses:
        text_area.insert(END, f"Date: {expense[1]} | Category: {expense[2]} | Amount: {expense[3]} | Description: {expense[4]}\n")

You can add a button on the main window to open the View Expenses window:

Button(root, text="View Expenses", command=view_expenses_gui).pack(pady=10)

6. Budget Management and Total Expense Calculation

You can extend the application with the following features:

A. Set Monthly Budget

You can create a table budget to store the user’s monthly budget and track the total expenses against this budget. Here’s a simple way to add and track the budget.

def set_monthly_budget(amount):
    conn = sqlite3.connect('expense_tracker.db')
    c = conn.cursor()
    c.execute("CREATE TABLE IF NOT EXISTS budget (id INTEGER PRIMARY KEY, amount REAL)")
    c.execute("INSERT OR REPLACE INTO budget (id, amount) VALUES (1, ?)", (amount,))
    conn.commit()
    conn.close()

def get_monthly_budget():
    conn = sqlite3.connect('expense_tracker.db')
    c = conn.cursor()
    c.execute("SELECT amount FROM budget WHERE id=1")
    budget = c.fetchone()
    conn.close()
    return budget[0] if budget else 0

B. Calculate Total Expenses

You can calculate the total expenses for the current month or any specific period:

def get_total_expenses():
    conn = sqlite3.connect('expense_tracker.db')
    c = conn.cursor()
    c.execute("SELECT SUM(amount) FROM expenses")
    total = c.fetchone()[0]
    conn.close()
    return total

7. Final Enhancements

To make the Expense Tracker more feature-rich, you can add the following improvements:

  1. Filter Expenses by Date or Category: Allow users to filter their expenses by date range or specific categories.
  2. Generate Reports: Create a feature to generate monthly or weekly expense reports.
  3. Expense Summary Visualization: Use matplotlib to create graphs showing spending trends and category-wise expenses.
  4. Login System: Add user accounts with authentication so that multiple users can manage their expenses on the same application.
  5. Improved UI: Enhance the user interface with better layouts, color schemes, and fonts for a more engaging experience.

8. Conclusion

This is a basic Expense Tracker Application using Python and Tkinter for the graphical user interface and SQLite for managing expenses. It allows users to add, view, edit, and delete their daily expenses, with the possibility of setting and tracking monthly budgets.

Would you like to explore any additional features or functionalities for this project?