优秀的编程知识分享平台

网站首页 > 技术文章 正文

Python GUI 编程入门教程 第34章:记账本应用升级——图表报表导出

nanyue 2025-09-21 20:11:40 技术文章 2 ℃

34.1 项目目标

  1. 新增 “导出图表” 功能
  2. 支持生成:
  3. 收支饼图(收入 vs 支出占比)
  4. 类别柱状图(各类别金额对比)
  5. 将图表导出为 PNG 图片 文件
  6. 管理员可生成所有用户的数据图表,普通用户仅能生成自己的

34.2 使用的库

我们使用 Python 标准可视化库 matplotlib(Tkinter 能很好地配合)。

import matplotlib.pyplot as plt

34.3 导出图表代码

在 BudgetApp 中新增:

def export_charts(self):
    """导出收支图表(PNG 图片)"""
    file_path = filedialog.asksaveasfilename(
        defaultextension=".png",
        filetypes=[("PNG 图片", "*.png")]
    )
    if not file_path:
        return

    # 加载数据
    if self.role == "user":
        self.cursor.execute("SELECT type, category, amount FROM records WHERE user_id=?", (self.user_id,))
    else:
        self.cursor.execute("SELECT type, category, amount FROM records")

    rows = self.cursor.fetchall()
    if not rows:
        messagebox.showwarning("提示", "没有数据可导出图表")
        return

    # 统计收入 vs 支出
    income = sum(r[2] for r in rows if r[0] == "收入")
    expense = sum(r[2] for r in rows if r[0] == "支出")

    # 统计类别金额
    category_totals = {}
    for _, cat, amt in rows:
        category_totals[cat] = category_totals.get(cat, 0) + amt

    # 绘制图表
    fig, axes = plt.subplots(1, 2, figsize=(10, 5))

    # 饼图
    axes[0].pie([income, expense], labels=["收入", "支出"], autopct="%.1f%%", colors=["#4caf50", "#f44336"])
    axes[0].set_title("收入 vs 支出")

    # 柱状图
    axes[1].bar(category_totals.keys(), category_totals.values(), color="#2196f3")
    axes[1].set_title("各类别金额")
    axes[1].set_ylabel("金额")
    axes[1].tick_params(axis="x", rotation=30)

    plt.tight_layout()
    try:
        plt.savefig(file_path)
        plt.close(fig)
        messagebox.showinfo("成功", f"图表已导出到 {file_path}")
    except Exception as e:
        messagebox.showerror("错误", f"导出失败: {e}")

34.4 在界面中加入按钮

在 BudgetApp.__init__ 的操作按钮区增加:

tk.Button(frame_btn, text="导出图表", command=self.export_charts).pack(side=tk.LEFT, padx=10)

34.5 功能演示

  1. 用户点击 “导出图表”
  2. 选择 report.png → 程序生成一个包含 两个图表 的 PNG:
  3. 左边:饼图,显示收入 vs 支出比例
  4. 右边:柱状图,显示不同类别的支出或收入金额
  5. 普通用户:只显示自己数据的图表
  6. 管理员:包含所有用户数据的图表

34.6 小结

  • 使用 matplotlib 生成 饼图 + 柱状图,直观展示收支情况
  • 支持导出为 PNG 图片,便于分享或打印
  • 根据用户权限导出不同范围的数据

Tags:

最近发表
标签列表