Python GUI 编程入门教程 第25章:记账本应用升级—类别统计与图表
liuian 2025-10-19 08:46 43 浏览
25.1 项目目标
在第24章的 月份筛选功能 基础上,新增:
- 类别输入:记录时选择支出/收入类别,例如:餐饮、交通、购物、工资、理财等
- 类别统计:计算选定月份的各类别总额
- 类别图表:生成饼图,展示各类别所占比例
25.2 界面设计
- 在 添加记录区 新增 类别下拉框,收入和支出都有对应类别。
- 在 统计功能区 新增按钮 → “类别统计”。
- 点击按钮后,显示 饼图,展示该月的各类别收支比例。
25.3 核心代码
下面是在第24章的 BudgetApp 基础上修改后的核心实现:
import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class BudgetApp:
def __init__(self, root):
self.root = root
self.root.title("记账本(类别统计版)")
self.root.geometry("850x600")
# 数据库
self.conn = sqlite3.connect("budget.db")
self.cursor = self.conn.cursor()
self.create_table()
# 输入区
frame_input = tk.Frame(self.root)
frame_input.pack(pady=10)
tk.Label(frame_input, text="日期(YYYY-MM-DD):").grid(row=0, column=0, padx=5)
self.entry_date = tk.Entry(frame_input, width=12)
self.entry_date.grid(row=0, column=1, padx=5)
self.entry_date.insert(0, datetime.now().strftime("%Y-%m-%d"))
tk.Label(frame_input, text="收支类型:").grid(row=0, column=2, padx=5)
self.combo_type = ttk.Combobox(frame_input, values=["收入", "支出"], width=8)
self.combo_type.grid(row=0, column=3, padx=5)
self.combo_type.current(0)
self.combo_type.bind("<<ComboboxSelected>>", self.update_categories)
tk.Label(frame_input, text="类别:").grid(row=0, column=4, padx=5)
self.combo_category = ttk.Combobox(frame_input, values=[], width=10)
self.combo_category.grid(row=0, column=5, padx=5)
self.update_categories() # 初始化类别
tk.Label(frame_input, text="金额:").grid(row=0, column=6, padx=5)
self.entry_amount = tk.Entry(frame_input, width=10)
self.entry_amount.grid(row=0, column=7, padx=5)
tk.Label(frame_input, text="备注:").grid(row=0, column=8, padx=5)
self.entry_note = tk.Entry(frame_input, width=15)
self.entry_note.grid(row=0, column=9, padx=5)
tk.Button(frame_input, text="添加记录", command=self.add_record).grid(row=0, column=10, padx=10)
# 月份筛选区
frame_month = tk.Frame(self.root)
frame_month.pack(pady=5)
tk.Label(frame_month, text="选择月份:").pack(side=tk.LEFT, padx=5)
self.combo_month = ttk.Combobox(frame_month, values=self.get_months(), width=10)
self.combo_month.pack(side=tk.LEFT, padx=5)
self.combo_month.set(datetime.now().strftime("%Y-%m"))
tk.Button(frame_month, text="查询", command=self.load_records).pack(side=tk.LEFT, padx=10)
# 表格
self.tree = ttk.Treeview(self.root, columns=("id", "date", "type", "category", "amount", "note"), show="headings")
self.tree.heading("id", text="ID")
self.tree.heading("date", text="日期")
self.tree.heading("type", text="收支类型")
self.tree.heading("category", text="类别")
self.tree.heading("amount", text="金额")
self.tree.heading("note", text="备注")
self.tree.column("id", width=50, anchor="center")
self.tree.column("date", width=100, anchor="center")
self.tree.column("type", width=80, anchor="center")
self.tree.column("category", width=100, anchor="center")
self.tree.column("amount", width=80, anchor="center")
self.tree.column("note", width=200, anchor="w")
self.tree.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# 操作按钮
frame_btn = tk.Frame(self.root)
frame_btn.pack(pady=5)
tk.Button(frame_btn, text="删除记录", command=self.delete_record).pack(side=tk.LEFT, padx=10)
tk.Button(frame_btn, text="统计收支", command=self.show_summary).pack(side=tk.LEFT, padx=10)
tk.Button(frame_btn, text="收支饼图", command=self.show_pie_chart).pack(side=tk.LEFT, padx=10)
tk.Button(frame_btn, text="收支趋势图", command=self.show_line_chart).pack(side=tk.LEFT, padx=10)
tk.Button(frame_btn, text="类别统计图", command=self.show_category_chart).pack(side=tk.LEFT, padx=10)
# 初始加载
self.load_records()
def create_table(self):
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT,
type TEXT,
category TEXT,
amount REAL,
note TEXT
)
""")
self.conn.commit()
def update_categories(self, event=None):
"""根据收支类型更新类别"""
if self.combo_type.get() == "收入":
categories = ["工资", "奖金", "理财", "其他"]
else:
categories = ["餐饮", "交通", "购物", "住房", "娱乐", "医疗", "其他"]
self.combo_category["values"] = categories
self.combo_category.current(0)
def add_record(self):
date = self.entry_date.get()
type_ = self.combo_type.get()
category = self.combo_category.get()
try:
amount = float(self.entry_amount.get())
except ValueError:
messagebox.showerror("错误", "金额必须是数字")
return
note = self.entry_note.get()
self.cursor.execute("INSERT INTO records (date, type, category, amount, note) VALUES (?, ?, ?, ?, ?)",
(date, type_, category, amount, note))
self.conn.commit()
self.load_records()
self.entry_amount.delete(0, tk.END)
self.entry_note.delete(0, tk.END)
def get_months(self):
self.cursor.execute("SELECT DISTINCT substr(date, 1, 7) FROM records ORDER BY date DESC")
months = [row[0] for row in self.cursor.fetchall()]
if not months:
months = [datetime.now().strftime("%Y-%m")]
return months
def load_records(self):
for row in self.tree.get_children():
self.tree.delete(row)
month = self.combo_month.get()
self.cursor.execute("SELECT * FROM records WHERE substr(date,1,7)=? ORDER BY date DESC", (month,))
for row in self.cursor.fetchall():
self.tree.insert("", tk.END, values=row)
def delete_record(self):
selected = self.tree.selection()
if not selected:
messagebox.showwarning("提示", "请选择要删除的记录")
return
record_id = self.tree.item(selected[0])["values"][0]
self.cursor.execute("DELETE FROM records WHERE id=?", (record_id,))
self.conn.commit()
self.load_records()
def show_summary(self):
month = self.combo_month.get()
self.cursor.execute("SELECT type, SUM(amount) FROM records WHERE substr(date,1,7)=? GROUP BY type", (month,))
result = self.cursor.fetchall()
income = sum(r[1] for r in result if r[0] == "收入")
expense = sum(r[1] for r in result if r[0] == "支出")
messagebox.showinfo("统计结果", f"{month} 收支情况:\n总收入: {income} 元\n总支出: {expense} 元\n结余: {income - expense} 元")
def show_pie_chart(self):
month = self.combo_month.get()
self.cursor.execute("SELECT type, SUM(amount) FROM records WHERE substr(date,1,7)=? GROUP BY type", (month,))
result = self.cursor.fetchall()
if not result:
messagebox.showwarning("提示", "没有数据可显示")
return
labels = [r[0] for r in result]
amounts = [r[1] for r in result]
fig, ax = plt.subplots()
ax.pie(amounts, labels=labels, autopct="%1.1f%%", startangle=90)
ax.set_title(f"{month} 收支比例")
win = tk.Toplevel(self.root)
win.title("收支饼图")
canvas = FigureCanvasTkAgg(fig, master=win)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
def show_line_chart(self):
month = self.combo_month.get()
self.cursor.execute("SELECT date, type, SUM(amount) FROM records WHERE substr(date,1,7)=? GROUP BY date, type ORDER BY date", (month,))
result = self.cursor.fetchall()
if not result:
messagebox.showwarning("提示", "没有数据可显示")
return
dates = sorted(set(r[0] for r in result))
income_data, expense_data = [], []
for d in dates:
income = sum(r[2] for r in result if r[0] == d and r[1] == "收入")
expense = sum(r[2] for r in result if r[0] == d and r[1] == "支出")
income_data.append(income)
expense_data.append(expense)
fig, ax = plt.subplots()
ax.plot(dates, income_data, marker="o", label="收入")
ax.plot(dates, expense_data, marker="o", label="支出")
ax.set_title(f"{month} 收支趋势图")
ax.set_xlabel("日期")
ax.set_ylabel("金额")
ax.legend()
plt.xticks(rotation=45)
win = tk.Toplevel(self.root)
win.title("收支趋势图")
canvas = FigureCanvasTkAgg(fig, master=win)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
def show_category_chart(self):
"""按类别统计并绘制饼图"""
month = self.combo_month.get()
self.cursor.execute("SELECT category, SUM(amount) FROM records WHERE substr(date,1,7)=? GROUP BY category", (month,))
result = self.cursor.fetchall()
if not result:
messagebox.showwarning("提示", "没有数据可显示")
return
labels = [r[0] for r in result]
amounts = [r[1] for r in result]
fig, ax = plt.subplots()
ax.pie(amounts, labels=labels, autopct="%1.1f%%", startangle=90)
ax.set_title(f"{month} 各类别占比")
win = tk.Toplevel(self.root)
win.title("类别统计图")
canvas = FigureCanvasTkAgg(fig, master=win)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
def __del__(self):
self.conn.close()
if __name__ == "__main__":
root = tk.Tk()
app = BudgetApp(root)
root.mainloop()
25.4 功能演示
- 录入一条支出:2025-09-01 支出 餐饮 45 午餐
- 录入一条支出:2025-09-02 支出 交通 10 地铁
- 录入一条收入:2025-09-05 收入 工资 5000
- 点击“类别统计图” → 显示 当月各类别占比饼图
25.5 小结
- 学会了根据收支类型动态更新类别下拉框
- 在数据库中新增 category 列,用于存储类别信息
- 实现了 类别统计图表,让财务分析更直观
相关推荐
-
- mediaplayer播放记录在哪里(mediaplayer历史记录)
-
《WindowsMediaPlayer》无法播放该文件,表示《WindowsMediaPlayer》目前的版本不支持该视频的格式编码。解决方法: 1.如果安装的是正版操作系统,点帮助→检查更新,稍待片刻,WindowsMed...
-
2026-01-14 02:37 liuian
- 电脑xp怎么换系统win7(电脑xp系统换win7教程)
-
第一种方法:自助安装win7系统 我们在进行自助安装win7系统之前我们要保证我们的电脑是联网的。为了能更加顺利的完成对xp系统的升级,我们的电脑最好是能高速上网的,只有能联网我们才可以下载最新的系...
- appstore官方网站(appstore.apple.com)
-
Appstore即applicationstore,通常理解为应用商店。Appstore是苹果公司基于iPhone的软件应用商店,向iPhone的用户提供第三方的应用软件服务,这是苹果开创的一...
- 电脑开不了机怎么办显示英文字母
-
win7操作系统电脑在开机的时候屏幕界面出现CLIENTMACADDR,然后就一直停在了这个界面,要等很长时间才能进入系统登入界面。出现这样问题的原因是什么?这是因为网卡启用了BOOTROM芯片...
- win7此windows副本不是正版(win7 此windows副本不是正版)
-
win7系统提示副本不是正版解决方法:1.打开设备,调出运行窗口,输入命令“cmd”,并按下回车键;2.这时命令提示符窗口便会自动弹出;3.输入命令“SLMGR-REARM”,再按下回车键;4.命令...
- win7安装选版本(win7选哪个版本)
-
Win7旗舰版更好用。Windows7旗舰版属于微软公司开发的Windows7系统系列中的终结版本,是为了取代WindowsXP系统的新系统,Windows7的版本还有简易版、家庭普通版、家庭高...
-
- 电脑psd文件用什么打开(电脑上psd文件打不开)
-
具体操作步骤如下:1、首先鼠标右键单击PSD格式的图片,然后点击“打开方式”选项。2、然后在该页面中点击“选择默认程序”选项。3、之后在该页面中点击“浏览”选项。4、然后在该页面中点击选择要打开的软件后点击“确定”选项即可打开了。PSD文...
-
2026-01-14 01:05 liuian
- tplink登陆密码(tplink登录密码)
-
TP-LINK路由器默认的出厂登录用户名和密码均为小写字母“admin”。该密码是保护路由器免遭攻击的重要密码,忘记了登录的管理员密码,只能通过路由器的Reset复位键(部分路由器为Reset小孔)进...
- windows8中文版激活(windows8激活怎么操作)
-
要激活Windows8操作系统,可以按照以下步骤进行操作:1.打开“开始”菜单,点击桌面图标,进入桌面模式。2.从屏幕右侧滑动以打开“设置”栏,然后点击“更改PC设置”。3.在左侧导航栏中选择...
-
- 手机app怎么下载(手机app怎么下载安装)
-
每个手机上都有下载APP的应用商店,以下面为例演示,下载方法如下:1、首先在手机上找到并打开应用商店。2、接下来进入到应用商店之后,选择红色箭头所指处的搜索栏,搜索需要下载的应用。3、接下来会弹出搜索的应用,点击红色箭头所...
-
2026-01-13 23:37 liuian
- dell电脑蓝屏开不了机怎么办
-
电脑蓝屏的解决方法,先软件后硬件,一般软件问题比较多一点。1、最后一次正确的配置:在开机启动未进入到操作系统之前我们不停按下F8键,选择“最后一次正确的配置”然后回车即可。2、安全模式:如果“最后一次...
- 如何单独改c盘为mbr模式(如何c盘改为mbr分区 免格式化)
-
硬盘分为两种格式的分区,一种是GPT,一种是MBR,一般win7或者以下系统是安装在MBR分区中,而win8和win10一般是安装在gpt分区中的,这两个分区格...
- 一周热门
-
-
飞牛OS入门安装遇到问题,如何解决?
-
如何在 iPhone 和 Android 上恢复已删除的抖音消息
-
Boost高性能并发无锁队列指南:boost::lockfree::queue
-
大模型手册: 保姆级用CherryStudio知识库
-
用什么工具在Win中查看8G大的log文件?
-
如何在 Windows 10 或 11 上通过命令行安装 Node.js 和 NPM
-
威联通NAS安装阿里云盘WebDAV服务并添加到Infuse
-
Trae IDE 如何与 GitHub 无缝对接?
-
idea插件之maven search(工欲善其事,必先利其器)
-
如何修改图片拍摄日期?快速修改图片拍摄日期的6种方法
-
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)
- mysql刷新权限 (34)
