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

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

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

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 列,用于存储类别信息
  • 实现了 类别统计图表,让财务分析更直观

相关推荐

Spring Boot + Vue.js 实现前后端分离(附源码)

作者:梁小生0101链接:juejin.im/post/5c622fb5e51d457f9f2c2381SpringBoot+Vue.js前后端涉及基本概念介绍,搭建记录,本文会列举出用到环...

C#一步一步实现自己的插件框架(四),从此告别代码紧耦合

初学者写程序一般就是拖控件,双击,然后写上执行的代码,这样在窗口中就有很多事件代码,如果要实现各按钮的状态,那得在很多地方修改代码,极为复杂.通过参考CSHARPDEVELOP的代码就说明和网上各位...

基于UI组件的Vue可视化布局、快速生成.vue代码

一、项目简介基于UI组件的Vue可视化布局、快速生成.vue代码二、实现功能通用(文本、链接、换行、div、图片)支持elementUI支持iViewUI(button、icon、radio、sel...

【开源资讯】ViewUI 4.2.0(原 iView)发布,企业级 UI 组件库

简介iView作者Aresn于2019年创办了北京视图更新科技有限公司,开始自由、全职地维护iView及其相关的软件。ViewUI即为原先的iView,从2019年10月起...

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

25.1项目目标在第24章的月份筛选功能基础上,新增:类别输入:记录时选择支出/收入类别,例如:餐饮、交通、购物、工资、理财等类别统计:计算选定月份的各类别总额类别图表:生成饼图,展示各类别所占...

Python GUI 编程入门教程 第8章:文件处理、数据库操作与网络通信

8.1文件操作:处理本地文件与文件对话框在Tkinter应用中,文件操作是常见的需求。Tkinter提供了简单的文件对话框来帮助用户选择文件,并能通过Python内建的文件处理模块来读取和写入文件。...

手把手教你用Python做个可视化的“剪刀石头布”小游戏

/1前言/最近在学习PyQt5可视化界面,这是一个内容非常丰富的gui库,相对于tkinter库,功能更加强大,界面更加美观,操作也不难。于是我开始小试牛刀,用PyQt5做个可视化的“剪刀石头布”...

掌握基础技能快速用Python设计界面

我们在设计软件界面的时候,应该掌握一定的基础知识,不能我们看起来非常费解也很累。到后面设计界面的时候,很多基础知识不可能如你开始学的时候讲的那样仔细。熟练掌握Python的基本语法,如变量、数据类型...

Python GUI 编程入门教程 第22章:综合实战项目——记账本应用

22.1项目目标我们要开发一个带数据库的记账本,主要功能:添加收支记录(日期、类别、金额、备注)显示所有记录(表格形式)支持删除记录自动保存到SQLite数据库统计总收支22.2项目结构budge...

Python GUI 编程入门教程 第10章:高级布局与界面美化

10.1高级布局管理:使用grid和placeTkinter提供了三种常用的布局管理方式:pack、grid和place。在本章中,我们重点介绍grid和place,这两种布局方式相较于pack更加...

别再手动复制粘贴了!Python一招搞定取PDF内容,效率提升10倍!

别再手动复制粘贴了!Python一招搞定取PDF内容,效率提升10倍!还在为PDF内容提取头疼?100页的文档要折腾一下午?今天教你用Python几行代码搞定,10秒钟解决战斗,办公室小白也能轻松学会...

DearPyGui:GUI 性能秒杀 PyQt,揭秘 GPU 加速的 DearPyGui

什么是DearPyGui?嘿,最近我发现了一个超有意思的PythonGUI框架——DearPyGui。名字有点拗口,但它可不是随便起的。它基于C++和GPU渲染,性能吊打传统的Tki...

Python GUI 编程入门教程 第7章:事件绑定、动画效果与外部交互

7.1事件绑定:响应用户操作在Tkinter中,事件绑定允许你为控件添加响应函数,以处理用户的输入事件,如鼠标点击、键盘输入等。事件可以是各种形式的交互,如点击按钮、键盘按键等。7.1.1绑定鼠标...

Python GUI 编程入门教程 第21章:综合实战项目——记事本应用

21.1项目目标我们要实现一个简易版的记事本,具备以下功能:新建、打开、保存文件复制、粘贴、剪切、全选设置字体大小查找文字显示应用信息界面大致效果如下:+----------------------...

Python GUI 编程入门教程 第14章:构建复杂图形界面

14.1界面布局管理在Tkinter中,界面控件的排列是通过布局管理器来实现的。Tkinter提供了三种布局管理器:pack、grid和place,每种布局管理器都有其独特的用途和优势。14.1.1...