在这篇博客中,我们将介绍如何使用 Python 和 PyQt5 创建一个图形用户界面(GUI)的个人记账应用。这个应用程序允许用户记录收入和支出,并生成月度或年度报告。我们将逐步讲解代码的实现,并展示如何运行这个应用程序。
前提条件
在开始之前,请确保你已经安装了以下工具和库:
- Python:确保你的系统上已经安装了 Python。
- PyQt5:用于创建 GUI。
- SQLite:用于存储交易记录。
步骤
第一步:导入必要的模块
首先,我们需要导入必要的模块。sqlite3
用于与 SQLite 数据库进行交互,PyQt5
用于创建 GUI。
import sys
import sqlite3
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel, QPushButton, QLineEdit, QComboBox, QTextEdit, QMessageBox, QInputDialog
代码解析
- import sys:导入系统模块,用于处理命令行参数。
- import sqlite3:导入 SQLite 数据库模块,用于与 SQLite 数据库进行交互。
- from PyQt5.QtWidgets import …:导入 PyQt5 的各种控件,用于创建 GUI。
第二步:创建数据库连接和表
接下来,我们创建一个数据库连接,并创建一个名为 transactions
的表,用于存储交易记录。
# 创建数据库连接
conn = sqlite3.connect('finance.db')
c = conn.cursor()
# 创建表
c.execute('''CREATE TABLE IF NOT EXISTS transactions
(id INTEGER PRIMARY KEY, date TEXT, type TEXT, amount REAL, description TEXT)''')
conn.commit()
代码解析
- conn = sqlite3.connect(‘finance.db’):创建一个 SQLite 数据库连接,数据库文件名为
finance.db
。 - c = conn.cursor():创建一个游标对象,用于执行 SQL 语句。
- c.execute(…):执行 SQL 语句,创建一个名为
transactions
的表,用于存储交易记录。 - conn.commit():提交事务,保存更改。
第三步:定义添加交易记录的函数
我们定义一个函数 add_transaction
,用于向数据库中添加一条交易记录
def add_transaction(date, trans_type, amount, description):
c.execute("INSERT INTO transactions (date, type, amount, description) VALUES (?, ?, ?, ?)",
(date, trans_type, amount, description))
conn.commit()
代码解析
- def add_transaction(date, trans_type, amount, description):定义一个函数
add_transaction
,接受日期、类型、金额和描述作为参数。 - c.execute(…):执行 SQL 语句,向
transactions
表中插入一条记录。 - conn.commit():提交事务,保存更改。
第四步:定义生成报告的函数
接下来,我们定义一个函数 generate_report
,用于生成月度或年度报告。
def generate_report(period):
if period == 'monthly':
c.execute("SELECT strftime('%Y-%m', date) as month, type, SUM(amount) FROM transactions GROUP BY month, type")
elif period == 'yearly':
c.execute("SELECT strftime('%Y', date) as year, type, SUM(amount) FROM transactions GROUP BY year, type")
report = c.fetchall()
return report
代码解析
- def generate_report(period):定义一个函数
generate_report
,接受报告周期作为参数。 - c.execute(…):根据报告周期执行不同的 SQL 语句,生成月度或年度报告。
- report = c.fetchall():获取查询结果。
- return report:返回查询结果。
第五步:创建 GUI
我们使用 PyQt5 创建一个 GUI,包含输入日期、选择类型、输入金额和描述的控件,以及添加交易和生成报告的按钮。
class FinanceApp(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('个人记账应用')
self.setGeometry(100, 100, 400, 300)
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.layout = QVBoxLayout(self.central_widget)
self.label = QLabel('个人记账应用程序', self)
self.layout.addWidget(self.label)
self.date_label = QLabel('日期 (YYYY-MM-DD):', self)
self.layout.addWidget(self.date_label)
self.date_input = QLineEdit(self)
self.layout.addWidget(self.date_input)
self.type_label = QLabel('类型:', self)
self.layout.addWidget(self.type_label)
self.type_combo = QComboBox(self)
self.type_combo.addItems(['收入', '支出'])
self.layout.addWidget(self.type_combo)
self.amount_label = QLabel('金额:', self)
self.layout.addWidget(self.amount_label)
self.amount_input = QLineEdit(self)
self.layout.addWidget(self.amount_input)
self.description_label = QLabel('描述:', self)
self.layout.addWidget(self.description_label)
self.description_input = QTextEdit(self)
self.layout.addWidget(self.description_input)
self.add_button = QPushButton('添加交易', self)
self.add_button.clicked.connect(self.add_transaction)
self.layout.addWidget(self.add_button)
self.report_button = QPushButton('生成报告', self)
self.report_button.clicked.connect(self.show_report)
self.layout.addWidget(self.report_button)
def add_transaction(self):
date = self.date_input.text()
trans_type = self.type_combo.currentText()
amount = float(self.amount_input.text())
description = self.description_input.toPlainText()
add_transaction(date, trans_type, amount, description)
QMessageBox.information(self, '成功', f'{trans_type}记录成功!\n日期: {date}\n金额: {amount}\n描述: {description}')
def show_report(self):
period, ok = QInputDialog.getItem(self, '选择报告周期', '请选择报告周期:', ['monthly', 'yearly'], 0, False)
if ok:
report = generate_report(period)
report_text = '\n'.join([f'{row[0]} - {row[1]}: {row[2]}' for row in report])
QMessageBox.information(self, '报告', report_text)
代码解析
- class FinanceApp(QMainWindow):定义一个类
FinanceApp
,继承自QMainWindow
。 - def init(self):初始化函数,调用
initUI
方法初始化界面。 - def initUI(self):初始化界面,设置窗口标题、大小,并添加各种控件。
- def add_transaction(self):处理添加交易的逻辑,获取用户输入的数据,并调用
add_transaction
函数将数据添加到数据库中。 - def show_report(self):处理生成报告的逻辑,获取用户选择的报告周期,并调用
generate_report
函数生成报告。
第六步:运行应用程序
在主程序中,我们创建并运行应用程序。
if __name__ == "__main__":
app = QApplication(sys.argv)
main_window = FinanceApp()
main_window.show()
sys.exit(app.exec_())
conn.close()
运行结果
运行上述代码后,你将看到一个图形用户界面,允许你输入交易记录并生成报告。
代码解析
- if name == “main”::检查当前模块是否是主模块。
- app = QApplication(sys.argv):创建一个应用程序实例。
- main_window = FinanceApp():创建主窗口实例。
- main_window.show():显示主窗口。
- sys.exit(app.exec_()):运行应用程序的主循环。
- conn.close():关闭数据库连接。
说明
在这个示例中,我们使用 Python 和 PyQt5 创建了一个简单的个人记账应用。用户可以输入收入和支出的详细信息,并生成月度或年度报告。
总结
通过这篇博客文章,你学会了如何使用 Python 和 PyQt5 创建一个图形用户界面(GUI)的个人记账应用。我们逐步讲解了代码的实现,包括导入模块、创建数据库连接和表、定义函数、创建 GUI 和运行应用程序。你可以根据需要修改和扩展这个应用程序,以实现更多的功能。
其他文章推荐
如果你对 Python 编程感兴趣,以下是一些推荐的文章:
- PyQt5 创建个人记账应用-CSDN博客
- 使用 python 初始化和打印多个数据列表-CSDN博客
- 使用 Python 创建一个 HTTP 代理服务器-CSDN博客
- Python OS库 经典且使用的 5个脚本 示例 附源码-CSDN博客
- 使用Selenium 和 Python 抓取快手网页大量评论-CSDN博客
希望这些推荐的文章对你有帮助,祝你编程愉快!如果你有任何其他问题,请随时告诉我。😊