百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

Python GUI 编程入门教程 第25章:记账本应用升级—类别统计与图表

liuian 2025-10-19 08:46 49 浏览

25.1 项目目标

在第24章的 月份筛选功能 基础上,新增:

  1. 类别输入:记录时选择支出/收入类别,例如:餐饮、交通、购物、工资、理财等
  2. 类别统计:计算选定月份的各类别总额
  3. 类别图表:生成饼图,展示各类别所占比例

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 功能演示

  1. 录入一条支出:2025-09-01 支出 餐饮 45 午餐
  2. 录入一条支出:2025-09-02 支出 交通 10 地铁
  3. 录入一条收入:2025-09-05 收入 工资 5000
  4. 点击“类别统计图” → 显示 当月各类别占比饼图

25.5 小结

  • 学会了根据收支类型动态更新类别下拉框
  • 在数据库中新增 category 列,用于存储类别信息
  • 实现了 类别统计图表,让财务分析更直观

相关推荐

驱动网卡(怎么从新驱动网卡)
驱动网卡(怎么从新驱动网卡)

网卡一般是指为电脑主机提供有线无线网络功能的适配器。而网卡驱动指的就是电脑连接识别这些网卡型号的桥梁。网卡只有打上了网卡驱动才能正常使用。并不是说所有的网卡一插到电脑上面就能进行数据传输了,他都需要里面芯片组的驱动文件才能支持他进行数据传输...

2026-01-30 00:37 liuian

win10更新助手装系统(微软win10更新助手)

1、点击首页“系统升级”的按钮,给出弹框,告诉用户需要上传IMEI码才能使用升级服务。同时给出同意和取消按钮。华为手机助手2、点击同意,则进入到“系统升级”功能华为手机助手华为手机助手3、在检测界面,...

windows11专业版密钥最新(windows11专业版激活码永久)

 Windows11专业版的正版密钥,我们是对windows的激活所必备的工具。该密钥我们可以通过微软商城或者通过计算机的硬件供应商去购买获得。获得了windows11专业版的正版密钥后,我...

手机删过的软件恢复(手机删除过的软件怎么恢复)
手机删过的软件恢复(手机删除过的软件怎么恢复)

操作步骤:1、首先,我们需要先打开手机。然后在许多图标中找到带有[文件管理]文本的图标,然后单击“文件管理”进入页面。2、进入页面后,我们将在顶部看到一行文本:手机,最新信息,文档,视频,图片,音乐,收藏,最后是我们正在寻找的[更多],单击...

2026-01-29 23:55 liuian

一键ghost手动备份系统步骤(一键ghost 备份)

  步骤1、首先把装有一键GHOST装系统的U盘插在电脑上,然后打开电脑马上按F2或DEL键入BIOS界面,然后就选择BOOT打USDHDD模式选择好,然后按F10键保存,电脑就会马上重启。  步骤...

怎么创建局域网(怎么创建局域网打游戏)

  1、购买路由器一台。进入路由器把dhcp功能打开  2、购买一台交换机。从路由器lan端口拉出一条网线查到交换机的任意一个端口上。  3、两台以上电脑。从交换机任意端口拉出网线插到电脑上(电脑设置...

精灵驱动器官方下载(精灵驱动手机版下载)

是的。驱动精灵是一款集驱动管理和硬件检测于一体的、专业级的驱动管理和维护工具。驱动精灵为用户提供驱动备份、恢复、安装、删除、在线更新等实用功能。1、全新驱动精灵2012引擎,大幅提升硬件和驱动辨识能力...

一键还原系统步骤(一键还原系统有哪些)

1、首先需要下载安装一下Windows一键还原程序,在安装程序窗口中,点击“下一步”,弹出“用户许可协议”窗口,选择“我同意该许可协议的条款”,并点击“下一步”。  2、在弹出的“准备安装”窗口中,可...

电脑加速器哪个好(电脑加速器哪款好)

我认为pp加速器最好用,飞速土豆太懒,急速酷六根本不工作。pp加速器什么网页都加速,太任劳任怨了!以上是个人观点,具体性能请自己试。ps:我家电脑性能很好。迅游加速盒子是可以加速电脑的。因为有过之...

任何u盘都可以做启动盘吗(u盘必须做成启动盘才能装系统吗)

是的,需要注意,U盘的大小要在4G以上,最好是8G以上,因为启动盘里面需要装系统,内存小的话,不能用来安装系统。内存卡或者U盘或者移动硬盘都可以用来做启动盘安装系统。普通的U盘就可以,不过最好U盘...

u盘怎么恢复文件(u盘文件恢复的方法)

开360安全卫士,点击上面的“功能大全”。点击文件恢复然后点击“数据”下的“文件恢复”功能。选择驱动接着选择需要恢复的驱动,选择接入的U盘。点击开始扫描选好就点击中间的“开始扫描”,开始扫描U盘数据。...

系统虚拟内存太低怎么办(系统虚拟内存占用过高什么原因)

1.检查系统虚拟内存使用情况,如果发现有大量的空闲内存,可以尝试释放一些不必要的进程,以释放内存空间。2.如果系统虚拟内存使用率较高,可以尝试增加系统虚拟内存的大小,以便更多的应用程序可以使用更多...

剪贴板权限设置方法(剪贴板访问权限)
剪贴板权限设置方法(剪贴板访问权限)

1、首先打开iphone手机,触碰并按住单词或图像直到显示选择选项。2、其次,然后选取“拷贝”或“剪贴板”。3、勾选需要的“权限”,最后选择开启,即可完成苹果剪贴板权限设置。仅参考1.打开苹果手机设置按钮,点击【通用】。2.点击【键盘】,再...

2026-01-29 21:37 liuian

平板系统重装大师(平板重装win系统)

如果你的平板开不了机,但可以连接上电脑,那就能好办,楼主下载安装个平板刷机王到你的个人电脑上,然后连接你的平板,平板刷机王会自动识别你的平板,平板刷机王上有你平板的我刷机包,楼主点击下载一个,下载完成...

联想官网售后服务网点(联想官网售后服务热线)

联想3c服务中心是联想旗下的官方售后,是基于互联网O2O模式开发的全新服务平台。可以为终端用户提供多品牌手机、电脑以及其他3C类产品的维修、保养和保险服务。根据客户需求层次,联想服务针对个人及家庭客户...