import tkinter as tk from tkinter import ttk import sqlite3 from datetime import datetime # Создание или подключение к базе данных SQLite def create_db(): conn = sqlite3.connect('finance_tracker.db') cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS transactions ( id INTEGER PRIMARY KEY AUTOINCREMENT, amount REAL, category TEXT, transaction_type TEXT, description TEXT, date TEXT ) ''') conn.commit() conn.close() # Функция для добавления записи в базу данных def add_transaction(amount, category, transaction_type, description): date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") conn = sqlite3.connect('finance_tracker.db') cursor = conn.cursor() cursor.execute(''' INSERT INTO transactions (amount, category, transaction_type, description, date) VALUES (?, ?, ?, ?, ?) ''', (amount, category, transaction_type, description, date)) conn.commit() conn.close() # Функция для отображения всех записей из базы данных def show_transactions(treeview): for row in treeview.get_children(): treeview.delete(row) conn = sqlite3.connect('finance_tracker.db') cursor = conn.cursor() cursor.execute('SELECT amount, category, transaction_type, description, date FROM transactions ORDER BY date DESC') rows = cursor.fetchall() conn.close() for row in rows: treeview.insert("", "end", values=row) # Функция для подсчета общей суммы доходов, расходов и разности def calculate_totals(): conn = sqlite3.connect('finance_tracker.db') cursor = conn.cursor() cursor.execute('SELECT * FROM transactions') rows = cursor.fetchall() conn.close() total_income = 0 total_expense = 0 for row in rows: amount = row[1] transaction_type = row[3] if transaction_type == 'Доход': total_income += amount elif transaction_type == 'Расход': total_expense += amount balance = total_income - total_expense return total_income, total_expense, balance # Обновление отображения общей суммы и разности def update_totals(label_income, label_expense, label_balance): total_income, total_expense, balance = calculate_totals() label_income.config(text=f"Общий доход: {total_income:.2f} руб.") label_expense.config(text=f"Общие расходы: {total_expense:.2f} руб.") label_balance.config(text=f"Разность: {balance:.2f} руб.") # Добавление транзакции через форму def add_transaction_from_form(entry_amount, combo_category, combo_type, entry_description): try: amount = float(entry_amount.get()) category = combo_category.get() transaction_type = combo_type.get() description = entry_description.get() if amount <= 0 or not category or not transaction_type: raise ValueError("Заполните все обязательные поля!") add_transaction(amount, category, transaction_type, description) update_totals(label_income, label_expense, label_balance) show_transactions(treeview) # Очистка полей entry_amount.delete(0, tk.END) combo_category.set("") combo_type.set("") entry_description.delete(0, tk.END) except ValueError as e: print(f"Ошибка: {e}") # Создание графического интерфейса def create_gui(): root = tk.Tk() root.title("Учет финансов") # Лейблы для общей суммы и разности global label_income, label_expense, label_balance label_income = tk.Label(root, text="Общий доход: 0.00 руб.", font=("Arial", 14)) label_income.pack(pady=5) label_expense = tk.Label(root, text="Общие расходы: 0.00 руб.", font=("Arial", 14)) label_expense.pack(pady=5) label_balance = tk.Label(root, text="Разность: 0.00 руб.", font=("Arial", 14)) label_balance.pack(pady=5) # Форма для добавления транзакции frame_input = tk.Frame(root) frame_input.pack(pady=10) tk.Label(frame_input, text="Сумма:").grid(row=0, column=0) entry_amount = tk.Entry(frame_input) entry_amount.grid(row=0, column=1) tk.Label(frame_input, text="Категория:").grid(row=1, column=0) combo_category = ttk.Combobox(frame_input, values=["Продукты", "Транспорт", "Развлечения", "Счета", "Зарплата", "Другое"]) combo_category.grid(row=1, column=1) tk.Label(frame_input, text="Тип:").grid(row=2, column=0) combo_type = ttk.Combobox(frame_input, values=["Доход", "Расход"]) combo_type.grid(row=2, column=1) tk.Label(frame_input, text="Описание:").grid(row=3, column=0) entry_description = tk.Entry(frame_input, width=40) entry_description.grid(row=3, column=1) button_add = tk.Button(frame_input, text="Добавить транзакцию", command=lambda: add_transaction_from_form(entry_amount, combo_category, combo_type, entry_description)) button_add.grid(row=4, column=0, columnspan=2, pady=10) # Таблица для отображения транзакций global treeview treeview = ttk.Treeview(root, columns=("Сумма", "Категория", "Тип", "Описание", "Дата"), show="headings") treeview.heading("Сумма", text="Сумма") treeview.heading("Категория", text="Категория") treeview.heading("Тип", text="Тип") treeview.heading("Описание", text="Описание") treeview.heading("Дата", text="Дата") treeview.pack(pady=10) # Кнопка для отображения всех транзакций button_show = tk.Button(root, text="Показать все транзакции", command=lambda: show_transactions(treeview)) button_show.pack(pady=10) # Инициализация базы данных и начальное обновление данных create_db() update_totals(label_income, label_expense, label_balance) show_transactions(treeview) root.mainloop() if __name__ == "__main__": create_gui()