Personal Budget Tracker with Tkinter and SQLite in Python

Build a Personal Budget Tracker with Tkinter and SQLite in Python

A personal budget tracker helps you manage and monitor your finances. In this tutorial, we will create a simple budget tracker app using Python, Tkinter, and SQLite. We’ll also add features like categorizing transactions, visualizing spending, and setting a custom window icon for a more polished look.

Prerequisites

Before we begin, make sure you have Python installed on your system. You’ll also need the following libraries:

  • Matplotlib: For visualizing spending in the form of pie charts.
  • Tkinter: For the graphical user interface (GUI).
  • SQLite: For storing transaction data in a local database.

To install Matplotlib, run:

pip install matplotlib

Step 1: Set Up the Database

First, we need to set up an SQLite database to store the transactions. The database will include a table where we will store the transaction details like date, category, description, amount, and type (income or expense).

Here’s the code to create the database and table:

import sqlite3
from datetime import datetime
def initialize_database():
    conn = sqlite3.connect('budget_tracker.db')
    cursor = conn.cursor()
    
    # Create a table for transactions
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS transactions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            date TEXT,
            category TEXT,
            description TEXT,
            amount REAL,
            type TEXT
        )
    ''')
    conn.commit()
    conn.close()
initialize_database()

Step 2: Create the Add Transaction Form – Personal Budget Tracker

We need a form where users can input transaction details such as category, description, amount, and type (income or expense). We will build this form using Tkinter’s widgets like Entry, Label, and Button.

Here is the code for the form and how it will add transactions to the database:

import tkinter as tk
from tkinter import ttk, messagebox

def add_transaction_gui():
    def submit():
        category = category_entry.get()
        description = description_entry.get()
        amount = float(amount_entry.get())
        trans_type = trans_type_var.get()

        if not category or not description or not amount or not trans_type:
            messagebox.showerror("Error", "All fields are required.")
            return

        add_transaction(category, description, amount, trans_type)
        messagebox.showinfo("Success", f"{trans_type.capitalize()} added successfully!")
        window.destroy()

    window = tk.Toplevel()
    window.title("Add Transaction")
    window.geometry("400x300")

    tk.Label(window, text="Category").grid(row=0, column=0, padx=10, pady=10)
    category_entry = tk.Entry(window)
    category_entry.grid(row=0, column=1, padx=10, pady=10)

    tk.Label(window, text="Description").grid(row=1, column=0, padx=10, pady=10)
    description_entry = tk.Entry(window)
    description_entry.grid(row=1, column=1, padx=10, pady=10)

    tk.Label(window, text="Amount").grid(row=2, column=0, padx=10, pady=10)
    amount_entry = tk.Entry(window)
    amount_entry.grid(row=2, column=1, padx=10, pady=10)

    tk.Label(window, text="Type").grid(row=3, column=0, padx=10, pady=10)
    trans_type_var = tk.StringVar(value="income")
    trans_type_menu = ttk.Combobox(window, textvariable=trans_type_var, values=["income", "expense"])
    trans_type_menu.grid(row=3, column=1, padx=10, pady=10)

    submit_btn = tk.Button(window, text="Submit", command=submit)
    submit_btn.grid(row=4, column=0, columnspan=2, pady=20)

Step 3: View Transactions

To track our spending, we need to view all transactions in a list. Tkinter’s Treeview widget is perfect for this purpose. It allows us to display transaction details in a structured, scrollable table.

Here’s how you can display transactions from the database:

def view_transactions():
    conn = sqlite3.connect('budget_tracker.db')
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM transactions')
    transactions = cursor.fetchall()
    conn.close()

    window = tk.Toplevel()
    window.title("Transaction History")
    window.geometry("600x400")

    tree = ttk.Treeview(window, columns=("Date", "Category", "Description", "Amount", "Type"), show="headings")
    tree.heading("Date", text="Date")
    tree.heading("Category", text="Category")
    tree.heading("Description", text="Description")
    tree.heading("Amount", text="Amount")
    tree.heading("Type", text="Type")

    for trans in transactions:
        tree.insert("", tk.END, values=trans[1:])
    
    tree.pack(fill=tk.BOTH, expand=True)

Step 4: Visualize Spending

To help users understand their spending habits, we can visualize their expenses by category using a pie chart. Matplotlib will be used to generate the pie chart, which will show a breakdown of spending across different categories.

import matplotlib.pyplot as plt

def visualize_spending_by_category():
    conn = sqlite3.connect('budget_tracker.db')
    cursor = conn.cursor()
    cursor.execute('''
        SELECT category, SUM(amount) FROM transactions
        WHERE type = 'expense'
        GROUP BY category
    ''')
    spending = cursor.fetchall()
    conn.close()

    if not spending:
        messagebox.showinfo("Info", "No expenses to display.")
        return

    categories = [row[0] for row in spending]
    amounts = [row[1] for row in spending]

    plt.figure(figsize=(8, 6))
    plt.pie(amounts, labels=categories, autopct='%1.1f%%', startangle=140)
    plt.title("Spending by Category")
    plt.show()

Step 5: Customize the Window Icon (Favicon)

To give your app a more professional look, you can set a custom window icon (favicon). Tkinter allows us to easily set a .ico file as the window icon.

Here’s how you can change the default icon:

def main_gui():
    root = tk.Tk()
    root.title("Personal Budget Tracker")
    root.geometry("400x300")

    # Set the window icon (Favicon)
    root.iconbitmap('favicon.ico')  # Provide the path to your icon file

    tk.Label(root, text="Personal Budget Tracker", font=("Helvetica", 16)).pack(pady=20)

    tk.Button(root, text="Add Transaction", width=20, command=add_transaction_gui).pack(pady=10)
    tk.Button(root, text="View Transactions", width=20, command=view_transactions).pack(pady=10)
    tk.Button(root, text="Visualize Spending", width=20, command=visualize_spending_by_category).pack(pady=10)
    tk.Button(root, text="Exit", width=20, command=root.quit).pack(pady=10)

    root.mainloop()

Tip: You can convert any PNG or JPEG image into an .ico file using online converters.

Step 6: Putting Everything Together

Now, let’s integrate everything into one cohesive app. The following is the complete code for the Personal Budget Tracker.

import sqlite3
import tkinter as tk
from tkinter import ttk, messagebox
from datetime import datetime
import matplotlib.pyplot as plt

# Code for database setup, adding transactions, viewing transactions, and visualizing spending
# (Refer to the code sections above)

if __name__ == "__main__":
    main_gui()

Step 7: Running Personal Budget Tracker Application

Once you’ve written the code, save it as budget_tracker.py. To run the app, simply execute the script in your terminal:

python budget_tracker.py

You should now see the Personal Budget Tracker GUI with a custom window icon. You can add income and expense transactions, view them, and visualize your spending by category.

Step 8: Application Screenshot

Execute Application – Personal Budget Tracker

Personal Budget Tracker using Python
Personal Budget Tracker using Python

Insert a Sample Income

Add Sample Income - Personal Budget Tracker using Python
Add Sample Income

Now Insert a Sample Expenses

Add Sample Expenses
Add Sample Expenses

View Transactions History

View Transactions History
View Transactions History

Visualize Spending using Tkinter App – Matplotlib

Visualize Spending - Personal Budget Tracker using Python
Visualize Spending

GitHub Repository Link: https://github.com/data-coach/personal-budget-tracker-python.git

About Author: Connect with Me on LinkedIn

Conclusion – Personal Budget Tracker using Python

This simple Python app demonstrates how to build a personal budget tracker with Tkinter for the GUI and SQLite for data storage. You also learned how to visualize your expenses using Matplotlib and customize your app with a custom icon.

To dive deeper into building a sentiment analysis model using Transformers (BERT) and deploying it as an API, check out this detailed guide: How to Build a Sentiment Analysis API with Transformers in 2024.

Learn how to build a personal budget tracker using Python, Tkinter, and SQLite in this step-by-step guide. We cover how to create a user-friendly interface, store transactions in a database, visualize spending with charts, and even set a custom window icon for a polished look.