中級者向け No.081

家計簿ダッシュボード

収支データをpandasで集計しmatplotlibで月別・カテゴリ別グラフを表示するビジュアル家計簿。

🎯 難易度: ★★★ 📦 ライブラリ: tkinter(標準ライブラリ), matplotlib, sqlite3(標準) ⏱️ 制作時間: 30〜90分

1. アプリ概要

収支データをpandasで集計しmatplotlibで月別・カテゴリ別グラフを表示するビジュアル家計簿。

このアプリはdataカテゴリの実践的なPythonアプリです。使用ライブラリは tkinter(標準ライブラリ)・pandas・matplotlib、難易度は ★★★ です。

Pythonの豊富なライブラリを活用することで、実用的なアプリを短いコードで実装できます。ソースコードをコピーして実行し、仕組みを理解したうえでカスタマイズに挑戦してみてください。

GUIアプリ開発はプログラミングの楽しさを実感できる最も効果的な学習方法のひとつです。変数・関数・クラス・イベント処理などの重要な概念が自然と身につきます。

2. 機能一覧

  • 家計簿ダッシュボードのメイン機能
  • 直感的なGUIインターフェース
  • 入力値のバリデーション
  • エラーハンドリング
  • 結果の見やすい表示
  • クリア機能付き

3. 事前準備・環境

ℹ️
動作確認環境

Python 3.10 以上 / Windows・Mac・Linux すべて対応

以下の環境で動作確認しています。

  • Python 3.10 以上
  • OS: Windows 10/11・macOS 12+・Ubuntu 20.04+

インストールが必要なライブラリ

pip install matplotlib

4. 完全なソースコード

💡
コードのコピー方法

右上の「コピー」ボタンをクリックするとコードをクリップボードにコピーできます。

app081.py
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
import threading
from datetime import datetime, date, timedelta

try:
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    MATPLOTLIB_AVAILABLE = True
except ImportError:
    MATPLOTLIB_AVAILABLE = False

DB_PATH = os.path.join(os.path.dirname(__file__), "kakeibo.db")


