import mysql.
connector
try:
connection = [Link](
host="localhost",
user="root",
password="1234",
database="ansh"
)
if connection.is_connected():
print("Connected to MySQL Server successfully")
[Link]()
except [Link] as err:
print(f"Error: {err}")
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
from datetime import datetime
from collections import defaultdict
class FinanceManager:
def __init__(self, root):
[Link] = root
[Link]("Personal Finance Manager")
[Link]("800x600")
# Data structures
[Link] = {
'income': [],
'expenses': [],
'investments': [],
'loans': [],
'properties': [],
'taxes': [],
'categories': {
'income': ['Salary', 'Investments', 'Others'],
'expenses': ['Food', 'Entertainment', 'Bills', 'Others'],
'investments': ['Stocks', 'Bonds', 'Real Estate', 'Others'],
'loans': ['Mortgage', 'Car Loan', 'Personal Loan', 'Others'],
'properties': ['Residential', 'Commercial', 'Land', 'Others']
},
'budgets': defaultdict(float)
}
# Setup GUI components
self.setup_gui()
def setup_gui(self):
# Notebook for different sections
[Link] = [Link]([Link])
[Link](expand=True, fill='both')
# Frames for each section
self.income_frame = [Link]([Link])
self.expenses_frame = [Link]([Link])
self.investments_frame = [Link]([Link])
self.loans_frame = [Link]([Link])
self.properties_frame = [Link]([Link])
self.taxes_frame = [Link]([Link])
self.report_frame = [Link]([Link])
self.budget_frame = [Link]([Link])
[Link](self.income_frame, text="Income")
[Link](self.expenses_frame, text="Expenses")
[Link](self.investments_frame, text="Investments")
[Link](self.loans_frame, text="Loans")
[Link](self.properties_frame, text="Properties")
[Link](self.taxes_frame, text="Taxes")
[Link](self.report_frame, text="Reports")
[Link](self.budget_frame, text="Budgets")
# Income section
self.setup_income_section()
# Expenses section
self.setup_expenses_section()
# Investments section
self.setup_investments_section()
# Loans section
self.setup_loans_section()
# Properties section
self.setup_properties_section()
# Taxes section
self.setup_taxes_section()
# Report section
self.setup_report_section()
# Budget section
self.setup_budget_section()
# Menu
self.setup_menu()
def setup_income_section(self):
[Link](self.income_frame, text="Income Entry", font=("Arial", 16)).pack(pady=10)
form_frame = [Link](self.income_frame)
form_frame.pack(pady=20)
[Link](form_frame, text="Description").grid(row=0, column=0, padx=5, pady=5)
self.income_description = [Link](form_frame, width=40)
self.income_description.grid(row=0, column=1, padx=5, pady=5)
[Link](form_frame, text="Amount").grid(row=1, column=0, padx=5, pady=5)
self.income_amount = [Link](form_frame, width=40)
self.income_amount.grid(row=1, column=1, padx=5, pady=5)
[Link](form_frame, text="Category").grid(row=2, column=0, padx=5, pady=5)
self.income_category = [Link](form_frame, values=[Link]['categories']['income'])
self.income_category.grid(row=2, column=1, padx=5, pady=5)
self.income_category.current(0) # Set default value
[Link](form_frame, text="Add Income", command=self.add_income).grid(row=3, column=0, columnspan=2, pady=10)
self.income_list = [Link](self.income_frame, columns=("Description", "Amount", "Category", "Date"),
show='headings')
self.income_list.heading("Description", text="Description")
self.income_list.heading("Amount", text="Amount")
self.income_list.heading("Category", text="Category")
self.income_list.heading("Date", text="Date")
self.income_list.pack(pady=20, padx=20, fill='both', expand=True)
def setup_expenses_section(self):
[Link](self.expenses_frame, text="Expenses Entry", font=("Arial", 16)).pack(pady=10)
form_frame = [Link](self.expenses_frame)
form_frame.pack(pady=20)
[Link](form_frame, text="Description").grid(row=0, column=0, padx=5, pady=5)
self.expenses_description = [Link](form_frame, width=40)
self.expenses_description.grid(row=0, column=1, padx=5, pady=5)
[Link](form_frame, text="Amount").grid(row=1, column=0, padx=5, pady=5)
self.expenses_amount = [Link](form_frame, width=40)
self.expenses_amount.grid(row=1, column=1, padx=5, pady=5)
[Link](form_frame, text="Category").grid(row=2, column=0, padx=5, pady=5)
self.expenses_category = [Link](form_frame, values=[Link]['categories']['expenses'])
self.expenses_category.grid(row=2, column=1, padx=5, pady=5)
self.expenses_category.current(0) # Set default value
[Link](form_frame, text="Add Expense", command=self.add_expense).grid(row=3, column=0, columnspan=2,
pady=10)
self.expenses_list = [Link](self.expenses_frame, columns=("Description", "Amount", "Category", "Date"),
show='headings')
self.expenses_list.heading("Description", text="Description")
self.expenses_list.heading("Amount", text="Amount")
self.expenses_list.heading("Category", text="Category")
self.expenses_list.heading("Date", text="Date")
self.expenses_list.pack(pady=20, padx=20, fill='both', expand=True)
def setup_investments_section(self):
[Link](self.investments_frame, text="Investment Entry", font=("Arial", 16)).pack(pady=10)
form_frame = [Link](self.investments_frame)
form_frame.pack(pady=20)
[Link](form_frame, text="Description").grid(row=0, column=0, padx=5, pady=5)
self.investment_description = [Link](form_frame, width=40)
self.investment_description.grid(row=0, column=1, padx=5, pady=5)
[Link](form_frame, text="Amount").grid(row=1, column=0, padx=5, pady=5)
self.investment_amount = [Link](form_frame, width=40)
self.investment_amount.grid(row=1, column=1, padx=5, pady=5)
[Link](form_frame, text="Category").grid(row=2, column=0, padx=5, pady=5)
self.investment_category = [Link](form_frame, values=[Link]['categories']['investments'])
self.investment_category.grid(row=2, column=1, padx=5, pady=5)
self.investment_category.current(0) # Set default value
[Link](form_frame, text="Add Investment", command=self.add_investment).grid(row=3, column=0, columnspan=2,
pady=10)
self.investment_list = [Link](self.investments_frame,
columns=("Description", "Amount", "Category", "Date"), show='headings')
self.investment_list.heading("Description", text="Description")
self.investment_list.heading("Amount", text="Amount")
self.investment_list.heading("Category", text="Category")
self.investment_list.heading("Date", text="Date")
self.investment_list.pack(pady=20, padx=20, fill='both', expand=True)
def setup_loans_section(self):
[Link](self.loans_frame, text="Loan Entry", font=("Arial", 16)).pack(pady=10)
form_frame = [Link](self.loans_frame)
form_frame.pack(pady=20)
[Link](form_frame, text="Description").grid(row=0, column=0, padx=5, pady=5)
self.loan_description = [Link](form_frame, width=40)
self.loan_description.grid(row=0, column=1, padx=5, pady=5)
[Link](form_frame, text="Amount").grid(row=1, column=0, padx=5, pady=5)
self.loan_amount = [Link](form_frame, width=40)
self.loan_amount.grid(row=1, column=1, padx=5, pady=5)
[Link](form_frame, text="Category").grid(row=2, column=0, padx=5, pady=5)
self.loan_category = [Link](form_frame, values=[Link]['categories']['loans'])
self.loan_category.grid(row=2, column=1, padx=5, pady=5)
self.loan_category.current(0) # Set default value
[Link](form_frame, text="Add Loan", command=self.add_loan).grid(row=3, column=0, columnspan=2, pady=10)
self.loan_list = [Link](self.loans_frame, columns=("Description", "Amount", "Category", "Date"),
show='headings')
self.loan_list.heading("Description", text="Description")
self.loan_list.heading("Amount", text="Amount")
self.loan_list.heading("Category", text="Category")
self.loan_list.heading("Date", text="Date")
self.loan_list.pack(pady=20, padx=20, fill='both', expand=True)
def setup_properties_section(self):
[Link](self.properties_frame, text="Property Entry", font=("Arial", 16)).pack(pady=10)
form_frame = [Link](self.properties_frame)
form_frame.pack(pady=20)
[Link](form_frame, text="Description").grid(row=0, column=0, padx=5, pady=5)
self.property_description = [Link](form_frame, width=40)
self.property_description.grid(row=0, column=1, padx=5, pady=5)
[Link](form_frame, text="Value").grid(row=1, column=0, padx=5, pady=5)
self.property_value = [Link](form_frame, width=40)
self.property_value.grid(row=1, column=1, padx=5, pady=5)
[Link](form_frame, text="Category").grid(row=2, column=0, padx=5, pady=5)
self.property_category = [Link](form_frame, values=[Link]['categories']['properties'])
self.property_category.grid(row=2, column=1, padx=5, pady=5)
self.property_category.current(0) # Set default value
[Link](form_frame, text="Add Property", command=self.add_property).grid(row=3, column=0, columnspan=2,
pady=10)
self.property_list = [Link](self.properties_frame, columns=("Description", "Value", "Category", "Date"),
show='headings')
self.property_list.heading("Description", text="Description")
self.property_list.heading("Value", text="Value")
self.property_list.heading("Category", text="Category")
self.property_list.heading("Date", text="Date")
self.property_list.pack(pady=20, padx=20, fill='both', expand=True)
def setup_taxes_section(self):
[Link](self.taxes_frame, text="Tax Entry", font=("Arial", 16)).pack(pady=10)
form_frame = [Link](self.taxes_frame)
form_frame.pack(pady=20)
[Link](form_frame, text="Description").grid(row=0, column=0, padx=5, pady=5)
self.tax_description = [Link](form_frame, width=40)
self.tax_description.grid(row=0, column=1, padx=5, pady=5)
[Link](form_frame, text="Amount").grid(row=1, column=0, padx=5, pady=5)
self.tax_amount = [Link](form_frame, width=40)
self.tax_amount.grid(row=1, column=1, padx=5, pady=5)
[Link](form_frame, text="Category").grid(row=2, column=0, padx=5, pady=5)
self.tax_category = [Link](form_frame, values=[Link]['categories']['expenses'])
self.tax_category.grid(row=2, column=1, padx=5, pady=5)
self.tax_category.current(0) # Set default value
[Link](form_frame, text="Add Tax", command=self.add_tax).grid(row=3, column=0, columnspan=2, pady=10)
self.tax_list = [Link](self.taxes_frame, columns=("Description", "Amount", "Category", "Date"),
show='headings')
self.tax_list.heading("Description", text="Description")
self.tax_list.heading("Amount", text="Amount")
self.tax_list.heading("Category", text="Category")
self.tax_list.heading("Date", text="Date")
self.tax_list.pack(pady=20, padx=20, fill='both', expand=True)
def setup_report_section(self):
[Link](self.report_frame, text="Reports", font=("Arial", 16)).pack(pady=10)
self.report_text = [Link](self.report_frame, wrap='word', height=20, width=80)
self.report_text.pack(pady=20)
[Link](self.report_frame, text="Generate Report", command=self.generate_report).pack()
def setup_budget_section(self):
[Link](self.budget_frame, text="Budget Management", font=("Arial", 16)).pack(pady=10)
form_frame = [Link](self.budget_frame)
form_frame.pack(pady=20)
[Link](form_frame, text="Category").grid(row=0, column=0, padx=5, pady=5)
self.budget_category = [Link](form_frame, values=[Link]['categories']['expenses'])
self.budget_category.grid(row=0, column=1, padx=5, pady=5)
self.budget_category.current(0) # Set default value
[Link](form_frame, text="Budget Amount").grid(row=1, column=0, padx=5, pady=5)
self.budget_amount = [Link](form_frame, width=40)
self.budget_amount.grid(row=1, column=1, padx=5, pady=5)
[Link](form_frame, text="Set Budget", command=self.set_budget).grid(row=2, column=0, columnspan=2, pady=10)
[Link](form_frame, text="View Budgets", command=self.view_budgets).grid(row=3, column=0, columnspan=2,
pady=10)
def setup_menu(self):
menubar = [Link]([Link])
[Link](menu=menubar)
file_menu = [Link](menubar, tearoff=0)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Load Data", command=self.load_data)
file_menu.add_command(label="Save Data", command=self.save_data)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=[Link])
def add_income(self):
description = self.income_description.get()
amount = self.income_amount.get()
category = self.income_category.get()
if not description or not amount or not category:
[Link]("Error", "All fields must be filled.")
return
try:
amount = float(amount)
except ValueError:
[Link]("Error", "Amount must be a number.")
return
entry = {'description': description, 'amount': amount, 'category': category,
'date': [Link]().strftime("%Y-%m-%d %H:%M:%S")}
[Link]['income'].append(entry)
self.income_list.insert('', 'end', values=(description, f"{amount:.2f}", category, entry['date']))
self.income_description.delete(0, [Link])
self.income_amount.delete(0, [Link])
def add_expense(self):
description = self.expenses_description.get()
amount = self.expenses_amount.get()
category = self.expenses_category.get()
if not description or not amount or not category:
[Link]("Error", "All fields must be filled.")
return
try:
amount = float(amount)
except ValueError:
[Link]("Error", "Amount must be a number.")
return
entry = {'description': description, 'amount': amount, 'category': category,
'date': [Link]().strftime("%Y-%m-%d %H:%M:%S")}
[Link]['expenses'].append(entry)
self.expenses_list.insert('', 'end', values=(description, f"{amount:.2f}", category, entry['date']))
self.expenses_description.delete(0, [Link])
self.expenses_amount.delete(0, [Link])
def add_investment(self):
description = self.investment_description.get()
amount = self.investment_amount.get()
category = self.investment_category.get()
if not description or not amount or not category:
[Link]("Error", "All fields must be filled.")
return
try:
amount = float(amount)
except ValueError:
[Link]("Error", "Amount must be a number.")
return
entry = {'description': description, 'amount': amount, 'category': category,
'date': [Link]().strftime("%Y-%m-%d %H:%M:%S")}
[Link]['investments'].append(entry)
self.investment_list.insert('', 'end', values=(description, f"{amount:.2f}", category, entry['date']))
self.investment_description.delete(0, [Link])
self.investment_amount.delete(0, [Link])
def add_loan(self):
description = self.loan_description.get()
amount = self.loan_amount.get()
category = self.loan_category.get()
if not description or not amount or not category:
[Link]("Error", "All fields must be filled.")
return
try:
amount = float(amount)
except ValueError:
[Link]("Error", "Amount must be a number.")
return
entry = {'description': description, 'amount': amount, 'category': category,
'date': [Link]().strftime("%Y-%m-%d %H:%M:%S")}
[Link]['loans'].append(entry)
self.loan_list.insert('', 'end', values=(description, f"{amount:.2f}", category, entry['date']))
self.loan_description.delete(0, [Link])
self.loan_amount.delete(0, [Link])
def add_property(self):
description = self.property_description.get()
value = self.property_value.get()
category = self.property_category.get()
if not description or not value or not category:
[Link]("Error", "All fields must be filled.")
return
try:
value = float(value)
except ValueError:
[Link]("Error", "Value must be a number.")
return
entry = {'description': description, 'value': value, 'category': category,
'date': [Link]().strftime("%Y-%m-%d %H:%M:%S")}
[Link]['properties'].append(entry)
self.property_list.insert('', 'end', values=(description, f"{value:.2f}", category, entry['date']))
self.property_description.delete(0, [Link])
self.property_value.delete(0, [Link])
def add_tax(self):
description = self.tax_description.get()
amount = self.tax_amount.get()
category = self.tax_category.get()
if not description or not amount or not category:
[Link]("Error", "All fields must be filled.")
return
try:
amount = float(amount)
except ValueError:
[Link]("Error", "Amount must be a number.")
return
entry = {'description': description, 'amount': amount, 'category': category,
'date': [Link]().strftime("%Y-%m-%d %H:%M:%S")}
[Link]['taxes'].append(entry)
self.tax_list.insert('', 'end', values=(description, f"{amount:.2f}", category, entry['date']))
self.tax_description.delete(0, [Link])
self.tax_amount.delete(0, [Link])
def generate_report(self):
total_income = sum(item['amount'] for item in [Link]['income'])
total_expenses = sum(item['amount'] for item in [Link]['expenses'])
total_investments = sum(item['amount'] for item in [Link]['investments'])
total_loans = sum(item['amount'] for item in [Link]['loans'])
total_properties = sum(item['value'] for item in [Link]['properties'])
total_taxes = sum(item['amount'] for item in [Link]['taxes'])
balance = total_income - total_expenses - total_taxes
report = f"Total Income: ${total_income:.2f}\n"
report += f"Total Expenses: ${total_expenses:.2f}\n"
report += f"Total Taxes: ${total_taxes:.2f}\n"
report += f"Balance: ${balance:.2f}\n\n"
report += "Investment Details:\n"
report += "Description\tAmount\tCategory\tDate\n"
for item in [Link]['investments']:
report += f"{item['description']}\t{item['amount']:.2f}\t{item['category']}\t{item['date']}\n"
report += "\nLoan Details:\n"
report += "Description\tAmount\tCategory\tDate\n"
for item in [Link]['loans']:
report += f"{item['description']}\t{item['amount']:.2f}\t{item['category']}\t{item['date']}\n"
report += "\nProperty Details:\n"
report += "Description\tValue\tCategory\tDate\n"
for item in [Link]['properties']:
report += f"{item['description']}\t{item['value']:.2f}\t{item['category']}\t{item['date']}\n"
report += "\nTax Details:\n"
report += "Description\tAmount\tCategory\tDate\n"
for item in [Link]['taxes']:
report += f"{item['description']}\t{item['amount']:.2f}\t{item['category']}\t{item['date']}\n"
self.report_text.delete(1.0, [Link])
self.report_text.insert([Link], report)
def save_data(self):
file_path = [Link](defaultextension=".json",
filetypes=[("JSON files", "*.json"), ("All files", "*.*")])
if file_path:
with open(file_path, 'w') as file:
[Link]([Link], file, indent=4)
[Link]("Success", "Data saved successfully.")
def load_data(self):
file_path = [Link](filetypes=[("JSON files", "*.json"), ("All files", "*.*")])
if file_path:
with open(file_path, 'r') as file:
[Link] = [Link](file)
self.populate_lists()
[Link]("Success", "Data loaded successfully.")
def populate_lists(self):
self.income_list.delete(*self.income_list.get_children())
for item in [Link]['income']:
self.income_list.insert('', 'end', values=(
item['description'], f"{item['amount']:.2f}", item['category'], item['date']))
self.expenses_list.delete(*self.expenses_list.get_children())
for item in [Link]['expenses']:
self.expenses_list.insert('', 'end', values=(
item['description'], f"{item['amount']:.2f}", item['category'], item['date']))
self.investment_list.delete(*self.investment_list.get_children())
for item in [Link]['investments']:
self.investment_list.insert('', 'end', values=(
item['description'], f"{item['amount']:.2f}", item['category'], item['date']))
self.loan_list.delete(*self.loan_list.get_children())
for item in [Link]['loans']:
self.loan_list.insert('', 'end',
values=(item['description'], f"{item['amount']:.2f}", item['category'], item['date']))
self.property_list.delete(*self.property_list.get_children())
for item in [Link]['properties']:
self.property_list.insert('', 'end', values=(
item['description'], f"{item['value']:.2f}", item['category'], item['date']))
self.tax_list.delete(*self.tax_list.get_children())
for item in [Link]['taxes']:
self.tax_list.insert('', 'end',
values=(item['description'], f"{item['amount']:.2f}", item['category'], item['date']))
def set_budget(self):
category = self.budget_category.get()
amount = self.budget_amount.get()
if not category or not amount:
[Link]("Error", "Category and Budget Amount cannot be empty.")
return
try:
amount = float(amount)
except ValueError:
[Link]("Error", "Budget Amount must be a number.")
return
[Link]['budgets'][category] = amount
[Link]("Success", f"Budget for {category} set to ${amount:.2f}")
def view_budgets(self):
budget_report = "Current Budgets:\n"
for category, amount in [Link]['budgets'].items():
budget_report += f"{category}: ${amount:.2f}\n"
[Link]("Budgets", budget_report)
if __name__ == "__main__":
root = [Link]()
app = FinanceManager(root)
[Link]()
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import [Link]
from datetime import date
# Connect to MySQL
try:
connection = [Link](
host="localhost",
user="root", # Replace with your MySQL username
password="", # Replace with your MySQL password
database="finance_manager"
)
cursor = [Link]()
print("Connected to MySQL database!")
except [Link] as err:
print(f"Error: {err}")
exit(1)
# Insert data into MySQL
def insert_data(table, data):
try:
placeholders = ', '.join(['%s'] * len(data))
columns = ', '.join([Link]())
sql = f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"
[Link](sql, list([Link]()))
[Link]()
[Link]("Success", f"Data added to {table} table successfully!")
except [Link] as err:
[Link]("Error", f"Failed to insert data: {err}")
# Fetch data from MySQL
def fetch_data(table):
try:
[Link](f"SELECT * FROM {table}")
return [Link]()
except [Link] as err:
[Link]("Error", f"Failed to fetch data: {err}")
return []
# Function to handle Income data submission
def add_income():
data = {
"description": income_desc_entry.get(),
"amount": income_amount_entry.get(),
"category": income_category_entry.get(),
"date": [Link]()
}
insert_data("income", data)
refresh_treeview(income_tree, "income")
# Function to handle Expenses data submission
def add_expense():
data = {
"description": expense_desc_entry.get(),
"amount": expense_amount_entry.get(),
"category": expense_category_entry.get(),
"date": [Link]()
}
insert_data("expenses", data)
refresh_treeview(expense_tree, "expenses")
# Function to refresh the Treeview with MySQL data
def refresh_treeview(treeview, table):
for row in treeview.get_children():
[Link](row)
for row in fetch_data(table):
[Link]("", "end", values=row)
# Main Tkinter window
root = [Link]()
[Link]("Personal Finance Manager")
[Link]("800x600")
notebook = [Link](root)
[Link](fill="both", expand=True)
# Income Tab
income_frame = [Link](notebook)
[Link](income_frame, text="Income")
[Link](income_frame, text="Description").grid(row=0, column=0)
income_desc_entry = [Link](income_frame)
income_desc_entry.grid(row=0, column=1)
[Link](income_frame, text="Amount").grid(row=1, column=0)
income_amount_entry = [Link](income_frame)
income_amount_entry.grid(row=1, column=1)
[Link](income_frame, text="Category").grid(row=2, column=0)
income_category_entry = [Link](income_frame)
income_category_entry.grid(row=2, column=1)
[Link](income_frame, text="Add Income", command=add_income).grid(row=3, column=1)
income_tree = [Link](income_frame, columns=("ID", "Description", "Amount", "Category", "Date"), show="headings")
income_tree.grid(row=4, column=0, columnspan=2)
for col in income_tree["columns"]:
income_tree.heading(col, text=col)
refresh_treeview(income_tree, "income")
# Expenses Tab
expense_frame = [Link](notebook)
[Link](expense_frame, text="Expenses")
[Link](expense_frame, text="Description").grid(row=0, column=0)
expense_desc_entry = [Link](expense_frame)
expense_desc_entry.grid(row=0, column=1)
[Link](expense_frame, text="Amount").grid(row=1, column=0)
expense_amount_entry = [Link](expense_frame)
expense_amount_entry.grid(row=1, column=1)
[Link](expense_frame, text="Category").grid(row=2, column=0)
expense_category_entry = [Link](expense_frame)
expense_category_entry.grid(row=2, column=1)
[Link](expense_frame, text="Add Expense", command=add_expense).grid(row=3, column=1)
expense_tree = [Link](expense_frame, columns=("ID", "Description", "Amount", "Category", "Date"), show="headings")
expense_tree.grid(row=4, column=0, columnspan=2)
for col in expense_tree["columns"]:
expense_tree.heading(col, text=col)
refresh_treeview(expense_tree, "expenses")
# Run the Tkinter main loop
[Link]()
# Close MySQL connection when done
[Link]()