class App081:
    """家計簿ダッシュボード"""

    CATEGORIES = ["食費", "交通費", "光熱費", "通信費", "娯楽", "医療",
                  "日用品", "衣服", "外食", "住居費", "教育", "貯蓄", "その他"]
    INCOME_CATS = ["給与", "副業", "ボーナス", "その他収入"]

    def __init__(self, root):
        self.root = root
        self.root.title("家計簿ダッシュボード")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._init_db()
        self._build_ui()
        self._load_month()

    def _init_db(self):
        conn = sqlite3.connect(DB_PATH)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS transactions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                date TEXT NOT NULL,
                type TEXT NOT NULL,
                category TEXT NOT NULL,
                amount INTEGER NOT NULL,
                memo TEXT DEFAULT ''
            )
        """)
        conn.commit()
        conn.close()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="💰 家計簿ダッシュボード",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        # 月選択
        nav_f = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        nav_f.pack(fill=tk.X)
        ttk.Button(nav_f, text="◀", command=self._prev_month).pack(side=tk.LEFT, padx=4)
        self.month_var = tk.StringVar(value=date.today().strftime("%Y-%m"))
        ttk.Entry(nav_f, textvariable=self.month_var, width=8).pack(side=tk.LEFT)
        ttk.Button(nav_f, text="▶", command=self._next_month).pack(side=tk.LEFT, padx=2)
        ttk.Button(nav_f, text="今月",
                   command=lambda: self._set_month(date.today().strftime("%Y-%m"))
                   ).pack(side=tk.LEFT, padx=4)
        ttk.Button(nav_f, text="▶ 読み込み",
                   command=self._load_month).pack(side=tk.LEFT, padx=4)

        # メイン PanedWindow
        paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        # 左: 入力フォーム + 一覧
        left = tk.Frame(paned, bg="#1e1e1e", width=380)
        paned.add(left, weight=0)

        # 入力フォーム
        form = tk.LabelFrame(left, text="収支入力", bg="#252526",
                              fg="#ccc", font=("Arial", 9), padx=6, pady=6)
        form.pack(fill=tk.X, padx=4, pady=4)

        tk.Label(form, text="日付:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=0, sticky="w")
        self.date_var = tk.StringVar(value=date.today().isoformat())
        ttk.Entry(form, textvariable=self.date_var, width=12).grid(row=0, column=1, padx=4)

        tk.Label(form, text="種別:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=2, sticky="w")
        self.type_var = tk.StringVar(value="支出")
        ttk.Combobox(form, textvariable=self.type_var,
                     values=["支出", "収入"],
                     state="readonly", width=6).grid(row=0, column=3, padx=4)
        self.type_var.trace_add("write", self._on_type_change)

        tk.Label(form, text="カテゴリ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=0, sticky="w", pady=4)
        self.cat_var = tk.StringVar(value="食費")
        self.cat_cb = ttk.Combobox(form, textvariable=self.cat_var,
                                    values=self.CATEGORIES,
                                    state="readonly", width=10)
        self.cat_cb.grid(row=1, column=1, padx=4)

        tk.Label(form, text="金額:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=2, sticky="w")
        self.amount_var = tk.IntVar(value=0)
        ttk.Entry(form, textvariable=self.amount_var, width=10).grid(row=1, column=3, padx=4)

        tk.Label(form, text="メモ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=2, column=0, sticky="w")
        self.memo_var = tk.StringVar()
        ttk.Entry(form, textvariable=self.memo_var, width=28).grid(
            row=2, column=1, columnspan=3, padx=4, sticky="ew", pady=4)

        btn_row = tk.Frame(form, bg="#252526")
        btn_row.grid(row=3, column=0, columnspan=4, pady=2)
        tk.Button(btn_row, text="+ 追加", command=self._add,
                  bg="#2e7d32", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#1b5e20", bd=0).pack(side=tk.LEFT, padx=4)
        tk.Button(btn_row, text="🗑 削除", command=self._delete,
                  bg="#c62828", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#b71c1c", bd=0).pack(side=tk.LEFT, padx=4)

        # 収支一覧
        tk.Label(left, text="明細一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w", padx=4)
        cols = ("date", "type", "category", "amount", "memo")
        self.tree = ttk.Treeview(left, columns=cols, show="headings", height=14)
        for col, text, width in [
            ("date",     "日付",     80),
            ("type",     "種別",     50),
            ("category", "カテゴリ", 70),
            ("amount",   "金額",     70),
            ("memo",     "メモ",    110),
        ]:
            self.tree.heading(col, text=text)
            self.tree.column(col, width=width, anchor="w")
        tsb = ttk.Scrollbar(left, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True, padx=(4, 0))
        self.tree.tag_configure("income",  foreground="#26a69a")
        self.tree.tag_configure("expense", foreground="#ef5350")

        # 右: サマリー + グラフ
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

        # サマリーカード
        summary_f = tk.Frame(right, bg="#1e1e1e")
        summary_f.pack(fill=tk.X, padx=4, pady=4)
        self._summary_labels = {}
        for key, label, color in [
            ("income",  "収入合計", "#26a69a"),
            ("expense", "支出合計", "#ef5350"),
            ("balance", "収支差額", "#4fc3f7"),
        ]:
            card = tk.Frame(summary_f, bg="#252526", padx=10, pady=8)
            card.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
            tk.Label(card, text=label, bg="#252526", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(card, text="¥0", bg="#252526", fg=color,
                           font=("Arial", 14, "bold"))
            lbl.pack()
            self._summary_labels[key] = lbl

        # グラフ
        if MATPLOTLIB_AVAILABLE:
            self.fig = Figure(figsize=(5, 3.5), facecolor="#1e1e1e")
            self.ax_pie  = self.fig.add_subplot(121)
            self.ax_bar  = self.fig.add_subplot(122)
            self.mpl_canvas = FigureCanvasTkAgg(self.fig, master=right)
            self.mpl_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=4)
        else:
            tk.Label(right, text="pip install matplotlib でグラフが表示されます",
                     bg="#1e1e1e", fg="#555").pack(expand=True)

        self.status_var = tk.StringVar(value="準備完了")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _on_type_change(self, *_):
        if self.type_var.get() == "収入":
            self.cat_cb["values"] = self.INCOME_CATS
            self.cat_var.set(self.INCOME_CATS[0])
        else:
            self.cat_cb["values"] = self.CATEGORIES
            self.cat_var.set(self.CATEGORIES[0])

    # ── DB操作 ───────────────────────────────────────────────
    def _add(self):
        try:
            amount = self.amount_var.get()
            if amount <= 0:
                raise ValueError("金額は正の整数で入力してください")
        except tk.TclError:
            messagebox.showerror("エラー", "金額を整数で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        conn.execute(
            "INSERT INTO transactions (date, type, category, amount, memo) VALUES (?,?,?,?,?)",
            (self.date_var.get(), self.type_var.get(),
             self.cat_var.get(), amount, self.memo_var.get()))
        conn.commit()
        conn.close()
        self.amount_var.set(0)
        self.memo_var.set("")
        self._load_month()

    def _delete(self):
        sel = self.tree.selection()
        if not sel:
            return
        row_id = self.tree.item(sel[0], "text")
        conn = sqlite3.connect(DB_PATH)
        conn.execute("DELETE FROM transactions WHERE id=?", (row_id,))
        conn.commit()
        conn.close()
        self._load_month()

    def _load_month(self):
        month = self.month_var.get().strip()
        try:
            y, m = month.split("-")
            start = f"{y}-{m:>02}-01"
            # 翌月1日
            nm = int(m) + 1
            ny = int(y)
            if nm > 12:
                nm = 1
                ny += 1
            end = f"{ny}-{nm:02d}-01"
        except Exception:
            messagebox.showerror("エラー", "月は YYYY-MM 形式で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        rows = conn.execute(
            "SELECT id, date, type, category, amount, memo "
            "FROM transactions WHERE date >= ? AND date < ? ORDER BY date",
            (start, end)).fetchall()
        conn.close()

        self.tree.delete(*self.tree.get_children())
        income = expense = 0
        cat_expense = {}
        daily_expense = {}
        for row_id, dt, rtype, cat, amt, memo in rows:
            tag = "income" if rtype == "収入" else "expense"
            self.tree.insert("", tk.END, text=row_id,
                              values=(dt, rtype, cat, f"¥{amt:,}", memo),
                              tags=(tag,))
            if rtype == "収入":
                income += amt
            else:
                expense += amt
                cat_expense[cat] = cat_expense.get(cat, 0) + amt
                daily_expense[dt] = daily_expense.get(dt, 0) + amt

        balance = income - expense
        self._summary_labels["income"].config(text=f"¥{income:,}")
        self._summary_labels["expense"].config(text=f"¥{expense:,}")
        color = "#26a69a" if balance >= 0 else "#ef5350"
        self._summary_labels["balance"].config(text=f"¥{balance:,}", fg=color)

        if MATPLOTLIB_AVAILABLE:
            self._draw_charts(cat_expense, daily_expense)
        self.status_var.set(f"{month}: 収入 ¥{income:,}  支出 ¥{expense:,}  差額 ¥{balance:,}")

    def _draw_charts(self, cat_expense, daily_expense):
        self.ax_pie.clear()
        self.ax_bar.clear()
        self.ax_pie.set_facecolor("#1e1e1e")
        self.ax_bar.set_facecolor("#1e1e1e")

        if cat_expense:
            labels = list(cat_expense.keys())
            vals   = list(cat_expense.values())
            self.ax_pie.pie(vals, labels=labels, autopct="%1.0f%%",
                             startangle=90, textprops={"fontsize": 6, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a", "#ffa726",
                                     "#ab47bc", "#66bb6a", "#ec407a", "#ff7043"])
            self.ax_pie.set_title("支出カテゴリ", color="#c9d1d9", fontsize=8)

        if daily_expense:
            dates  = sorted(daily_expense.keys())
            amounts = [daily_expense[d] for d in dates]
            day_labels = [d[5:] for d in dates]  # MM-DD
            self.ax_bar.bar(range(len(dates)), amounts, color="#4fc3f7")
            step = max(1, len(dates) // 6)
            self.ax_bar.set_xticks(range(0, len(dates), step))
            self.ax_bar.set_xticklabels(day_labels[::step], fontsize=6,
                                          color="#8b949e", rotation=30)
            self.ax_bar.set_title("日別支出", color="#c9d1d9", fontsize=8)
            self.ax_bar.tick_params(colors="#8b949e", labelsize=6)

        for ax in (self.ax_pie, self.ax_bar):
            for spine in ax.spines.values():
                spine.set_edgecolor("#30363d")

        self.fig.tight_layout(pad=1.5)
        self.mpl_canvas.draw()

    def _set_month(self, month_str):
        self.month_var.set(month_str)
        self._load_month()

    def _prev_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m -= 1
            if m < 1:
                m = 12
                y -= 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass

    def _next_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m += 1
            if m > 12:
                m = 1
                y += 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass


if __name__ == "__main__":
    root = tk.Tk()
    app = App081(root)
    root.mainloop()

5. コード解説

家計簿ダッシュボードのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。

クラス設計とコンストラクタ

App081クラスにアプリの全機能をまとめています。__init__でウィンドウ設定、_build_ui()でUI構築、process()でメイン処理を担当します。責任の分離により、コードが読みやすくなります。

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
import threading
from datetime import datetime, date, timedelta

try:
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    MATPLOTLIB_AVAILABLE = True
except ImportError:
    MATPLOTLIB_AVAILABLE = False

DB_PATH = os.path.join(os.path.dirname(__file__), "kakeibo.db")


class App081:
    """家計簿ダッシュボード"""

    CATEGORIES = ["食費", "交通費", "光熱費", "通信費", "娯楽", "医療",
                  "日用品", "衣服", "外食", "住居費", "教育", "貯蓄", "その他"]
    INCOME_CATS = ["給与", "副業", "ボーナス", "その他収入"]

    def __init__(self, root):
        self.root = root
        self.root.title("家計簿ダッシュボード")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._init_db()
        self._build_ui()
        self._load_month()

    def _init_db(self):
        conn = sqlite3.connect(DB_PATH)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS transactions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                date TEXT NOT NULL,
                type TEXT NOT NULL,
                category TEXT NOT NULL,
                amount INTEGER NOT NULL,
                memo TEXT DEFAULT ''
            )
        """)
        conn.commit()
        conn.close()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="💰 家計簿ダッシュボード",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        # 月選択
        nav_f = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        nav_f.pack(fill=tk.X)
        ttk.Button(nav_f, text="◀", command=self._prev_month).pack(side=tk.LEFT, padx=4)
        self.month_var = tk.StringVar(value=date.today().strftime("%Y-%m"))
        ttk.Entry(nav_f, textvariable=self.month_var, width=8).pack(side=tk.LEFT)
        ttk.Button(nav_f, text="▶", command=self._next_month).pack(side=tk.LEFT, padx=2)
        ttk.Button(nav_f, text="今月",
                   command=lambda: self._set_month(date.today().strftime("%Y-%m"))
                   ).pack(side=tk.LEFT, padx=4)
        ttk.Button(nav_f, text="▶ 読み込み",
                   command=self._load_month).pack(side=tk.LEFT, padx=4)

        # メイン PanedWindow
        paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        # 左: 入力フォーム + 一覧
        left = tk.Frame(paned, bg="#1e1e1e", width=380)
        paned.add(left, weight=0)

        # 入力フォーム
        form = tk.LabelFrame(left, text="収支入力", bg="#252526",
                              fg="#ccc", font=("Arial", 9), padx=6, pady=6)
        form.pack(fill=tk.X, padx=4, pady=4)

        tk.Label(form, text="日付:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=0, sticky="w")
        self.date_var = tk.StringVar(value=date.today().isoformat())
        ttk.Entry(form, textvariable=self.date_var, width=12).grid(row=0, column=1, padx=4)

        tk.Label(form, text="種別:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=2, sticky="w")
        self.type_var = tk.StringVar(value="支出")
        ttk.Combobox(form, textvariable=self.type_var,
                     values=["支出", "収入"],
                     state="readonly", width=6).grid(row=0, column=3, padx=4)
        self.type_var.trace_add("write", self._on_type_change)

        tk.Label(form, text="カテゴリ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=0, sticky="w", pady=4)
        self.cat_var = tk.StringVar(value="食費")
        self.cat_cb = ttk.Combobox(form, textvariable=self.cat_var,
                                    values=self.CATEGORIES,
                                    state="readonly", width=10)
        self.cat_cb.grid(row=1, column=1, padx=4)

        tk.Label(form, text="金額:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=2, sticky="w")
        self.amount_var = tk.IntVar(value=0)
        ttk.Entry(form, textvariable=self.amount_var, width=10).grid(row=1, column=3, padx=4)

        tk.Label(form, text="メモ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=2, column=0, sticky="w")
        self.memo_var = tk.StringVar()
        ttk.Entry(form, textvariable=self.memo_var, width=28).grid(
            row=2, column=1, columnspan=3, padx=4, sticky="ew", pady=4)

        btn_row = tk.Frame(form, bg="#252526")
        btn_row.grid(row=3, column=0, columnspan=4, pady=2)
        tk.Button(btn_row, text="+ 追加", command=self._add,
                  bg="#2e7d32", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#1b5e20", bd=0).pack(side=tk.LEFT, padx=4)
        tk.Button(btn_row, text="🗑 削除", command=self._delete,
                  bg="#c62828", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#b71c1c", bd=0).pack(side=tk.LEFT, padx=4)

        # 収支一覧
        tk.Label(left, text="明細一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w", padx=4)
        cols = ("date", "type", "category", "amount", "memo")
        self.tree = ttk.Treeview(left, columns=cols, show="headings", height=14)
        for col, text, width in [
            ("date",     "日付",     80),
            ("type",     "種別",     50),
            ("category", "カテゴリ", 70),
            ("amount",   "金額",     70),
            ("memo",     "メモ",    110),
        ]:
            self.tree.heading(col, text=text)
            self.tree.column(col, width=width, anchor="w")
        tsb = ttk.Scrollbar(left, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True, padx=(4, 0))
        self.tree.tag_configure("income",  foreground="#26a69a")
        self.tree.tag_configure("expense", foreground="#ef5350")

        # 右: サマリー + グラフ
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

        # サマリーカード
        summary_f = tk.Frame(right, bg="#1e1e1e")
        summary_f.pack(fill=tk.X, padx=4, pady=4)
        self._summary_labels = {}
        for key, label, color in [
            ("income",  "収入合計", "#26a69a"),
            ("expense", "支出合計", "#ef5350"),
            ("balance", "収支差額", "#4fc3f7"),
        ]:
            card = tk.Frame(summary_f, bg="#252526", padx=10, pady=8)
            card.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
            tk.Label(card, text=label, bg="#252526", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(card, text="¥0", bg="#252526", fg=color,
                           font=("Arial", 14, "bold"))
            lbl.pack()
            self._summary_labels[key] = lbl

        # グラフ
        if MATPLOTLIB_AVAILABLE:
            self.fig = Figure(figsize=(5, 3.5), facecolor="#1e1e1e")
            self.ax_pie  = self.fig.add_subplot(121)
            self.ax_bar  = self.fig.add_subplot(122)
            self.mpl_canvas = FigureCanvasTkAgg(self.fig, master=right)
            self.mpl_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=4)
        else:
            tk.Label(right, text="pip install matplotlib でグラフが表示されます",
                     bg="#1e1e1e", fg="#555").pack(expand=True)

        self.status_var = tk.StringVar(value="準備完了")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _on_type_change(self, *_):
        if self.type_var.get() == "収入":
            self.cat_cb["values"] = self.INCOME_CATS
            self.cat_var.set(self.INCOME_CATS[0])
        else:
            self.cat_cb["values"] = self.CATEGORIES
            self.cat_var.set(self.CATEGORIES[0])

    # ── DB操作 ───────────────────────────────────────────────
    def _add(self):
        try:
            amount = self.amount_var.get()
            if amount <= 0:
                raise ValueError("金額は正の整数で入力してください")
        except tk.TclError:
            messagebox.showerror("エラー", "金額を整数で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        conn.execute(
            "INSERT INTO transactions (date, type, category, amount, memo) VALUES (?,?,?,?,?)",
            (self.date_var.get(), self.type_var.get(),
             self.cat_var.get(), amount, self.memo_var.get()))
        conn.commit()
        conn.close()
        self.amount_var.set(0)
        self.memo_var.set("")
        self._load_month()

    def _delete(self):
        sel = self.tree.selection()
        if not sel:
            return
        row_id = self.tree.item(sel[0], "text")
        conn = sqlite3.connect(DB_PATH)
        conn.execute("DELETE FROM transactions WHERE id=?", (row_id,))
        conn.commit()
        conn.close()
        self._load_month()

    def _load_month(self):
        month = self.month_var.get().strip()
        try:
            y, m = month.split("-")
            start = f"{y}-{m:>02}-01"
            # 翌月1日
            nm = int(m) + 1
            ny = int(y)
            if nm > 12:
                nm = 1
                ny += 1
            end = f"{ny}-{nm:02d}-01"
        except Exception:
            messagebox.showerror("エラー", "月は YYYY-MM 形式で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        rows = conn.execute(
            "SELECT id, date, type, category, amount, memo "
            "FROM transactions WHERE date >= ? AND date < ? ORDER BY date",
            (start, end)).fetchall()
        conn.close()

        self.tree.delete(*self.tree.get_children())
        income = expense = 0
        cat_expense = {}
        daily_expense = {}
        for row_id, dt, rtype, cat, amt, memo in rows:
            tag = "income" if rtype == "収入" else "expense"
            self.tree.insert("", tk.END, text=row_id,
                              values=(dt, rtype, cat, f"¥{amt:,}", memo),
                              tags=(tag,))
            if rtype == "収入":
                income += amt
            else:
                expense += amt
                cat_expense[cat] = cat_expense.get(cat, 0) + amt
                daily_expense[dt] = daily_expense.get(dt, 0) + amt

        balance = income - expense
        self._summary_labels["income"].config(text=f"¥{income:,}")
        self._summary_labels["expense"].config(text=f"¥{expense:,}")
        color = "#26a69a" if balance >= 0 else "#ef5350"
        self._summary_labels["balance"].config(text=f"¥{balance:,}", fg=color)

        if MATPLOTLIB_AVAILABLE:
            self._draw_charts(cat_expense, daily_expense)
        self.status_var.set(f"{month}: 収入 ¥{income:,}  支出 ¥{expense:,}  差額 ¥{balance:,}")

    def _draw_charts(self, cat_expense, daily_expense):
        self.ax_pie.clear()
        self.ax_bar.clear()
        self.ax_pie.set_facecolor("#1e1e1e")
        self.ax_bar.set_facecolor("#1e1e1e")

        if cat_expense:
            labels = list(cat_expense.keys())
            vals   = list(cat_expense.values())
            self.ax_pie.pie(vals, labels=labels, autopct="%1.0f%%",
                             startangle=90, textprops={"fontsize": 6, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a", "#ffa726",
                                     "#ab47bc", "#66bb6a", "#ec407a", "#ff7043"])
            self.ax_pie.set_title("支出カテゴリ", color="#c9d1d9", fontsize=8)

        if daily_expense:
            dates  = sorted(daily_expense.keys())
            amounts = [daily_expense[d] for d in dates]
            day_labels = [d[5:] for d in dates]  # MM-DD
            self.ax_bar.bar(range(len(dates)), amounts, color="#4fc3f7")
            step = max(1, len(dates) // 6)
            self.ax_bar.set_xticks(range(0, len(dates), step))
            self.ax_bar.set_xticklabels(day_labels[::step], fontsize=6,
                                          color="#8b949e", rotation=30)
            self.ax_bar.set_title("日別支出", color="#c9d1d9", fontsize=8)
            self.ax_bar.tick_params(colors="#8b949e", labelsize=6)

        for ax in (self.ax_pie, self.ax_bar):
            for spine in ax.spines.values():
                spine.set_edgecolor("#30363d")

        self.fig.tight_layout(pad=1.5)
        self.mpl_canvas.draw()

    def _set_month(self, month_str):
        self.month_var.set(month_str)
        self._load_month()

    def _prev_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m -= 1
            if m < 1:
                m = 12
                y -= 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass

    def _next_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m += 1
            if m > 12:
                m = 1
                y += 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass


if __name__ == "__main__":
    root = tk.Tk()
    app = App081(root)
    root.mainloop()

UIレイアウトの構築

LabelFrameで入力エリアと結果エリアを視覚的に分けています。pack()で縦に並べ、expand=Trueで結果エリアが画面いっぱいに広がるよう設定しています。

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
import threading
from datetime import datetime, date, timedelta

try:
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    MATPLOTLIB_AVAILABLE = True
except ImportError:
    MATPLOTLIB_AVAILABLE = False

DB_PATH = os.path.join(os.path.dirname(__file__), "kakeibo.db")


class App081:
    """家計簿ダッシュボード"""

    CATEGORIES = ["食費", "交通費", "光熱費", "通信費", "娯楽", "医療",
                  "日用品", "衣服", "外食", "住居費", "教育", "貯蓄", "その他"]
    INCOME_CATS = ["給与", "副業", "ボーナス", "その他収入"]

    def __init__(self, root):
        self.root = root
        self.root.title("家計簿ダッシュボード")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._init_db()
        self._build_ui()
        self._load_month()

    def _init_db(self):
        conn = sqlite3.connect(DB_PATH)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS transactions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                date TEXT NOT NULL,
                type TEXT NOT NULL,
                category TEXT NOT NULL,
                amount INTEGER NOT NULL,
                memo TEXT DEFAULT ''
            )
        """)
        conn.commit()
        conn.close()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="💰 家計簿ダッシュボード",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        # 月選択
        nav_f = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        nav_f.pack(fill=tk.X)
        ttk.Button(nav_f, text="◀", command=self._prev_month).pack(side=tk.LEFT, padx=4)
        self.month_var = tk.StringVar(value=date.today().strftime("%Y-%m"))
        ttk.Entry(nav_f, textvariable=self.month_var, width=8).pack(side=tk.LEFT)
        ttk.Button(nav_f, text="▶", command=self._next_month).pack(side=tk.LEFT, padx=2)
        ttk.Button(nav_f, text="今月",
                   command=lambda: self._set_month(date.today().strftime("%Y-%m"))
                   ).pack(side=tk.LEFT, padx=4)
        ttk.Button(nav_f, text="▶ 読み込み",
                   command=self._load_month).pack(side=tk.LEFT, padx=4)

        # メイン PanedWindow
        paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        # 左: 入力フォーム + 一覧
        left = tk.Frame(paned, bg="#1e1e1e", width=380)
        paned.add(left, weight=0)

        # 入力フォーム
        form = tk.LabelFrame(left, text="収支入力", bg="#252526",
                              fg="#ccc", font=("Arial", 9), padx=6, pady=6)
        form.pack(fill=tk.X, padx=4, pady=4)

        tk.Label(form, text="日付:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=0, sticky="w")
        self.date_var = tk.StringVar(value=date.today().isoformat())
        ttk.Entry(form, textvariable=self.date_var, width=12).grid(row=0, column=1, padx=4)

        tk.Label(form, text="種別:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=2, sticky="w")
        self.type_var = tk.StringVar(value="支出")
        ttk.Combobox(form, textvariable=self.type_var,
                     values=["支出", "収入"],
                     state="readonly", width=6).grid(row=0, column=3, padx=4)
        self.type_var.trace_add("write", self._on_type_change)

        tk.Label(form, text="カテゴリ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=0, sticky="w", pady=4)
        self.cat_var = tk.StringVar(value="食費")
        self.cat_cb = ttk.Combobox(form, textvariable=self.cat_var,
                                    values=self.CATEGORIES,
                                    state="readonly", width=10)
        self.cat_cb.grid(row=1, column=1, padx=4)

        tk.Label(form, text="金額:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=2, sticky="w")
        self.amount_var = tk.IntVar(value=0)
        ttk.Entry(form, textvariable=self.amount_var, width=10).grid(row=1, column=3, padx=4)

        tk.Label(form, text="メモ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=2, column=0, sticky="w")
        self.memo_var = tk.StringVar()
        ttk.Entry(form, textvariable=self.memo_var, width=28).grid(
            row=2, column=1, columnspan=3, padx=4, sticky="ew", pady=4)

        btn_row = tk.Frame(form, bg="#252526")
        btn_row.grid(row=3, column=0, columnspan=4, pady=2)
        tk.Button(btn_row, text="+ 追加", command=self._add,
                  bg="#2e7d32", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#1b5e20", bd=0).pack(side=tk.LEFT, padx=4)
        tk.Button(btn_row, text="🗑 削除", command=self._delete,
                  bg="#c62828", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#b71c1c", bd=0).pack(side=tk.LEFT, padx=4)

        # 収支一覧
        tk.Label(left, text="明細一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w", padx=4)
        cols = ("date", "type", "category", "amount", "memo")
        self.tree = ttk.Treeview(left, columns=cols, show="headings", height=14)
        for col, text, width in [
            ("date",     "日付",     80),
            ("type",     "種別",     50),
            ("category", "カテゴリ", 70),
            ("amount",   "金額",     70),
            ("memo",     "メモ",    110),
        ]:
            self.tree.heading(col, text=text)
            self.tree.column(col, width=width, anchor="w")
        tsb = ttk.Scrollbar(left, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True, padx=(4, 0))
        self.tree.tag_configure("income",  foreground="#26a69a")
        self.tree.tag_configure("expense", foreground="#ef5350")

        # 右: サマリー + グラフ
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

        # サマリーカード
        summary_f = tk.Frame(right, bg="#1e1e1e")
        summary_f.pack(fill=tk.X, padx=4, pady=4)
        self._summary_labels = {}
        for key, label, color in [
            ("income",  "収入合計", "#26a69a"),
            ("expense", "支出合計", "#ef5350"),
            ("balance", "収支差額", "#4fc3f7"),
        ]:
            card = tk.Frame(summary_f, bg="#252526", padx=10, pady=8)
            card.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
            tk.Label(card, text=label, bg="#252526", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(card, text="¥0", bg="#252526", fg=color,
                           font=("Arial", 14, "bold"))
            lbl.pack()
            self._summary_labels[key] = lbl

        # グラフ
        if MATPLOTLIB_AVAILABLE:
            self.fig = Figure(figsize=(5, 3.5), facecolor="#1e1e1e")
            self.ax_pie  = self.fig.add_subplot(121)
            self.ax_bar  = self.fig.add_subplot(122)
            self.mpl_canvas = FigureCanvasTkAgg(self.fig, master=right)
            self.mpl_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=4)
        else:
            tk.Label(right, text="pip install matplotlib でグラフが表示されます",
                     bg="#1e1e1e", fg="#555").pack(expand=True)

        self.status_var = tk.StringVar(value="準備完了")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _on_type_change(self, *_):
        if self.type_var.get() == "収入":
            self.cat_cb["values"] = self.INCOME_CATS
            self.cat_var.set(self.INCOME_CATS[0])
        else:
            self.cat_cb["values"] = self.CATEGORIES
            self.cat_var.set(self.CATEGORIES[0])

    # ── DB操作 ───────────────────────────────────────────────
    def _add(self):
        try:
            amount = self.amount_var.get()
            if amount <= 0:
                raise ValueError("金額は正の整数で入力してください")
        except tk.TclError:
            messagebox.showerror("エラー", "金額を整数で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        conn.execute(
            "INSERT INTO transactions (date, type, category, amount, memo) VALUES (?,?,?,?,?)",
            (self.date_var.get(), self.type_var.get(),
             self.cat_var.get(), amount, self.memo_var.get()))
        conn.commit()
        conn.close()
        self.amount_var.set(0)
        self.memo_var.set("")
        self._load_month()

    def _delete(self):
        sel = self.tree.selection()
        if not sel:
            return
        row_id = self.tree.item(sel[0], "text")
        conn = sqlite3.connect(DB_PATH)
        conn.execute("DELETE FROM transactions WHERE id=?", (row_id,))
        conn.commit()
        conn.close()
        self._load_month()

    def _load_month(self):
        month = self.month_var.get().strip()
        try:
            y, m = month.split("-")
            start = f"{y}-{m:>02}-01"
            # 翌月1日
            nm = int(m) + 1
            ny = int(y)
            if nm > 12:
                nm = 1
                ny += 1
            end = f"{ny}-{nm:02d}-01"
        except Exception:
            messagebox.showerror("エラー", "月は YYYY-MM 形式で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        rows = conn.execute(
            "SELECT id, date, type, category, amount, memo "
            "FROM transactions WHERE date >= ? AND date < ? ORDER BY date",
            (start, end)).fetchall()
        conn.close()

        self.tree.delete(*self.tree.get_children())
        income = expense = 0
        cat_expense = {}
        daily_expense = {}
        for row_id, dt, rtype, cat, amt, memo in rows:
            tag = "income" if rtype == "収入" else "expense"
            self.tree.insert("", tk.END, text=row_id,
                              values=(dt, rtype, cat, f"¥{amt:,}", memo),
                              tags=(tag,))
            if rtype == "収入":
                income += amt
            else:
                expense += amt
                cat_expense[cat] = cat_expense.get(cat, 0) + amt
                daily_expense[dt] = daily_expense.get(dt, 0) + amt

        balance = income - expense
        self._summary_labels["income"].config(text=f"¥{income:,}")
        self._summary_labels["expense"].config(text=f"¥{expense:,}")
        color = "#26a69a" if balance >= 0 else "#ef5350"
        self._summary_labels["balance"].config(text=f"¥{balance:,}", fg=color)

        if MATPLOTLIB_AVAILABLE:
            self._draw_charts(cat_expense, daily_expense)
        self.status_var.set(f"{month}: 収入 ¥{income:,}  支出 ¥{expense:,}  差額 ¥{balance:,}")

    def _draw_charts(self, cat_expense, daily_expense):
        self.ax_pie.clear()
        self.ax_bar.clear()
        self.ax_pie.set_facecolor("#1e1e1e")
        self.ax_bar.set_facecolor("#1e1e1e")

        if cat_expense:
            labels = list(cat_expense.keys())
            vals   = list(cat_expense.values())
            self.ax_pie.pie(vals, labels=labels, autopct="%1.0f%%",
                             startangle=90, textprops={"fontsize": 6, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a", "#ffa726",
                                     "#ab47bc", "#66bb6a", "#ec407a", "#ff7043"])
            self.ax_pie.set_title("支出カテゴリ", color="#c9d1d9", fontsize=8)

        if daily_expense:
            dates  = sorted(daily_expense.keys())
            amounts = [daily_expense[d] for d in dates]
            day_labels = [d[5:] for d in dates]  # MM-DD
            self.ax_bar.bar(range(len(dates)), amounts, color="#4fc3f7")
            step = max(1, len(dates) // 6)
            self.ax_bar.set_xticks(range(0, len(dates), step))
            self.ax_bar.set_xticklabels(day_labels[::step], fontsize=6,
                                          color="#8b949e", rotation=30)
            self.ax_bar.set_title("日別支出", color="#c9d1d9", fontsize=8)
            self.ax_bar.tick_params(colors="#8b949e", labelsize=6)

        for ax in (self.ax_pie, self.ax_bar):
            for spine in ax.spines.values():
                spine.set_edgecolor("#30363d")

        self.fig.tight_layout(pad=1.5)
        self.mpl_canvas.draw()

    def _set_month(self, month_str):
        self.month_var.set(month_str)
        self._load_month()

    def _prev_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m -= 1
            if m < 1:
                m = 12
                y -= 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass

    def _next_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m += 1
            if m > 12:
                m = 1
                y += 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass


if __name__ == "__main__":
    root = tk.Tk()
    app = App081(root)
    root.mainloop()

イベント処理

ボタンのcommand引数でクリックイベントを、bind('')でEnterキーイベントを処理します。どちらの操作でも同じprocess()が呼ばれ、コードの重複を避けられます。

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
import threading
from datetime import datetime, date, timedelta

try:
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    MATPLOTLIB_AVAILABLE = True
except ImportError:
    MATPLOTLIB_AVAILABLE = False

DB_PATH = os.path.join(os.path.dirname(__file__), "kakeibo.db")


class App081:
    """家計簿ダッシュボード"""

    CATEGORIES = ["食費", "交通費", "光熱費", "通信費", "娯楽", "医療",
                  "日用品", "衣服", "外食", "住居費", "教育", "貯蓄", "その他"]
    INCOME_CATS = ["給与", "副業", "ボーナス", "その他収入"]

    def __init__(self, root):
        self.root = root
        self.root.title("家計簿ダッシュボード")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._init_db()
        self._build_ui()
        self._load_month()

    def _init_db(self):
        conn = sqlite3.connect(DB_PATH)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS transactions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                date TEXT NOT NULL,
                type TEXT NOT NULL,
                category TEXT NOT NULL,
                amount INTEGER NOT NULL,
                memo TEXT DEFAULT ''
            )
        """)
        conn.commit()
        conn.close()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="💰 家計簿ダッシュボード",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        # 月選択
        nav_f = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        nav_f.pack(fill=tk.X)
        ttk.Button(nav_f, text="◀", command=self._prev_month).pack(side=tk.LEFT, padx=4)
        self.month_var = tk.StringVar(value=date.today().strftime("%Y-%m"))
        ttk.Entry(nav_f, textvariable=self.month_var, width=8).pack(side=tk.LEFT)
        ttk.Button(nav_f, text="▶", command=self._next_month).pack(side=tk.LEFT, padx=2)
        ttk.Button(nav_f, text="今月",
                   command=lambda: self._set_month(date.today().strftime("%Y-%m"))
                   ).pack(side=tk.LEFT, padx=4)
        ttk.Button(nav_f, text="▶ 読み込み",
                   command=self._load_month).pack(side=tk.LEFT, padx=4)

        # メイン PanedWindow
        paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        # 左: 入力フォーム + 一覧
        left = tk.Frame(paned, bg="#1e1e1e", width=380)
        paned.add(left, weight=0)

        # 入力フォーム
        form = tk.LabelFrame(left, text="収支入力", bg="#252526",
                              fg="#ccc", font=("Arial", 9), padx=6, pady=6)
        form.pack(fill=tk.X, padx=4, pady=4)

        tk.Label(form, text="日付:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=0, sticky="w")
        self.date_var = tk.StringVar(value=date.today().isoformat())
        ttk.Entry(form, textvariable=self.date_var, width=12).grid(row=0, column=1, padx=4)

        tk.Label(form, text="種別:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=2, sticky="w")
        self.type_var = tk.StringVar(value="支出")
        ttk.Combobox(form, textvariable=self.type_var,
                     values=["支出", "収入"],
                     state="readonly", width=6).grid(row=0, column=3, padx=4)
        self.type_var.trace_add("write", self._on_type_change)

        tk.Label(form, text="カテゴリ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=0, sticky="w", pady=4)
        self.cat_var = tk.StringVar(value="食費")
        self.cat_cb = ttk.Combobox(form, textvariable=self.cat_var,
                                    values=self.CATEGORIES,
                                    state="readonly", width=10)
        self.cat_cb.grid(row=1, column=1, padx=4)

        tk.Label(form, text="金額:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=2, sticky="w")
        self.amount_var = tk.IntVar(value=0)
        ttk.Entry(form, textvariable=self.amount_var, width=10).grid(row=1, column=3, padx=4)

        tk.Label(form, text="メモ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=2, column=0, sticky="w")
        self.memo_var = tk.StringVar()
        ttk.Entry(form, textvariable=self.memo_var, width=28).grid(
            row=2, column=1, columnspan=3, padx=4, sticky="ew", pady=4)

        btn_row = tk.Frame(form, bg="#252526")
        btn_row.grid(row=3, column=0, columnspan=4, pady=2)
        tk.Button(btn_row, text="+ 追加", command=self._add,
                  bg="#2e7d32", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#1b5e20", bd=0).pack(side=tk.LEFT, padx=4)
        tk.Button(btn_row, text="🗑 削除", command=self._delete,
                  bg="#c62828", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#b71c1c", bd=0).pack(side=tk.LEFT, padx=4)

        # 収支一覧
        tk.Label(left, text="明細一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w", padx=4)
        cols = ("date", "type", "category", "amount", "memo")
        self.tree = ttk.Treeview(left, columns=cols, show="headings", height=14)
        for col, text, width in [
            ("date",     "日付",     80),
            ("type",     "種別",     50),
            ("category", "カテゴリ", 70),
            ("amount",   "金額",     70),
            ("memo",     "メモ",    110),
        ]:
            self.tree.heading(col, text=text)
            self.tree.column(col, width=width, anchor="w")
        tsb = ttk.Scrollbar(left, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True, padx=(4, 0))
        self.tree.tag_configure("income",  foreground="#26a69a")
        self.tree.tag_configure("expense", foreground="#ef5350")

        # 右: サマリー + グラフ
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

        # サマリーカード
        summary_f = tk.Frame(right, bg="#1e1e1e")
        summary_f.pack(fill=tk.X, padx=4, pady=4)
        self._summary_labels = {}
        for key, label, color in [
            ("income",  "収入合計", "#26a69a"),
            ("expense", "支出合計", "#ef5350"),
            ("balance", "収支差額", "#4fc3f7"),
        ]:
            card = tk.Frame(summary_f, bg="#252526", padx=10, pady=8)
            card.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
            tk.Label(card, text=label, bg="#252526", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(card, text="¥0", bg="#252526", fg=color,
                           font=("Arial", 14, "bold"))
            lbl.pack()
            self._summary_labels[key] = lbl

        # グラフ
        if MATPLOTLIB_AVAILABLE:
            self.fig = Figure(figsize=(5, 3.5), facecolor="#1e1e1e")
            self.ax_pie  = self.fig.add_subplot(121)
            self.ax_bar  = self.fig.add_subplot(122)
            self.mpl_canvas = FigureCanvasTkAgg(self.fig, master=right)
            self.mpl_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=4)
        else:
            tk.Label(right, text="pip install matplotlib でグラフが表示されます",
                     bg="#1e1e1e", fg="#555").pack(expand=True)

        self.status_var = tk.StringVar(value="準備完了")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _on_type_change(self, *_):
        if self.type_var.get() == "収入":
            self.cat_cb["values"] = self.INCOME_CATS
            self.cat_var.set(self.INCOME_CATS[0])
        else:
            self.cat_cb["values"] = self.CATEGORIES
            self.cat_var.set(self.CATEGORIES[0])

    # ── DB操作 ───────────────────────────────────────────────
    def _add(self):
        try:
            amount = self.amount_var.get()
            if amount <= 0:
                raise ValueError("金額は正の整数で入力してください")
        except tk.TclError:
            messagebox.showerror("エラー", "金額を整数で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        conn.execute(
            "INSERT INTO transactions (date, type, category, amount, memo) VALUES (?,?,?,?,?)",
            (self.date_var.get(), self.type_var.get(),
             self.cat_var.get(), amount, self.memo_var.get()))
        conn.commit()
        conn.close()
        self.amount_var.set(0)
        self.memo_var.set("")
        self._load_month()

    def _delete(self):
        sel = self.tree.selection()
        if not sel:
            return
        row_id = self.tree.item(sel[0], "text")
        conn = sqlite3.connect(DB_PATH)
        conn.execute("DELETE FROM transactions WHERE id=?", (row_id,))
        conn.commit()
        conn.close()
        self._load_month()

    def _load_month(self):
        month = self.month_var.get().strip()
        try:
            y, m = month.split("-")
            start = f"{y}-{m:>02}-01"
            # 翌月1日
            nm = int(m) + 1
            ny = int(y)
            if nm > 12:
                nm = 1
                ny += 1
            end = f"{ny}-{nm:02d}-01"
        except Exception:
            messagebox.showerror("エラー", "月は YYYY-MM 形式で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        rows = conn.execute(
            "SELECT id, date, type, category, amount, memo "
            "FROM transactions WHERE date >= ? AND date < ? ORDER BY date",
            (start, end)).fetchall()
        conn.close()

        self.tree.delete(*self.tree.get_children())
        income = expense = 0
        cat_expense = {}
        daily_expense = {}
        for row_id, dt, rtype, cat, amt, memo in rows:
            tag = "income" if rtype == "収入" else "expense"
            self.tree.insert("", tk.END, text=row_id,
                              values=(dt, rtype, cat, f"¥{amt:,}", memo),
                              tags=(tag,))
            if rtype == "収入":
                income += amt
            else:
                expense += amt
                cat_expense[cat] = cat_expense.get(cat, 0) + amt
                daily_expense[dt] = daily_expense.get(dt, 0) + amt

        balance = income - expense
        self._summary_labels["income"].config(text=f"¥{income:,}")
        self._summary_labels["expense"].config(text=f"¥{expense:,}")
        color = "#26a69a" if balance >= 0 else "#ef5350"
        self._summary_labels["balance"].config(text=f"¥{balance:,}", fg=color)

        if MATPLOTLIB_AVAILABLE:
            self._draw_charts(cat_expense, daily_expense)
        self.status_var.set(f"{month}: 収入 ¥{income:,}  支出 ¥{expense:,}  差額 ¥{balance:,}")

    def _draw_charts(self, cat_expense, daily_expense):
        self.ax_pie.clear()
        self.ax_bar.clear()
        self.ax_pie.set_facecolor("#1e1e1e")
        self.ax_bar.set_facecolor("#1e1e1e")

        if cat_expense:
            labels = list(cat_expense.keys())
            vals   = list(cat_expense.values())
            self.ax_pie.pie(vals, labels=labels, autopct="%1.0f%%",
                             startangle=90, textprops={"fontsize": 6, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a", "#ffa726",
                                     "#ab47bc", "#66bb6a", "#ec407a", "#ff7043"])
            self.ax_pie.set_title("支出カテゴリ", color="#c9d1d9", fontsize=8)

        if daily_expense:
            dates  = sorted(daily_expense.keys())
            amounts = [daily_expense[d] for d in dates]
            day_labels = [d[5:] for d in dates]  # MM-DD
            self.ax_bar.bar(range(len(dates)), amounts, color="#4fc3f7")
            step = max(1, len(dates) // 6)
            self.ax_bar.set_xticks(range(0, len(dates), step))
            self.ax_bar.set_xticklabels(day_labels[::step], fontsize=6,
                                          color="#8b949e", rotation=30)
            self.ax_bar.set_title("日別支出", color="#c9d1d9", fontsize=8)
            self.ax_bar.tick_params(colors="#8b949e", labelsize=6)

        for ax in (self.ax_pie, self.ax_bar):
            for spine in ax.spines.values():
                spine.set_edgecolor("#30363d")

        self.fig.tight_layout(pad=1.5)
        self.mpl_canvas.draw()

    def _set_month(self, month_str):
        self.month_var.set(month_str)
        self._load_month()

    def _prev_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m -= 1
            if m < 1:
                m = 12
                y -= 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass

    def _next_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m += 1
            if m > 12:
                m = 1
                y += 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass


if __name__ == "__main__":
    root = tk.Tk()
    app = App081(root)
    root.mainloop()

Textウィジェットでの結果表示

tk.Textウィジェットをstate=DISABLED(読み取り専用)で作成し、更新時はNORMALに変更してinsert()で内容を書き込み、再びDISABLEDに戻します。

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
import threading
from datetime import datetime, date, timedelta

try:
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    MATPLOTLIB_AVAILABLE = True
except ImportError:
    MATPLOTLIB_AVAILABLE = False

DB_PATH = os.path.join(os.path.dirname(__file__), "kakeibo.db")


class App081:
    """家計簿ダッシュボード"""

    CATEGORIES = ["食費", "交通費", "光熱費", "通信費", "娯楽", "医療",
                  "日用品", "衣服", "外食", "住居費", "教育", "貯蓄", "その他"]
    INCOME_CATS = ["給与", "副業", "ボーナス", "その他収入"]

    def __init__(self, root):
        self.root = root
        self.root.title("家計簿ダッシュボード")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._init_db()
        self._build_ui()
        self._load_month()

    def _init_db(self):
        conn = sqlite3.connect(DB_PATH)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS transactions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                date TEXT NOT NULL,
                type TEXT NOT NULL,
                category TEXT NOT NULL,
                amount INTEGER NOT NULL,
                memo TEXT DEFAULT ''
            )
        """)
        conn.commit()
        conn.close()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="💰 家計簿ダッシュボード",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        # 月選択
        nav_f = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        nav_f.pack(fill=tk.X)
        ttk.Button(nav_f, text="◀", command=self._prev_month).pack(side=tk.LEFT, padx=4)
        self.month_var = tk.StringVar(value=date.today().strftime("%Y-%m"))
        ttk.Entry(nav_f, textvariable=self.month_var, width=8).pack(side=tk.LEFT)
        ttk.Button(nav_f, text="▶", command=self._next_month).pack(side=tk.LEFT, padx=2)
        ttk.Button(nav_f, text="今月",
                   command=lambda: self._set_month(date.today().strftime("%Y-%m"))
                   ).pack(side=tk.LEFT, padx=4)
        ttk.Button(nav_f, text="▶ 読み込み",
                   command=self._load_month).pack(side=tk.LEFT, padx=4)

        # メイン PanedWindow
        paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        # 左: 入力フォーム + 一覧
        left = tk.Frame(paned, bg="#1e1e1e", width=380)
        paned.add(left, weight=0)

        # 入力フォーム
        form = tk.LabelFrame(left, text="収支入力", bg="#252526",
                              fg="#ccc", font=("Arial", 9), padx=6, pady=6)
        form.pack(fill=tk.X, padx=4, pady=4)

        tk.Label(form, text="日付:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=0, sticky="w")
        self.date_var = tk.StringVar(value=date.today().isoformat())
        ttk.Entry(form, textvariable=self.date_var, width=12).grid(row=0, column=1, padx=4)

        tk.Label(form, text="種別:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=2, sticky="w")
        self.type_var = tk.StringVar(value="支出")
        ttk.Combobox(form, textvariable=self.type_var,
                     values=["支出", "収入"],
                     state="readonly", width=6).grid(row=0, column=3, padx=4)
        self.type_var.trace_add("write", self._on_type_change)

        tk.Label(form, text="カテゴリ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=0, sticky="w", pady=4)
        self.cat_var = tk.StringVar(value="食費")
        self.cat_cb = ttk.Combobox(form, textvariable=self.cat_var,
                                    values=self.CATEGORIES,
                                    state="readonly", width=10)
        self.cat_cb.grid(row=1, column=1, padx=4)

        tk.Label(form, text="金額:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=2, sticky="w")
        self.amount_var = tk.IntVar(value=0)
        ttk.Entry(form, textvariable=self.amount_var, width=10).grid(row=1, column=3, padx=4)

        tk.Label(form, text="メモ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=2, column=0, sticky="w")
        self.memo_var = tk.StringVar()
        ttk.Entry(form, textvariable=self.memo_var, width=28).grid(
            row=2, column=1, columnspan=3, padx=4, sticky="ew", pady=4)

        btn_row = tk.Frame(form, bg="#252526")
        btn_row.grid(row=3, column=0, columnspan=4, pady=2)
        tk.Button(btn_row, text="+ 追加", command=self._add,
                  bg="#2e7d32", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#1b5e20", bd=0).pack(side=tk.LEFT, padx=4)
        tk.Button(btn_row, text="🗑 削除", command=self._delete,
                  bg="#c62828", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#b71c1c", bd=0).pack(side=tk.LEFT, padx=4)

        # 収支一覧
        tk.Label(left, text="明細一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w", padx=4)
        cols = ("date", "type", "category", "amount", "memo")
        self.tree = ttk.Treeview(left, columns=cols, show="headings", height=14)
        for col, text, width in [
            ("date",     "日付",     80),
            ("type",     "種別",     50),
            ("category", "カテゴリ", 70),
            ("amount",   "金額",     70),
            ("memo",     "メモ",    110),
        ]:
            self.tree.heading(col, text=text)
            self.tree.column(col, width=width, anchor="w")
        tsb = ttk.Scrollbar(left, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True, padx=(4, 0))
        self.tree.tag_configure("income",  foreground="#26a69a")
        self.tree.tag_configure("expense", foreground="#ef5350")

        # 右: サマリー + グラフ
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

        # サマリーカード
        summary_f = tk.Frame(right, bg="#1e1e1e")
        summary_f.pack(fill=tk.X, padx=4, pady=4)
        self._summary_labels = {}
        for key, label, color in [
            ("income",  "収入合計", "#26a69a"),
            ("expense", "支出合計", "#ef5350"),
            ("balance", "収支差額", "#4fc3f7"),
        ]:
            card = tk.Frame(summary_f, bg="#252526", padx=10, pady=8)
            card.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
            tk.Label(card, text=label, bg="#252526", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(card, text="¥0", bg="#252526", fg=color,
                           font=("Arial", 14, "bold"))
            lbl.pack()
            self._summary_labels[key] = lbl

        # グラフ
        if MATPLOTLIB_AVAILABLE:
            self.fig = Figure(figsize=(5, 3.5), facecolor="#1e1e1e")
            self.ax_pie  = self.fig.add_subplot(121)
            self.ax_bar  = self.fig.add_subplot(122)
            self.mpl_canvas = FigureCanvasTkAgg(self.fig, master=right)
            self.mpl_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=4)
        else:
            tk.Label(right, text="pip install matplotlib でグラフが表示されます",
                     bg="#1e1e1e", fg="#555").pack(expand=True)

        self.status_var = tk.StringVar(value="準備完了")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _on_type_change(self, *_):
        if self.type_var.get() == "収入":
            self.cat_cb["values"] = self.INCOME_CATS
            self.cat_var.set(self.INCOME_CATS[0])
        else:
            self.cat_cb["values"] = self.CATEGORIES
            self.cat_var.set(self.CATEGORIES[0])

    # ── DB操作 ───────────────────────────────────────────────
    def _add(self):
        try:
            amount = self.amount_var.get()
            if amount <= 0:
                raise ValueError("金額は正の整数で入力してください")
        except tk.TclError:
            messagebox.showerror("エラー", "金額を整数で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        conn.execute(
            "INSERT INTO transactions (date, type, category, amount, memo) VALUES (?,?,?,?,?)",
            (self.date_var.get(), self.type_var.get(),
             self.cat_var.get(), amount, self.memo_var.get()))
        conn.commit()
        conn.close()
        self.amount_var.set(0)
        self.memo_var.set("")
        self._load_month()

    def _delete(self):
        sel = self.tree.selection()
        if not sel:
            return
        row_id = self.tree.item(sel[0], "text")
        conn = sqlite3.connect(DB_PATH)
        conn.execute("DELETE FROM transactions WHERE id=?", (row_id,))
        conn.commit()
        conn.close()
        self._load_month()

    def _load_month(self):
        month = self.month_var.get().strip()
        try:
            y, m = month.split("-")
            start = f"{y}-{m:>02}-01"
            # 翌月1日
            nm = int(m) + 1
            ny = int(y)
            if nm > 12:
                nm = 1
                ny += 1
            end = f"{ny}-{nm:02d}-01"
        except Exception:
            messagebox.showerror("エラー", "月は YYYY-MM 形式で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        rows = conn.execute(
            "SELECT id, date, type, category, amount, memo "
            "FROM transactions WHERE date >= ? AND date < ? ORDER BY date",
            (start, end)).fetchall()
        conn.close()

        self.tree.delete(*self.tree.get_children())
        income = expense = 0
        cat_expense = {}
        daily_expense = {}
        for row_id, dt, rtype, cat, amt, memo in rows:
            tag = "income" if rtype == "収入" else "expense"
            self.tree.insert("", tk.END, text=row_id,
                              values=(dt, rtype, cat, f"¥{amt:,}", memo),
                              tags=(tag,))
            if rtype == "収入":
                income += amt
            else:
                expense += amt
                cat_expense[cat] = cat_expense.get(cat, 0) + amt
                daily_expense[dt] = daily_expense.get(dt, 0) + amt

        balance = income - expense
        self._summary_labels["income"].config(text=f"¥{income:,}")
        self._summary_labels["expense"].config(text=f"¥{expense:,}")
        color = "#26a69a" if balance >= 0 else "#ef5350"
        self._summary_labels["balance"].config(text=f"¥{balance:,}", fg=color)

        if MATPLOTLIB_AVAILABLE:
            self._draw_charts(cat_expense, daily_expense)
        self.status_var.set(f"{month}: 収入 ¥{income:,}  支出 ¥{expense:,}  差額 ¥{balance:,}")

    def _draw_charts(self, cat_expense, daily_expense):
        self.ax_pie.clear()
        self.ax_bar.clear()
        self.ax_pie.set_facecolor("#1e1e1e")
        self.ax_bar.set_facecolor("#1e1e1e")

        if cat_expense:
            labels = list(cat_expense.keys())
            vals   = list(cat_expense.values())
            self.ax_pie.pie(vals, labels=labels, autopct="%1.0f%%",
                             startangle=90, textprops={"fontsize": 6, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a", "#ffa726",
                                     "#ab47bc", "#66bb6a", "#ec407a", "#ff7043"])
            self.ax_pie.set_title("支出カテゴリ", color="#c9d1d9", fontsize=8)

        if daily_expense:
            dates  = sorted(daily_expense.keys())
            amounts = [daily_expense[d] for d in dates]
            day_labels = [d[5:] for d in dates]  # MM-DD
            self.ax_bar.bar(range(len(dates)), amounts, color="#4fc3f7")
            step = max(1, len(dates) // 6)
            self.ax_bar.set_xticks(range(0, len(dates), step))
            self.ax_bar.set_xticklabels(day_labels[::step], fontsize=6,
                                          color="#8b949e", rotation=30)
            self.ax_bar.set_title("日別支出", color="#c9d1d9", fontsize=8)
            self.ax_bar.tick_params(colors="#8b949e", labelsize=6)

        for ax in (self.ax_pie, self.ax_bar):
            for spine in ax.spines.values():
                spine.set_edgecolor("#30363d")

        self.fig.tight_layout(pad=1.5)
        self.mpl_canvas.draw()

    def _set_month(self, month_str):
        self.month_var.set(month_str)
        self._load_month()

    def _prev_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m -= 1
            if m < 1:
                m = 12
                y -= 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass

    def _next_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m += 1
            if m > 12:
                m = 1
                y += 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass


if __name__ == "__main__":
    root = tk.Tk()
    app = App081(root)
    root.mainloop()

例外処理とエラーハンドリング

try-exceptでValueErrorとExceptionを捕捉し、messagebox.showerror()でエラーメッセージを表示します。予期しないエラーも処理することで、アプリの堅牢性が向上します。

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
import threading
from datetime import datetime, date, timedelta

try:
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    MATPLOTLIB_AVAILABLE = True
except ImportError:
    MATPLOTLIB_AVAILABLE = False

DB_PATH = os.path.join(os.path.dirname(__file__), "kakeibo.db")


class App081:
    """家計簿ダッシュボード"""

    CATEGORIES = ["食費", "交通費", "光熱費", "通信費", "娯楽", "医療",
                  "日用品", "衣服", "外食", "住居費", "教育", "貯蓄", "その他"]
    INCOME_CATS = ["給与", "副業", "ボーナス", "その他収入"]

    def __init__(self, root):
        self.root = root
        self.root.title("家計簿ダッシュボード")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._init_db()
        self._build_ui()
        self._load_month()

    def _init_db(self):
        conn = sqlite3.connect(DB_PATH)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS transactions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                date TEXT NOT NULL,
                type TEXT NOT NULL,
                category TEXT NOT NULL,
                amount INTEGER NOT NULL,
                memo TEXT DEFAULT ''
            )
        """)
        conn.commit()
        conn.close()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="💰 家計簿ダッシュボード",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        # 月選択
        nav_f = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        nav_f.pack(fill=tk.X)
        ttk.Button(nav_f, text="◀", command=self._prev_month).pack(side=tk.LEFT, padx=4)
        self.month_var = tk.StringVar(value=date.today().strftime("%Y-%m"))
        ttk.Entry(nav_f, textvariable=self.month_var, width=8).pack(side=tk.LEFT)
        ttk.Button(nav_f, text="▶", command=self._next_month).pack(side=tk.LEFT, padx=2)
        ttk.Button(nav_f, text="今月",
                   command=lambda: self._set_month(date.today().strftime("%Y-%m"))
                   ).pack(side=tk.LEFT, padx=4)
        ttk.Button(nav_f, text="▶ 読み込み",
                   command=self._load_month).pack(side=tk.LEFT, padx=4)

        # メイン PanedWindow
        paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        # 左: 入力フォーム + 一覧
        left = tk.Frame(paned, bg="#1e1e1e", width=380)
        paned.add(left, weight=0)

        # 入力フォーム
        form = tk.LabelFrame(left, text="収支入力", bg="#252526",
                              fg="#ccc", font=("Arial", 9), padx=6, pady=6)
        form.pack(fill=tk.X, padx=4, pady=4)

        tk.Label(form, text="日付:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=0, sticky="w")
        self.date_var = tk.StringVar(value=date.today().isoformat())
        ttk.Entry(form, textvariable=self.date_var, width=12).grid(row=0, column=1, padx=4)

        tk.Label(form, text="種別:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=0, column=2, sticky="w")
        self.type_var = tk.StringVar(value="支出")
        ttk.Combobox(form, textvariable=self.type_var,
                     values=["支出", "収入"],
                     state="readonly", width=6).grid(row=0, column=3, padx=4)
        self.type_var.trace_add("write", self._on_type_change)

        tk.Label(form, text="カテゴリ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=0, sticky="w", pady=4)
        self.cat_var = tk.StringVar(value="食費")
        self.cat_cb = ttk.Combobox(form, textvariable=self.cat_var,
                                    values=self.CATEGORIES,
                                    state="readonly", width=10)
        self.cat_cb.grid(row=1, column=1, padx=4)

        tk.Label(form, text="金額:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=1, column=2, sticky="w")
        self.amount_var = tk.IntVar(value=0)
        ttk.Entry(form, textvariable=self.amount_var, width=10).grid(row=1, column=3, padx=4)

        tk.Label(form, text="メモ:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).grid(row=2, column=0, sticky="w")
        self.memo_var = tk.StringVar()
        ttk.Entry(form, textvariable=self.memo_var, width=28).grid(
            row=2, column=1, columnspan=3, padx=4, sticky="ew", pady=4)

        btn_row = tk.Frame(form, bg="#252526")
        btn_row.grid(row=3, column=0, columnspan=4, pady=2)
        tk.Button(btn_row, text="+ 追加", command=self._add,
                  bg="#2e7d32", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#1b5e20", bd=0).pack(side=tk.LEFT, padx=4)
        tk.Button(btn_row, text="🗑 削除", command=self._delete,
                  bg="#c62828", fg="white", relief=tk.FLAT,
                  font=("Arial", 10), padx=14, pady=4,
                  activebackground="#b71c1c", bd=0).pack(side=tk.LEFT, padx=4)

        # 収支一覧
        tk.Label(left, text="明細一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w", padx=4)
        cols = ("date", "type", "category", "amount", "memo")
        self.tree = ttk.Treeview(left, columns=cols, show="headings", height=14)
        for col, text, width in [
            ("date",     "日付",     80),
            ("type",     "種別",     50),
            ("category", "カテゴリ", 70),
            ("amount",   "金額",     70),
            ("memo",     "メモ",    110),
        ]:
            self.tree.heading(col, text=text)
            self.tree.column(col, width=width, anchor="w")
        tsb = ttk.Scrollbar(left, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True, padx=(4, 0))
        self.tree.tag_configure("income",  foreground="#26a69a")
        self.tree.tag_configure("expense", foreground="#ef5350")

        # 右: サマリー + グラフ
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

        # サマリーカード
        summary_f = tk.Frame(right, bg="#1e1e1e")
        summary_f.pack(fill=tk.X, padx=4, pady=4)
        self._summary_labels = {}
        for key, label, color in [
            ("income",  "収入合計", "#26a69a"),
            ("expense", "支出合計", "#ef5350"),
            ("balance", "収支差額", "#4fc3f7"),
        ]:
            card = tk.Frame(summary_f, bg="#252526", padx=10, pady=8)
            card.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
            tk.Label(card, text=label, bg="#252526", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(card, text="¥0", bg="#252526", fg=color,
                           font=("Arial", 14, "bold"))
            lbl.pack()
            self._summary_labels[key] = lbl

        # グラフ
        if MATPLOTLIB_AVAILABLE:
            self.fig = Figure(figsize=(5, 3.5), facecolor="#1e1e1e")
            self.ax_pie  = self.fig.add_subplot(121)
            self.ax_bar  = self.fig.add_subplot(122)
            self.mpl_canvas = FigureCanvasTkAgg(self.fig, master=right)
            self.mpl_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=4)
        else:
            tk.Label(right, text="pip install matplotlib でグラフが表示されます",
                     bg="#1e1e1e", fg="#555").pack(expand=True)

        self.status_var = tk.StringVar(value="準備完了")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _on_type_change(self, *_):
        if self.type_var.get() == "収入":
            self.cat_cb["values"] = self.INCOME_CATS
            self.cat_var.set(self.INCOME_CATS[0])
        else:
            self.cat_cb["values"] = self.CATEGORIES
            self.cat_var.set(self.CATEGORIES[0])

    # ── DB操作 ───────────────────────────────────────────────
    def _add(self):
        try:
            amount = self.amount_var.get()
            if amount <= 0:
                raise ValueError("金額は正の整数で入力してください")
        except tk.TclError:
            messagebox.showerror("エラー", "金額を整数で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        conn.execute(
            "INSERT INTO transactions (date, type, category, amount, memo) VALUES (?,?,?,?,?)",
            (self.date_var.get(), self.type_var.get(),
             self.cat_var.get(), amount, self.memo_var.get()))
        conn.commit()
        conn.close()
        self.amount_var.set(0)
        self.memo_var.set("")
        self._load_month()

    def _delete(self):
        sel = self.tree.selection()
        if not sel:
            return
        row_id = self.tree.item(sel[0], "text")
        conn = sqlite3.connect(DB_PATH)
        conn.execute("DELETE FROM transactions WHERE id=?", (row_id,))
        conn.commit()
        conn.close()
        self._load_month()

    def _load_month(self):
        month = self.month_var.get().strip()
        try:
            y, m = month.split("-")
            start = f"{y}-{m:>02}-01"
            # 翌月1日
            nm = int(m) + 1
            ny = int(y)
            if nm > 12:
                nm = 1
                ny += 1
            end = f"{ny}-{nm:02d}-01"
        except Exception:
            messagebox.showerror("エラー", "月は YYYY-MM 形式で入力してください")
            return
        conn = sqlite3.connect(DB_PATH)
        rows = conn.execute(
            "SELECT id, date, type, category, amount, memo "
            "FROM transactions WHERE date >= ? AND date < ? ORDER BY date",
            (start, end)).fetchall()
        conn.close()

        self.tree.delete(*self.tree.get_children())
        income = expense = 0
        cat_expense = {}
        daily_expense = {}
        for row_id, dt, rtype, cat, amt, memo in rows:
            tag = "income" if rtype == "収入" else "expense"
            self.tree.insert("", tk.END, text=row_id,
                              values=(dt, rtype, cat, f"¥{amt:,}", memo),
                              tags=(tag,))
            if rtype == "収入":
                income += amt
            else:
                expense += amt
                cat_expense[cat] = cat_expense.get(cat, 0) + amt
                daily_expense[dt] = daily_expense.get(dt, 0) + amt

        balance = income - expense
        self._summary_labels["income"].config(text=f"¥{income:,}")
        self._summary_labels["expense"].config(text=f"¥{expense:,}")
        color = "#26a69a" if balance >= 0 else "#ef5350"
        self._summary_labels["balance"].config(text=f"¥{balance:,}", fg=color)

        if MATPLOTLIB_AVAILABLE:
            self._draw_charts(cat_expense, daily_expense)
        self.status_var.set(f"{month}: 収入 ¥{income:,}  支出 ¥{expense:,}  差額 ¥{balance:,}")

    def _draw_charts(self, cat_expense, daily_expense):
        self.ax_pie.clear()
        self.ax_bar.clear()
        self.ax_pie.set_facecolor("#1e1e1e")
        self.ax_bar.set_facecolor("#1e1e1e")

        if cat_expense:
            labels = list(cat_expense.keys())
            vals   = list(cat_expense.values())
            self.ax_pie.pie(vals, labels=labels, autopct="%1.0f%%",
                             startangle=90, textprops={"fontsize": 6, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a", "#ffa726",
                                     "#ab47bc", "#66bb6a", "#ec407a", "#ff7043"])
            self.ax_pie.set_title("支出カテゴリ", color="#c9d1d9", fontsize=8)

        if daily_expense:
            dates  = sorted(daily_expense.keys())
            amounts = [daily_expense[d] for d in dates]
            day_labels = [d[5:] for d in dates]  # MM-DD
            self.ax_bar.bar(range(len(dates)), amounts, color="#4fc3f7")
            step = max(1, len(dates) // 6)
            self.ax_bar.set_xticks(range(0, len(dates), step))
            self.ax_bar.set_xticklabels(day_labels[::step], fontsize=6,
                                          color="#8b949e", rotation=30)
            self.ax_bar.set_title("日別支出", color="#c9d1d9", fontsize=8)
            self.ax_bar.tick_params(colors="#8b949e", labelsize=6)

        for ax in (self.ax_pie, self.ax_bar):
            for spine in ax.spines.values():
                spine.set_edgecolor("#30363d")

        self.fig.tight_layout(pad=1.5)
        self.mpl_canvas.draw()

    def _set_month(self, month_str):
        self.month_var.set(month_str)
        self._load_month()

    def _prev_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m -= 1
            if m < 1:
                m = 12
                y -= 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass

    def _next_month(self):
        try:
            y, m = map(int, self.month_var.get().split("-"))
            m += 1
            if m > 12:
                m = 1
                y += 1
            self._set_month(f"{y}-{m:02d}")
        except Exception:
            pass


if __name__ == "__main__":
    root = tk.Tk()
    app = App081(root)
    root.mainloop()

6. ステップバイステップガイド

このアプリをゼロから自分で作る手順を解説します。コードをコピーするだけでなく、実際に手順を追って自分で書いてみましょう。

  1. 1
    ファイルを作成する

    新しいファイルを作成して app081.py と保存します。

  2. 2
    クラスの骨格を作る

    App081クラスを定義し、__init__とmainloop()の最小構成を作ります。

  3. 3
    タイトルバーを作る

    Frameを使ってカラーバー付きのタイトルエリアを作ります。

  4. 4
    入力フォームを実装する

    LabelFrameとEntryウィジェットで入力エリアを作ります。

  5. 5
    処理ロジックを実装する

    _execute()メソッドにメインロジックを実装します。

  6. 6
    結果表示を実装する

    TextウィジェットかLabelに結果を表示する_show_result()を実装します。

  7. 7
    エラー処理を追加する

    try-exceptとmessageboxでエラーハンドリングを追加します。

7. カスタマイズアイデア

基本機能を習得したら、以下のカスタマイズに挑戦してみましょう。

💡 ダークモードを追加する

bg色・fg色を辞書で管理し、ボタン1つでダークモード・ライトモードを切り替えられるようにしましょう。

💡 データの保存機能

処理結果をCSV・TXTファイルに保存する機能を追加しましょう。filedialog.asksaveasfilename()でファイル保存ダイアログが使えます。

💡 設定ダイアログ

フォントサイズや色などの設定をユーザーが変更できるオプションダイアログを追加しましょう。

8. よくある問題と解決法

❌ 日本語フォントが表示されない

原因:システムに日本語フォントが見つからない場合があります。

解決法:font引数を省略するかシステムに合ったフォントを指定してください。

❌ ライブラリのインポートエラー

原因:必要なライブラリがインストールされていません。

解決法:pip install コマンドで必要なライブラリをインストールしてください。 (pip install pandas matplotlib)

❌ ウィンドウサイズが合わない

原因:画面解像度や表示スケールによって異なる場合があります。

解決法:root.geometry()で適切なサイズに調整してください。

9. 練習問題

アプリの理解を深めるための練習問題です。

  1. 課題1:機能拡張

    家計簿ダッシュボードに新しい機能を1つ追加してみましょう。

  2. 課題2:UIの改善

    色・フォント・レイアウトを変更して、より使いやすいUIにカスタマイズしましょう。

  3. 課題3:保存機能の追加

    処理結果をファイルに保存する機能を追加しましょう。

🚀
次に挑戦するアプリ

このアプリをマスターしたら、次のアプリに挑戦しましょう。