中級者向け No.082

アンケート集計ツール

CSVのアンケートデータをpandasで集計しmatplotlibで自動グラフ生成するレポートツール。

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

1. アプリ概要

CSVのアンケートデータを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. 完全なソースコード

💡
コードのコピー方法

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

app082.py
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import csv
import os
import threading
from datetime import datetime

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


class App082:
    """アンケート集計ツール"""

    QUESTION_TYPES = ["単一選択", "複数選択", "テキスト", "評価(1-5)"]

    def __init__(self, root):
        self.root = root
        self.root.title("アンケート集計ツール")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._questions = []   # [{"text": ..., "type": ..., "options": [...]}]
        self._responses = []   # [{q_idx: answer, ...}]
        self._build_ui()
        self._load_sample()

    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)

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        ttk.Button(tb, text="📂 JSON読み込み",
                   command=self._load_json).pack(side=tk.LEFT, padx=4)
        ttk.Button(tb, text="📂 CSV読み込み",
                   command=self._load_csv).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="💾 結果をエクスポート",
                   command=self._export).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="➕ 質問追加",
                   command=self._add_question).pack(side=tk.LEFT, padx=8)
        ttk.Button(tb, text="📝 回答を入力",
                   command=self._open_response_form).pack(side=tk.LEFT, padx=2)

        # メイン 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=320)
        paned.add(left, weight=0)
        tk.Label(left, text="質問一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.q_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
                                     selectbackground="#1f6feb",
                                     font=("Arial", 9), relief=tk.FLAT)
        qsb = ttk.Scrollbar(left, command=self.q_listbox.yview)
        self.q_listbox.configure(yscrollcommand=qsb.set)
        qsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.q_listbox.pack(fill=tk.BOTH, expand=True)
        self.q_listbox.bind("<<ListboxSelect>>", self._on_q_select)

        info_f = tk.Frame(left, bg="#1e1e1e")
        info_f.pack(fill=tk.X, pady=4)
        self.resp_count_lbl = tk.Label(info_f, text="回答数: 0",
                                        bg="#1e1e1e", fg="#4fc3f7",
                                        font=("Arial", 10, "bold"))
        self.resp_count_lbl.pack(side=tk.LEFT, padx=4)

        # 右: グラフ + 集計
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

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

        # 集計テーブル
        tk.Label(right, text="集計結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        cols = ("option", "count", "pct")
        self.result_tree = ttk.Treeview(right, columns=cols,
                                         show="headings", height=6)
        self.result_tree.heading("option", text="選択肢 / 回答")
        self.result_tree.heading("count",  text="件数")
        self.result_tree.heading("pct",    text="割合")
        self.result_tree.column("option", width=250, anchor="w")
        self.result_tree.column("count",  width=60,  anchor="center")
        self.result_tree.column("pct",    width=70,  anchor="center")
        rsb = ttk.Scrollbar(right, command=self.result_tree.yview)
        self.result_tree.configure(yscrollcommand=rsb.set)
        rsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.result_tree.pack(fill=tk.X)

        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 _load_sample(self):
        """サンプルアンケートを自動生成"""
        import random
        self._questions = [
            {"text": "Python の経験年数は?",
             "type": "単一選択",
             "options": ["1年未満", "1〜3年", "3〜5年", "5年以上"]},
            {"text": "使用するライブラリ (複数可)",
             "type": "複数選択",
             "options": ["NumPy", "Pandas", "Matplotlib", "Requests", "Flask", "Django"]},
            {"text": "Python の満足度",
             "type": "評価(1-5)",
             "options": []},
            {"text": "Python で改善してほしい点",
             "type": "テキスト",
             "options": []},
        ]
        # ランダム回答を 20件生成
        for _ in range(20):
            resp = {}
            resp[0] = random.choice(self._questions[0]["options"])
            sel = random.sample(self._questions[1]["options"],
                                 random.randint(1, 3))
            resp[1] = sel
            resp[2] = str(random.randint(2, 5))
            resp[3] = ""
            self._responses.append(resp)
        self._refresh_q_list()

    def _refresh_q_list(self):
        self.q_listbox.delete(0, tk.END)
        for i, q in enumerate(self._questions):
            self.q_listbox.insert(tk.END, f"Q{i+1}. {q['text']}")
        self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")

    def _on_q_select(self, _=None):
        sel = self.q_listbox.curselection()
        if not sel:
            return
        self._show_results(sel[0])

    def _show_results(self, q_idx):
        if q_idx >= len(self._questions):
            return
        q = self._questions[q_idx]
        q_type = q["type"]
        options = q["options"]
        n = len(self._responses)

        counter = {}
        for resp in self._responses:
            ans = resp.get(q_idx, "")
            if q_type == "複数選択" and isinstance(ans, list):
                for a in ans:
                    counter[a] = counter.get(a, 0) + 1
            elif ans:
                counter[str(ans)] = counter.get(str(ans), 0) + 1

        # テーブル
        self.result_tree.delete(*self.result_tree.get_children())
        sorted_items = sorted(counter.items(), key=lambda x: -x[1])
        for opt, cnt in sorted_items:
            pct = cnt / max(1, n) * 100
            self.result_tree.insert("", tk.END,
                                     values=(opt, cnt, f"{pct:.1f}%"))

        # グラフ
        if MATPLOTLIB_AVAILABLE and counter:
            self.ax.clear()
            self.ax.set_facecolor("#1e1e1e")
            labels = [k for k, _ in sorted_items]
            values = [v for _, v in sorted_items]

            if q_type in ("単一選択", "評価(1-5)"):
                self.ax.pie(values, labels=labels, autopct="%1.1f%%",
                             startangle=90,
                             textprops={"fontsize": 7, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a",
                                     "#ffa726", "#ab47bc", "#66bb6a"])
            else:
                colors = ["#4fc3f7"] * len(labels)
                self.ax.barh(labels, values, color=colors)
                self.ax.tick_params(colors="#8b949e", labelsize=7)
                for spine in self.ax.spines.values():
                    spine.set_edgecolor("#30363d")

            self.ax.set_title(f"Q{q_idx+1}. {q['text'][:30]}",
                               color="#c9d1d9", fontsize=9)
            self.fig.tight_layout()
            self.mpl_canvas.draw()

        self.status_var.set(
            f"Q{q_idx+1}: {q['text']}  ({n} 件中 {sum(counter.values())} 件回答)")

    def _add_question(self):
        dlg = tk.Toplevel(self.root)
        dlg.title("質問を追加")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        tk.Label(dlg, text="質問文:", bg="#252526", fg="#ccc").pack(padx=12, pady=(12, 2), anchor="w")
        q_text = tk.Text(dlg, height=3, width=40, bg="#0d1117", fg="#c9d1d9",
                          relief=tk.FLAT, insertbackground="white")
        q_text.pack(padx=12)

        tk.Label(dlg, text="種別:", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        type_var = tk.StringVar(value="単一選択")
        ttk.Combobox(dlg, textvariable=type_var,
                     values=self.QUESTION_TYPES,
                     state="readonly", width=14).pack(padx=12)

        tk.Label(dlg, text="選択肢 (改行区切り):", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        opts_text = tk.Text(dlg, height=5, width=40, bg="#0d1117", fg="#c9d1d9",
                             relief=tk.FLAT, insertbackground="white")
        opts_text.pack(padx=12)

        def _ok():
            text = q_text.get("1.0", tk.END).strip()
            if not text:
                return
            opts = [o.strip() for o in opts_text.get("1.0", tk.END).splitlines() if o.strip()]
            self._questions.append({"text": text, "type": type_var.get(), "options": opts})
            self._refresh_q_list()
            dlg.destroy()

        ttk.Button(dlg, text="追加", command=_ok).pack(pady=8)

    def _open_response_form(self):
        if not self._questions:
            messagebox.showwarning("警告", "質問を追加してください")
            return
        dlg = tk.Toplevel(self.root)
        dlg.title("回答入力")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        widgets = []
        for i, q in enumerate(self._questions):
            tk.Label(dlg, text=f"Q{i+1}. {q['text']}", bg="#252526", fg="#ccc",
                     font=("Arial", 9, "bold"),
                     wraplength=400, justify=tk.LEFT).pack(padx=12, pady=(8, 2), anchor="w")
            q_type = q["type"]
            if q_type == "単一選択":
                var = tk.StringVar()
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    tk.Radiobutton(f, text=opt, variable=var, value=opt,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                widgets.append(("single", var))
            elif q_type == "複数選択":
                vars_ = []
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    v = tk.BooleanVar()
                    tk.Checkbutton(f, text=opt, variable=v,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                    vars_.append((opt, v))
                widgets.append(("multi", vars_))
            elif q_type == "評価(1-5)":
                var = tk.IntVar(value=3)
                ttk.Scale(dlg, from_=1, to=5, variable=var,
                           orient=tk.HORIZONTAL, length=200).pack(padx=12, anchor="w")
                lbl = tk.Label(dlg, textvariable=var, bg="#252526", fg="#4fc3f7",
                                font=("Arial", 10, "bold"))
                lbl.pack(padx=12, anchor="w")
                widgets.append(("rating", var))
            else:
                txt = tk.Text(dlg, height=2, width=40, bg="#0d1117", fg="#c9d1d9",
                               relief=tk.FLAT, insertbackground="white")
                txt.pack(padx=12, pady=2)
                widgets.append(("text", txt))

        def _submit():
            resp = {}
            for i, (wtype, widget) in enumerate(widgets):
                if wtype == "single":
                    resp[i] = widget.get()
                elif wtype == "multi":
                    resp[i] = [opt for opt, v in widget if v.get()]
                elif wtype == "rating":
                    resp[i] = str(widget.get())
                else:
                    resp[i] = widget.get("1.0", tk.END).strip()
            self._responses.append(resp)
            self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")
            self.status_var.set(f"回答を受け付けました ({len(self._responses)} 件)")
            dlg.destroy()

        ttk.Button(dlg, text="回答を送信", command=_submit).pack(pady=10)

    def _load_json(self):
        path = filedialog.askopenfilename(filetypes=[("JSON", "*.json")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8") as f:
                data = json.load(f)
            self._questions = data.get("questions", [])
            self._responses = data.get("responses", [])
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _load_csv(self):
        path = filedialog.askopenfilename(filetypes=[("CSV", "*.csv")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8-sig", newline="") as f:
                reader = csv.DictReader(f)
                rows = list(reader)
            if not rows:
                return
            self._questions = [{"text": h, "type": "テキスト", "options": []}
                                for h in rows[0].keys()]
            self._responses = [{i: row[h] for i, h in enumerate(rows[0].keys())}
                                for row in rows]
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}  ({len(rows)} 件)")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _export(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON", "*.json"), ("CSV", "*.csv")])
        if not path:
            return
        try:
            if path.endswith(".csv"):
                with open(path, "w", encoding="utf-8-sig", newline="") as f:
                    writer = csv.writer(f)
                    writer.writerow([f"Q{i+1}_{q['text']}"
                                     for i, q in enumerate(self._questions)])
                    for resp in self._responses:
                        row = [str(resp.get(i, "")) for i in range(len(self._questions))]
                        writer.writerow(row)
            else:
                with open(path, "w", encoding="utf-8") as f:
                    json.dump({"questions": self._questions,
                               "responses": self._responses}, f,
                              ensure_ascii=False, indent=2)
            messagebox.showinfo("完了", f"エクスポート: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))


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

5. コード解説

アンケート集計ツールのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。

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

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import csv
import os
import threading
from datetime import datetime

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


class App082:
    """アンケート集計ツール"""

    QUESTION_TYPES = ["単一選択", "複数選択", "テキスト", "評価(1-5)"]

    def __init__(self, root):
        self.root = root
        self.root.title("アンケート集計ツール")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._questions = []   # [{"text": ..., "type": ..., "options": [...]}]
        self._responses = []   # [{q_idx: answer, ...}]
        self._build_ui()
        self._load_sample()

    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)

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        ttk.Button(tb, text="📂 JSON読み込み",
                   command=self._load_json).pack(side=tk.LEFT, padx=4)
        ttk.Button(tb, text="📂 CSV読み込み",
                   command=self._load_csv).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="💾 結果をエクスポート",
                   command=self._export).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="➕ 質問追加",
                   command=self._add_question).pack(side=tk.LEFT, padx=8)
        ttk.Button(tb, text="📝 回答を入力",
                   command=self._open_response_form).pack(side=tk.LEFT, padx=2)

        # メイン 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=320)
        paned.add(left, weight=0)
        tk.Label(left, text="質問一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.q_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
                                     selectbackground="#1f6feb",
                                     font=("Arial", 9), relief=tk.FLAT)
        qsb = ttk.Scrollbar(left, command=self.q_listbox.yview)
        self.q_listbox.configure(yscrollcommand=qsb.set)
        qsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.q_listbox.pack(fill=tk.BOTH, expand=True)
        self.q_listbox.bind("<<ListboxSelect>>", self._on_q_select)

        info_f = tk.Frame(left, bg="#1e1e1e")
        info_f.pack(fill=tk.X, pady=4)
        self.resp_count_lbl = tk.Label(info_f, text="回答数: 0",
                                        bg="#1e1e1e", fg="#4fc3f7",
                                        font=("Arial", 10, "bold"))
        self.resp_count_lbl.pack(side=tk.LEFT, padx=4)

        # 右: グラフ + 集計
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

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

        # 集計テーブル
        tk.Label(right, text="集計結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        cols = ("option", "count", "pct")
        self.result_tree = ttk.Treeview(right, columns=cols,
                                         show="headings", height=6)
        self.result_tree.heading("option", text="選択肢 / 回答")
        self.result_tree.heading("count",  text="件数")
        self.result_tree.heading("pct",    text="割合")
        self.result_tree.column("option", width=250, anchor="w")
        self.result_tree.column("count",  width=60,  anchor="center")
        self.result_tree.column("pct",    width=70,  anchor="center")
        rsb = ttk.Scrollbar(right, command=self.result_tree.yview)
        self.result_tree.configure(yscrollcommand=rsb.set)
        rsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.result_tree.pack(fill=tk.X)

        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 _load_sample(self):
        """サンプルアンケートを自動生成"""
        import random
        self._questions = [
            {"text": "Python の経験年数は?",
             "type": "単一選択",
             "options": ["1年未満", "1〜3年", "3〜5年", "5年以上"]},
            {"text": "使用するライブラリ (複数可)",
             "type": "複数選択",
             "options": ["NumPy", "Pandas", "Matplotlib", "Requests", "Flask", "Django"]},
            {"text": "Python の満足度",
             "type": "評価(1-5)",
             "options": []},
            {"text": "Python で改善してほしい点",
             "type": "テキスト",
             "options": []},
        ]
        # ランダム回答を 20件生成
        for _ in range(20):
            resp = {}
            resp[0] = random.choice(self._questions[0]["options"])
            sel = random.sample(self._questions[1]["options"],
                                 random.randint(1, 3))
            resp[1] = sel
            resp[2] = str(random.randint(2, 5))
            resp[3] = ""
            self._responses.append(resp)
        self._refresh_q_list()

    def _refresh_q_list(self):
        self.q_listbox.delete(0, tk.END)
        for i, q in enumerate(self._questions):
            self.q_listbox.insert(tk.END, f"Q{i+1}. {q['text']}")
        self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")

    def _on_q_select(self, _=None):
        sel = self.q_listbox.curselection()
        if not sel:
            return
        self._show_results(sel[0])

    def _show_results(self, q_idx):
        if q_idx >= len(self._questions):
            return
        q = self._questions[q_idx]
        q_type = q["type"]
        options = q["options"]
        n = len(self._responses)

        counter = {}
        for resp in self._responses:
            ans = resp.get(q_idx, "")
            if q_type == "複数選択" and isinstance(ans, list):
                for a in ans:
                    counter[a] = counter.get(a, 0) + 1
            elif ans:
                counter[str(ans)] = counter.get(str(ans), 0) + 1

        # テーブル
        self.result_tree.delete(*self.result_tree.get_children())
        sorted_items = sorted(counter.items(), key=lambda x: -x[1])
        for opt, cnt in sorted_items:
            pct = cnt / max(1, n) * 100
            self.result_tree.insert("", tk.END,
                                     values=(opt, cnt, f"{pct:.1f}%"))

        # グラフ
        if MATPLOTLIB_AVAILABLE and counter:
            self.ax.clear()
            self.ax.set_facecolor("#1e1e1e")
            labels = [k for k, _ in sorted_items]
            values = [v for _, v in sorted_items]

            if q_type in ("単一選択", "評価(1-5)"):
                self.ax.pie(values, labels=labels, autopct="%1.1f%%",
                             startangle=90,
                             textprops={"fontsize": 7, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a",
                                     "#ffa726", "#ab47bc", "#66bb6a"])
            else:
                colors = ["#4fc3f7"] * len(labels)
                self.ax.barh(labels, values, color=colors)
                self.ax.tick_params(colors="#8b949e", labelsize=7)
                for spine in self.ax.spines.values():
                    spine.set_edgecolor("#30363d")

            self.ax.set_title(f"Q{q_idx+1}. {q['text'][:30]}",
                               color="#c9d1d9", fontsize=9)
            self.fig.tight_layout()
            self.mpl_canvas.draw()

        self.status_var.set(
            f"Q{q_idx+1}: {q['text']}  ({n} 件中 {sum(counter.values())} 件回答)")

    def _add_question(self):
        dlg = tk.Toplevel(self.root)
        dlg.title("質問を追加")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        tk.Label(dlg, text="質問文:", bg="#252526", fg="#ccc").pack(padx=12, pady=(12, 2), anchor="w")
        q_text = tk.Text(dlg, height=3, width=40, bg="#0d1117", fg="#c9d1d9",
                          relief=tk.FLAT, insertbackground="white")
        q_text.pack(padx=12)

        tk.Label(dlg, text="種別:", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        type_var = tk.StringVar(value="単一選択")
        ttk.Combobox(dlg, textvariable=type_var,
                     values=self.QUESTION_TYPES,
                     state="readonly", width=14).pack(padx=12)

        tk.Label(dlg, text="選択肢 (改行区切り):", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        opts_text = tk.Text(dlg, height=5, width=40, bg="#0d1117", fg="#c9d1d9",
                             relief=tk.FLAT, insertbackground="white")
        opts_text.pack(padx=12)

        def _ok():
            text = q_text.get("1.0", tk.END).strip()
            if not text:
                return
            opts = [o.strip() for o in opts_text.get("1.0", tk.END).splitlines() if o.strip()]
            self._questions.append({"text": text, "type": type_var.get(), "options": opts})
            self._refresh_q_list()
            dlg.destroy()

        ttk.Button(dlg, text="追加", command=_ok).pack(pady=8)

    def _open_response_form(self):
        if not self._questions:
            messagebox.showwarning("警告", "質問を追加してください")
            return
        dlg = tk.Toplevel(self.root)
        dlg.title("回答入力")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        widgets = []
        for i, q in enumerate(self._questions):
            tk.Label(dlg, text=f"Q{i+1}. {q['text']}", bg="#252526", fg="#ccc",
                     font=("Arial", 9, "bold"),
                     wraplength=400, justify=tk.LEFT).pack(padx=12, pady=(8, 2), anchor="w")
            q_type = q["type"]
            if q_type == "単一選択":
                var = tk.StringVar()
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    tk.Radiobutton(f, text=opt, variable=var, value=opt,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                widgets.append(("single", var))
            elif q_type == "複数選択":
                vars_ = []
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    v = tk.BooleanVar()
                    tk.Checkbutton(f, text=opt, variable=v,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                    vars_.append((opt, v))
                widgets.append(("multi", vars_))
            elif q_type == "評価(1-5)":
                var = tk.IntVar(value=3)
                ttk.Scale(dlg, from_=1, to=5, variable=var,
                           orient=tk.HORIZONTAL, length=200).pack(padx=12, anchor="w")
                lbl = tk.Label(dlg, textvariable=var, bg="#252526", fg="#4fc3f7",
                                font=("Arial", 10, "bold"))
                lbl.pack(padx=12, anchor="w")
                widgets.append(("rating", var))
            else:
                txt = tk.Text(dlg, height=2, width=40, bg="#0d1117", fg="#c9d1d9",
                               relief=tk.FLAT, insertbackground="white")
                txt.pack(padx=12, pady=2)
                widgets.append(("text", txt))

        def _submit():
            resp = {}
            for i, (wtype, widget) in enumerate(widgets):
                if wtype == "single":
                    resp[i] = widget.get()
                elif wtype == "multi":
                    resp[i] = [opt for opt, v in widget if v.get()]
                elif wtype == "rating":
                    resp[i] = str(widget.get())
                else:
                    resp[i] = widget.get("1.0", tk.END).strip()
            self._responses.append(resp)
            self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")
            self.status_var.set(f"回答を受け付けました ({len(self._responses)} 件)")
            dlg.destroy()

        ttk.Button(dlg, text="回答を送信", command=_submit).pack(pady=10)

    def _load_json(self):
        path = filedialog.askopenfilename(filetypes=[("JSON", "*.json")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8") as f:
                data = json.load(f)
            self._questions = data.get("questions", [])
            self._responses = data.get("responses", [])
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _load_csv(self):
        path = filedialog.askopenfilename(filetypes=[("CSV", "*.csv")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8-sig", newline="") as f:
                reader = csv.DictReader(f)
                rows = list(reader)
            if not rows:
                return
            self._questions = [{"text": h, "type": "テキスト", "options": []}
                                for h in rows[0].keys()]
            self._responses = [{i: row[h] for i, h in enumerate(rows[0].keys())}
                                for row in rows]
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}  ({len(rows)} 件)")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _export(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON", "*.json"), ("CSV", "*.csv")])
        if not path:
            return
        try:
            if path.endswith(".csv"):
                with open(path, "w", encoding="utf-8-sig", newline="") as f:
                    writer = csv.writer(f)
                    writer.writerow([f"Q{i+1}_{q['text']}"
                                     for i, q in enumerate(self._questions)])
                    for resp in self._responses:
                        row = [str(resp.get(i, "")) for i in range(len(self._questions))]
                        writer.writerow(row)
            else:
                with open(path, "w", encoding="utf-8") as f:
                    json.dump({"questions": self._questions,
                               "responses": self._responses}, f,
                              ensure_ascii=False, indent=2)
            messagebox.showinfo("完了", f"エクスポート: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))


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

UIレイアウトの構築

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import csv
import os
import threading
from datetime import datetime

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


class App082:
    """アンケート集計ツール"""

    QUESTION_TYPES = ["単一選択", "複数選択", "テキスト", "評価(1-5)"]

    def __init__(self, root):
        self.root = root
        self.root.title("アンケート集計ツール")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._questions = []   # [{"text": ..., "type": ..., "options": [...]}]
        self._responses = []   # [{q_idx: answer, ...}]
        self._build_ui()
        self._load_sample()

    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)

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        ttk.Button(tb, text="📂 JSON読み込み",
                   command=self._load_json).pack(side=tk.LEFT, padx=4)
        ttk.Button(tb, text="📂 CSV読み込み",
                   command=self._load_csv).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="💾 結果をエクスポート",
                   command=self._export).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="➕ 質問追加",
                   command=self._add_question).pack(side=tk.LEFT, padx=8)
        ttk.Button(tb, text="📝 回答を入力",
                   command=self._open_response_form).pack(side=tk.LEFT, padx=2)

        # メイン 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=320)
        paned.add(left, weight=0)
        tk.Label(left, text="質問一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.q_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
                                     selectbackground="#1f6feb",
                                     font=("Arial", 9), relief=tk.FLAT)
        qsb = ttk.Scrollbar(left, command=self.q_listbox.yview)
        self.q_listbox.configure(yscrollcommand=qsb.set)
        qsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.q_listbox.pack(fill=tk.BOTH, expand=True)
        self.q_listbox.bind("<<ListboxSelect>>", self._on_q_select)

        info_f = tk.Frame(left, bg="#1e1e1e")
        info_f.pack(fill=tk.X, pady=4)
        self.resp_count_lbl = tk.Label(info_f, text="回答数: 0",
                                        bg="#1e1e1e", fg="#4fc3f7",
                                        font=("Arial", 10, "bold"))
        self.resp_count_lbl.pack(side=tk.LEFT, padx=4)

        # 右: グラフ + 集計
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

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

        # 集計テーブル
        tk.Label(right, text="集計結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        cols = ("option", "count", "pct")
        self.result_tree = ttk.Treeview(right, columns=cols,
                                         show="headings", height=6)
        self.result_tree.heading("option", text="選択肢 / 回答")
        self.result_tree.heading("count",  text="件数")
        self.result_tree.heading("pct",    text="割合")
        self.result_tree.column("option", width=250, anchor="w")
        self.result_tree.column("count",  width=60,  anchor="center")
        self.result_tree.column("pct",    width=70,  anchor="center")
        rsb = ttk.Scrollbar(right, command=self.result_tree.yview)
        self.result_tree.configure(yscrollcommand=rsb.set)
        rsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.result_tree.pack(fill=tk.X)

        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 _load_sample(self):
        """サンプルアンケートを自動生成"""
        import random
        self._questions = [
            {"text": "Python の経験年数は?",
             "type": "単一選択",
             "options": ["1年未満", "1〜3年", "3〜5年", "5年以上"]},
            {"text": "使用するライブラリ (複数可)",
             "type": "複数選択",
             "options": ["NumPy", "Pandas", "Matplotlib", "Requests", "Flask", "Django"]},
            {"text": "Python の満足度",
             "type": "評価(1-5)",
             "options": []},
            {"text": "Python で改善してほしい点",
             "type": "テキスト",
             "options": []},
        ]
        # ランダム回答を 20件生成
        for _ in range(20):
            resp = {}
            resp[0] = random.choice(self._questions[0]["options"])
            sel = random.sample(self._questions[1]["options"],
                                 random.randint(1, 3))
            resp[1] = sel
            resp[2] = str(random.randint(2, 5))
            resp[3] = ""
            self._responses.append(resp)
        self._refresh_q_list()

    def _refresh_q_list(self):
        self.q_listbox.delete(0, tk.END)
        for i, q in enumerate(self._questions):
            self.q_listbox.insert(tk.END, f"Q{i+1}. {q['text']}")
        self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")

    def _on_q_select(self, _=None):
        sel = self.q_listbox.curselection()
        if not sel:
            return
        self._show_results(sel[0])

    def _show_results(self, q_idx):
        if q_idx >= len(self._questions):
            return
        q = self._questions[q_idx]
        q_type = q["type"]
        options = q["options"]
        n = len(self._responses)

        counter = {}
        for resp in self._responses:
            ans = resp.get(q_idx, "")
            if q_type == "複数選択" and isinstance(ans, list):
                for a in ans:
                    counter[a] = counter.get(a, 0) + 1
            elif ans:
                counter[str(ans)] = counter.get(str(ans), 0) + 1

        # テーブル
        self.result_tree.delete(*self.result_tree.get_children())
        sorted_items = sorted(counter.items(), key=lambda x: -x[1])
        for opt, cnt in sorted_items:
            pct = cnt / max(1, n) * 100
            self.result_tree.insert("", tk.END,
                                     values=(opt, cnt, f"{pct:.1f}%"))

        # グラフ
        if MATPLOTLIB_AVAILABLE and counter:
            self.ax.clear()
            self.ax.set_facecolor("#1e1e1e")
            labels = [k for k, _ in sorted_items]
            values = [v for _, v in sorted_items]

            if q_type in ("単一選択", "評価(1-5)"):
                self.ax.pie(values, labels=labels, autopct="%1.1f%%",
                             startangle=90,
                             textprops={"fontsize": 7, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a",
                                     "#ffa726", "#ab47bc", "#66bb6a"])
            else:
                colors = ["#4fc3f7"] * len(labels)
                self.ax.barh(labels, values, color=colors)
                self.ax.tick_params(colors="#8b949e", labelsize=7)
                for spine in self.ax.spines.values():
                    spine.set_edgecolor("#30363d")

            self.ax.set_title(f"Q{q_idx+1}. {q['text'][:30]}",
                               color="#c9d1d9", fontsize=9)
            self.fig.tight_layout()
            self.mpl_canvas.draw()

        self.status_var.set(
            f"Q{q_idx+1}: {q['text']}  ({n} 件中 {sum(counter.values())} 件回答)")

    def _add_question(self):
        dlg = tk.Toplevel(self.root)
        dlg.title("質問を追加")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        tk.Label(dlg, text="質問文:", bg="#252526", fg="#ccc").pack(padx=12, pady=(12, 2), anchor="w")
        q_text = tk.Text(dlg, height=3, width=40, bg="#0d1117", fg="#c9d1d9",
                          relief=tk.FLAT, insertbackground="white")
        q_text.pack(padx=12)

        tk.Label(dlg, text="種別:", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        type_var = tk.StringVar(value="単一選択")
        ttk.Combobox(dlg, textvariable=type_var,
                     values=self.QUESTION_TYPES,
                     state="readonly", width=14).pack(padx=12)

        tk.Label(dlg, text="選択肢 (改行区切り):", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        opts_text = tk.Text(dlg, height=5, width=40, bg="#0d1117", fg="#c9d1d9",
                             relief=tk.FLAT, insertbackground="white")
        opts_text.pack(padx=12)

        def _ok():
            text = q_text.get("1.0", tk.END).strip()
            if not text:
                return
            opts = [o.strip() for o in opts_text.get("1.0", tk.END).splitlines() if o.strip()]
            self._questions.append({"text": text, "type": type_var.get(), "options": opts})
            self._refresh_q_list()
            dlg.destroy()

        ttk.Button(dlg, text="追加", command=_ok).pack(pady=8)

    def _open_response_form(self):
        if not self._questions:
            messagebox.showwarning("警告", "質問を追加してください")
            return
        dlg = tk.Toplevel(self.root)
        dlg.title("回答入力")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        widgets = []
        for i, q in enumerate(self._questions):
            tk.Label(dlg, text=f"Q{i+1}. {q['text']}", bg="#252526", fg="#ccc",
                     font=("Arial", 9, "bold"),
                     wraplength=400, justify=tk.LEFT).pack(padx=12, pady=(8, 2), anchor="w")
            q_type = q["type"]
            if q_type == "単一選択":
                var = tk.StringVar()
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    tk.Radiobutton(f, text=opt, variable=var, value=opt,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                widgets.append(("single", var))
            elif q_type == "複数選択":
                vars_ = []
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    v = tk.BooleanVar()
                    tk.Checkbutton(f, text=opt, variable=v,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                    vars_.append((opt, v))
                widgets.append(("multi", vars_))
            elif q_type == "評価(1-5)":
                var = tk.IntVar(value=3)
                ttk.Scale(dlg, from_=1, to=5, variable=var,
                           orient=tk.HORIZONTAL, length=200).pack(padx=12, anchor="w")
                lbl = tk.Label(dlg, textvariable=var, bg="#252526", fg="#4fc3f7",
                                font=("Arial", 10, "bold"))
                lbl.pack(padx=12, anchor="w")
                widgets.append(("rating", var))
            else:
                txt = tk.Text(dlg, height=2, width=40, bg="#0d1117", fg="#c9d1d9",
                               relief=tk.FLAT, insertbackground="white")
                txt.pack(padx=12, pady=2)
                widgets.append(("text", txt))

        def _submit():
            resp = {}
            for i, (wtype, widget) in enumerate(widgets):
                if wtype == "single":
                    resp[i] = widget.get()
                elif wtype == "multi":
                    resp[i] = [opt for opt, v in widget if v.get()]
                elif wtype == "rating":
                    resp[i] = str(widget.get())
                else:
                    resp[i] = widget.get("1.0", tk.END).strip()
            self._responses.append(resp)
            self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")
            self.status_var.set(f"回答を受け付けました ({len(self._responses)} 件)")
            dlg.destroy()

        ttk.Button(dlg, text="回答を送信", command=_submit).pack(pady=10)

    def _load_json(self):
        path = filedialog.askopenfilename(filetypes=[("JSON", "*.json")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8") as f:
                data = json.load(f)
            self._questions = data.get("questions", [])
            self._responses = data.get("responses", [])
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _load_csv(self):
        path = filedialog.askopenfilename(filetypes=[("CSV", "*.csv")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8-sig", newline="") as f:
                reader = csv.DictReader(f)
                rows = list(reader)
            if not rows:
                return
            self._questions = [{"text": h, "type": "テキスト", "options": []}
                                for h in rows[0].keys()]
            self._responses = [{i: row[h] for i, h in enumerate(rows[0].keys())}
                                for row in rows]
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}  ({len(rows)} 件)")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _export(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON", "*.json"), ("CSV", "*.csv")])
        if not path:
            return
        try:
            if path.endswith(".csv"):
                with open(path, "w", encoding="utf-8-sig", newline="") as f:
                    writer = csv.writer(f)
                    writer.writerow([f"Q{i+1}_{q['text']}"
                                     for i, q in enumerate(self._questions)])
                    for resp in self._responses:
                        row = [str(resp.get(i, "")) for i in range(len(self._questions))]
                        writer.writerow(row)
            else:
                with open(path, "w", encoding="utf-8") as f:
                    json.dump({"questions": self._questions,
                               "responses": self._responses}, f,
                              ensure_ascii=False, indent=2)
            messagebox.showinfo("完了", f"エクスポート: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))


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

イベント処理

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import csv
import os
import threading
from datetime import datetime

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


class App082:
    """アンケート集計ツール"""

    QUESTION_TYPES = ["単一選択", "複数選択", "テキスト", "評価(1-5)"]

    def __init__(self, root):
        self.root = root
        self.root.title("アンケート集計ツール")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._questions = []   # [{"text": ..., "type": ..., "options": [...]}]
        self._responses = []   # [{q_idx: answer, ...}]
        self._build_ui()
        self._load_sample()

    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)

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        ttk.Button(tb, text="📂 JSON読み込み",
                   command=self._load_json).pack(side=tk.LEFT, padx=4)
        ttk.Button(tb, text="📂 CSV読み込み",
                   command=self._load_csv).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="💾 結果をエクスポート",
                   command=self._export).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="➕ 質問追加",
                   command=self._add_question).pack(side=tk.LEFT, padx=8)
        ttk.Button(tb, text="📝 回答を入力",
                   command=self._open_response_form).pack(side=tk.LEFT, padx=2)

        # メイン 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=320)
        paned.add(left, weight=0)
        tk.Label(left, text="質問一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.q_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
                                     selectbackground="#1f6feb",
                                     font=("Arial", 9), relief=tk.FLAT)
        qsb = ttk.Scrollbar(left, command=self.q_listbox.yview)
        self.q_listbox.configure(yscrollcommand=qsb.set)
        qsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.q_listbox.pack(fill=tk.BOTH, expand=True)
        self.q_listbox.bind("<<ListboxSelect>>", self._on_q_select)

        info_f = tk.Frame(left, bg="#1e1e1e")
        info_f.pack(fill=tk.X, pady=4)
        self.resp_count_lbl = tk.Label(info_f, text="回答数: 0",
                                        bg="#1e1e1e", fg="#4fc3f7",
                                        font=("Arial", 10, "bold"))
        self.resp_count_lbl.pack(side=tk.LEFT, padx=4)

        # 右: グラフ + 集計
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

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

        # 集計テーブル
        tk.Label(right, text="集計結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        cols = ("option", "count", "pct")
        self.result_tree = ttk.Treeview(right, columns=cols,
                                         show="headings", height=6)
        self.result_tree.heading("option", text="選択肢 / 回答")
        self.result_tree.heading("count",  text="件数")
        self.result_tree.heading("pct",    text="割合")
        self.result_tree.column("option", width=250, anchor="w")
        self.result_tree.column("count",  width=60,  anchor="center")
        self.result_tree.column("pct",    width=70,  anchor="center")
        rsb = ttk.Scrollbar(right, command=self.result_tree.yview)
        self.result_tree.configure(yscrollcommand=rsb.set)
        rsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.result_tree.pack(fill=tk.X)

        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 _load_sample(self):
        """サンプルアンケートを自動生成"""
        import random
        self._questions = [
            {"text": "Python の経験年数は?",
             "type": "単一選択",
             "options": ["1年未満", "1〜3年", "3〜5年", "5年以上"]},
            {"text": "使用するライブラリ (複数可)",
             "type": "複数選択",
             "options": ["NumPy", "Pandas", "Matplotlib", "Requests", "Flask", "Django"]},
            {"text": "Python の満足度",
             "type": "評価(1-5)",
             "options": []},
            {"text": "Python で改善してほしい点",
             "type": "テキスト",
             "options": []},
        ]
        # ランダム回答を 20件生成
        for _ in range(20):
            resp = {}
            resp[0] = random.choice(self._questions[0]["options"])
            sel = random.sample(self._questions[1]["options"],
                                 random.randint(1, 3))
            resp[1] = sel
            resp[2] = str(random.randint(2, 5))
            resp[3] = ""
            self._responses.append(resp)
        self._refresh_q_list()

    def _refresh_q_list(self):
        self.q_listbox.delete(0, tk.END)
        for i, q in enumerate(self._questions):
            self.q_listbox.insert(tk.END, f"Q{i+1}. {q['text']}")
        self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")

    def _on_q_select(self, _=None):
        sel = self.q_listbox.curselection()
        if not sel:
            return
        self._show_results(sel[0])

    def _show_results(self, q_idx):
        if q_idx >= len(self._questions):
            return
        q = self._questions[q_idx]
        q_type = q["type"]
        options = q["options"]
        n = len(self._responses)

        counter = {}
        for resp in self._responses:
            ans = resp.get(q_idx, "")
            if q_type == "複数選択" and isinstance(ans, list):
                for a in ans:
                    counter[a] = counter.get(a, 0) + 1
            elif ans:
                counter[str(ans)] = counter.get(str(ans), 0) + 1

        # テーブル
        self.result_tree.delete(*self.result_tree.get_children())
        sorted_items = sorted(counter.items(), key=lambda x: -x[1])
        for opt, cnt in sorted_items:
            pct = cnt / max(1, n) * 100
            self.result_tree.insert("", tk.END,
                                     values=(opt, cnt, f"{pct:.1f}%"))

        # グラフ
        if MATPLOTLIB_AVAILABLE and counter:
            self.ax.clear()
            self.ax.set_facecolor("#1e1e1e")
            labels = [k for k, _ in sorted_items]
            values = [v for _, v in sorted_items]

            if q_type in ("単一選択", "評価(1-5)"):
                self.ax.pie(values, labels=labels, autopct="%1.1f%%",
                             startangle=90,
                             textprops={"fontsize": 7, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a",
                                     "#ffa726", "#ab47bc", "#66bb6a"])
            else:
                colors = ["#4fc3f7"] * len(labels)
                self.ax.barh(labels, values, color=colors)
                self.ax.tick_params(colors="#8b949e", labelsize=7)
                for spine in self.ax.spines.values():
                    spine.set_edgecolor("#30363d")

            self.ax.set_title(f"Q{q_idx+1}. {q['text'][:30]}",
                               color="#c9d1d9", fontsize=9)
            self.fig.tight_layout()
            self.mpl_canvas.draw()

        self.status_var.set(
            f"Q{q_idx+1}: {q['text']}  ({n} 件中 {sum(counter.values())} 件回答)")

    def _add_question(self):
        dlg = tk.Toplevel(self.root)
        dlg.title("質問を追加")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        tk.Label(dlg, text="質問文:", bg="#252526", fg="#ccc").pack(padx=12, pady=(12, 2), anchor="w")
        q_text = tk.Text(dlg, height=3, width=40, bg="#0d1117", fg="#c9d1d9",
                          relief=tk.FLAT, insertbackground="white")
        q_text.pack(padx=12)

        tk.Label(dlg, text="種別:", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        type_var = tk.StringVar(value="単一選択")
        ttk.Combobox(dlg, textvariable=type_var,
                     values=self.QUESTION_TYPES,
                     state="readonly", width=14).pack(padx=12)

        tk.Label(dlg, text="選択肢 (改行区切り):", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        opts_text = tk.Text(dlg, height=5, width=40, bg="#0d1117", fg="#c9d1d9",
                             relief=tk.FLAT, insertbackground="white")
        opts_text.pack(padx=12)

        def _ok():
            text = q_text.get("1.0", tk.END).strip()
            if not text:
                return
            opts = [o.strip() for o in opts_text.get("1.0", tk.END).splitlines() if o.strip()]
            self._questions.append({"text": text, "type": type_var.get(), "options": opts})
            self._refresh_q_list()
            dlg.destroy()

        ttk.Button(dlg, text="追加", command=_ok).pack(pady=8)

    def _open_response_form(self):
        if not self._questions:
            messagebox.showwarning("警告", "質問を追加してください")
            return
        dlg = tk.Toplevel(self.root)
        dlg.title("回答入力")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        widgets = []
        for i, q in enumerate(self._questions):
            tk.Label(dlg, text=f"Q{i+1}. {q['text']}", bg="#252526", fg="#ccc",
                     font=("Arial", 9, "bold"),
                     wraplength=400, justify=tk.LEFT).pack(padx=12, pady=(8, 2), anchor="w")
            q_type = q["type"]
            if q_type == "単一選択":
                var = tk.StringVar()
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    tk.Radiobutton(f, text=opt, variable=var, value=opt,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                widgets.append(("single", var))
            elif q_type == "複数選択":
                vars_ = []
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    v = tk.BooleanVar()
                    tk.Checkbutton(f, text=opt, variable=v,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                    vars_.append((opt, v))
                widgets.append(("multi", vars_))
            elif q_type == "評価(1-5)":
                var = tk.IntVar(value=3)
                ttk.Scale(dlg, from_=1, to=5, variable=var,
                           orient=tk.HORIZONTAL, length=200).pack(padx=12, anchor="w")
                lbl = tk.Label(dlg, textvariable=var, bg="#252526", fg="#4fc3f7",
                                font=("Arial", 10, "bold"))
                lbl.pack(padx=12, anchor="w")
                widgets.append(("rating", var))
            else:
                txt = tk.Text(dlg, height=2, width=40, bg="#0d1117", fg="#c9d1d9",
                               relief=tk.FLAT, insertbackground="white")
                txt.pack(padx=12, pady=2)
                widgets.append(("text", txt))

        def _submit():
            resp = {}
            for i, (wtype, widget) in enumerate(widgets):
                if wtype == "single":
                    resp[i] = widget.get()
                elif wtype == "multi":
                    resp[i] = [opt for opt, v in widget if v.get()]
                elif wtype == "rating":
                    resp[i] = str(widget.get())
                else:
                    resp[i] = widget.get("1.0", tk.END).strip()
            self._responses.append(resp)
            self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")
            self.status_var.set(f"回答を受け付けました ({len(self._responses)} 件)")
            dlg.destroy()

        ttk.Button(dlg, text="回答を送信", command=_submit).pack(pady=10)

    def _load_json(self):
        path = filedialog.askopenfilename(filetypes=[("JSON", "*.json")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8") as f:
                data = json.load(f)
            self._questions = data.get("questions", [])
            self._responses = data.get("responses", [])
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _load_csv(self):
        path = filedialog.askopenfilename(filetypes=[("CSV", "*.csv")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8-sig", newline="") as f:
                reader = csv.DictReader(f)
                rows = list(reader)
            if not rows:
                return
            self._questions = [{"text": h, "type": "テキスト", "options": []}
                                for h in rows[0].keys()]
            self._responses = [{i: row[h] for i, h in enumerate(rows[0].keys())}
                                for row in rows]
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}  ({len(rows)} 件)")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _export(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON", "*.json"), ("CSV", "*.csv")])
        if not path:
            return
        try:
            if path.endswith(".csv"):
                with open(path, "w", encoding="utf-8-sig", newline="") as f:
                    writer = csv.writer(f)
                    writer.writerow([f"Q{i+1}_{q['text']}"
                                     for i, q in enumerate(self._questions)])
                    for resp in self._responses:
                        row = [str(resp.get(i, "")) for i in range(len(self._questions))]
                        writer.writerow(row)
            else:
                with open(path, "w", encoding="utf-8") as f:
                    json.dump({"questions": self._questions,
                               "responses": self._responses}, f,
                              ensure_ascii=False, indent=2)
            messagebox.showinfo("完了", f"エクスポート: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))


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

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

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import csv
import os
import threading
from datetime import datetime

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


class App082:
    """アンケート集計ツール"""

    QUESTION_TYPES = ["単一選択", "複数選択", "テキスト", "評価(1-5)"]

    def __init__(self, root):
        self.root = root
        self.root.title("アンケート集計ツール")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._questions = []   # [{"text": ..., "type": ..., "options": [...]}]
        self._responses = []   # [{q_idx: answer, ...}]
        self._build_ui()
        self._load_sample()

    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)

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        ttk.Button(tb, text="📂 JSON読み込み",
                   command=self._load_json).pack(side=tk.LEFT, padx=4)
        ttk.Button(tb, text="📂 CSV読み込み",
                   command=self._load_csv).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="💾 結果をエクスポート",
                   command=self._export).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="➕ 質問追加",
                   command=self._add_question).pack(side=tk.LEFT, padx=8)
        ttk.Button(tb, text="📝 回答を入力",
                   command=self._open_response_form).pack(side=tk.LEFT, padx=2)

        # メイン 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=320)
        paned.add(left, weight=0)
        tk.Label(left, text="質問一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.q_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
                                     selectbackground="#1f6feb",
                                     font=("Arial", 9), relief=tk.FLAT)
        qsb = ttk.Scrollbar(left, command=self.q_listbox.yview)
        self.q_listbox.configure(yscrollcommand=qsb.set)
        qsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.q_listbox.pack(fill=tk.BOTH, expand=True)
        self.q_listbox.bind("<<ListboxSelect>>", self._on_q_select)

        info_f = tk.Frame(left, bg="#1e1e1e")
        info_f.pack(fill=tk.X, pady=4)
        self.resp_count_lbl = tk.Label(info_f, text="回答数: 0",
                                        bg="#1e1e1e", fg="#4fc3f7",
                                        font=("Arial", 10, "bold"))
        self.resp_count_lbl.pack(side=tk.LEFT, padx=4)

        # 右: グラフ + 集計
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

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

        # 集計テーブル
        tk.Label(right, text="集計結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        cols = ("option", "count", "pct")
        self.result_tree = ttk.Treeview(right, columns=cols,
                                         show="headings", height=6)
        self.result_tree.heading("option", text="選択肢 / 回答")
        self.result_tree.heading("count",  text="件数")
        self.result_tree.heading("pct",    text="割合")
        self.result_tree.column("option", width=250, anchor="w")
        self.result_tree.column("count",  width=60,  anchor="center")
        self.result_tree.column("pct",    width=70,  anchor="center")
        rsb = ttk.Scrollbar(right, command=self.result_tree.yview)
        self.result_tree.configure(yscrollcommand=rsb.set)
        rsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.result_tree.pack(fill=tk.X)

        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 _load_sample(self):
        """サンプルアンケートを自動生成"""
        import random
        self._questions = [
            {"text": "Python の経験年数は?",
             "type": "単一選択",
             "options": ["1年未満", "1〜3年", "3〜5年", "5年以上"]},
            {"text": "使用するライブラリ (複数可)",
             "type": "複数選択",
             "options": ["NumPy", "Pandas", "Matplotlib", "Requests", "Flask", "Django"]},
            {"text": "Python の満足度",
             "type": "評価(1-5)",
             "options": []},
            {"text": "Python で改善してほしい点",
             "type": "テキスト",
             "options": []},
        ]
        # ランダム回答を 20件生成
        for _ in range(20):
            resp = {}
            resp[0] = random.choice(self._questions[0]["options"])
            sel = random.sample(self._questions[1]["options"],
                                 random.randint(1, 3))
            resp[1] = sel
            resp[2] = str(random.randint(2, 5))
            resp[3] = ""
            self._responses.append(resp)
        self._refresh_q_list()

    def _refresh_q_list(self):
        self.q_listbox.delete(0, tk.END)
        for i, q in enumerate(self._questions):
            self.q_listbox.insert(tk.END, f"Q{i+1}. {q['text']}")
        self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")

    def _on_q_select(self, _=None):
        sel = self.q_listbox.curselection()
        if not sel:
            return
        self._show_results(sel[0])

    def _show_results(self, q_idx):
        if q_idx >= len(self._questions):
            return
        q = self._questions[q_idx]
        q_type = q["type"]
        options = q["options"]
        n = len(self._responses)

        counter = {}
        for resp in self._responses:
            ans = resp.get(q_idx, "")
            if q_type == "複数選択" and isinstance(ans, list):
                for a in ans:
                    counter[a] = counter.get(a, 0) + 1
            elif ans:
                counter[str(ans)] = counter.get(str(ans), 0) + 1

        # テーブル
        self.result_tree.delete(*self.result_tree.get_children())
        sorted_items = sorted(counter.items(), key=lambda x: -x[1])
        for opt, cnt in sorted_items:
            pct = cnt / max(1, n) * 100
            self.result_tree.insert("", tk.END,
                                     values=(opt, cnt, f"{pct:.1f}%"))

        # グラフ
        if MATPLOTLIB_AVAILABLE and counter:
            self.ax.clear()
            self.ax.set_facecolor("#1e1e1e")
            labels = [k for k, _ in sorted_items]
            values = [v for _, v in sorted_items]

            if q_type in ("単一選択", "評価(1-5)"):
                self.ax.pie(values, labels=labels, autopct="%1.1f%%",
                             startangle=90,
                             textprops={"fontsize": 7, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a",
                                     "#ffa726", "#ab47bc", "#66bb6a"])
            else:
                colors = ["#4fc3f7"] * len(labels)
                self.ax.barh(labels, values, color=colors)
                self.ax.tick_params(colors="#8b949e", labelsize=7)
                for spine in self.ax.spines.values():
                    spine.set_edgecolor("#30363d")

            self.ax.set_title(f"Q{q_idx+1}. {q['text'][:30]}",
                               color="#c9d1d9", fontsize=9)
            self.fig.tight_layout()
            self.mpl_canvas.draw()

        self.status_var.set(
            f"Q{q_idx+1}: {q['text']}  ({n} 件中 {sum(counter.values())} 件回答)")

    def _add_question(self):
        dlg = tk.Toplevel(self.root)
        dlg.title("質問を追加")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        tk.Label(dlg, text="質問文:", bg="#252526", fg="#ccc").pack(padx=12, pady=(12, 2), anchor="w")
        q_text = tk.Text(dlg, height=3, width=40, bg="#0d1117", fg="#c9d1d9",
                          relief=tk.FLAT, insertbackground="white")
        q_text.pack(padx=12)

        tk.Label(dlg, text="種別:", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        type_var = tk.StringVar(value="単一選択")
        ttk.Combobox(dlg, textvariable=type_var,
                     values=self.QUESTION_TYPES,
                     state="readonly", width=14).pack(padx=12)

        tk.Label(dlg, text="選択肢 (改行区切り):", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        opts_text = tk.Text(dlg, height=5, width=40, bg="#0d1117", fg="#c9d1d9",
                             relief=tk.FLAT, insertbackground="white")
        opts_text.pack(padx=12)

        def _ok():
            text = q_text.get("1.0", tk.END).strip()
            if not text:
                return
            opts = [o.strip() for o in opts_text.get("1.0", tk.END).splitlines() if o.strip()]
            self._questions.append({"text": text, "type": type_var.get(), "options": opts})
            self._refresh_q_list()
            dlg.destroy()

        ttk.Button(dlg, text="追加", command=_ok).pack(pady=8)

    def _open_response_form(self):
        if not self._questions:
            messagebox.showwarning("警告", "質問を追加してください")
            return
        dlg = tk.Toplevel(self.root)
        dlg.title("回答入力")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        widgets = []
        for i, q in enumerate(self._questions):
            tk.Label(dlg, text=f"Q{i+1}. {q['text']}", bg="#252526", fg="#ccc",
                     font=("Arial", 9, "bold"),
                     wraplength=400, justify=tk.LEFT).pack(padx=12, pady=(8, 2), anchor="w")
            q_type = q["type"]
            if q_type == "単一選択":
                var = tk.StringVar()
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    tk.Radiobutton(f, text=opt, variable=var, value=opt,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                widgets.append(("single", var))
            elif q_type == "複数選択":
                vars_ = []
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    v = tk.BooleanVar()
                    tk.Checkbutton(f, text=opt, variable=v,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                    vars_.append((opt, v))
                widgets.append(("multi", vars_))
            elif q_type == "評価(1-5)":
                var = tk.IntVar(value=3)
                ttk.Scale(dlg, from_=1, to=5, variable=var,
                           orient=tk.HORIZONTAL, length=200).pack(padx=12, anchor="w")
                lbl = tk.Label(dlg, textvariable=var, bg="#252526", fg="#4fc3f7",
                                font=("Arial", 10, "bold"))
                lbl.pack(padx=12, anchor="w")
                widgets.append(("rating", var))
            else:
                txt = tk.Text(dlg, height=2, width=40, bg="#0d1117", fg="#c9d1d9",
                               relief=tk.FLAT, insertbackground="white")
                txt.pack(padx=12, pady=2)
                widgets.append(("text", txt))

        def _submit():
            resp = {}
            for i, (wtype, widget) in enumerate(widgets):
                if wtype == "single":
                    resp[i] = widget.get()
                elif wtype == "multi":
                    resp[i] = [opt for opt, v in widget if v.get()]
                elif wtype == "rating":
                    resp[i] = str(widget.get())
                else:
                    resp[i] = widget.get("1.0", tk.END).strip()
            self._responses.append(resp)
            self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")
            self.status_var.set(f"回答を受け付けました ({len(self._responses)} 件)")
            dlg.destroy()

        ttk.Button(dlg, text="回答を送信", command=_submit).pack(pady=10)

    def _load_json(self):
        path = filedialog.askopenfilename(filetypes=[("JSON", "*.json")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8") as f:
                data = json.load(f)
            self._questions = data.get("questions", [])
            self._responses = data.get("responses", [])
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _load_csv(self):
        path = filedialog.askopenfilename(filetypes=[("CSV", "*.csv")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8-sig", newline="") as f:
                reader = csv.DictReader(f)
                rows = list(reader)
            if not rows:
                return
            self._questions = [{"text": h, "type": "テキスト", "options": []}
                                for h in rows[0].keys()]
            self._responses = [{i: row[h] for i, h in enumerate(rows[0].keys())}
                                for row in rows]
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}  ({len(rows)} 件)")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _export(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON", "*.json"), ("CSV", "*.csv")])
        if not path:
            return
        try:
            if path.endswith(".csv"):
                with open(path, "w", encoding="utf-8-sig", newline="") as f:
                    writer = csv.writer(f)
                    writer.writerow([f"Q{i+1}_{q['text']}"
                                     for i, q in enumerate(self._questions)])
                    for resp in self._responses:
                        row = [str(resp.get(i, "")) for i in range(len(self._questions))]
                        writer.writerow(row)
            else:
                with open(path, "w", encoding="utf-8") as f:
                    json.dump({"questions": self._questions,
                               "responses": self._responses}, f,
                              ensure_ascii=False, indent=2)
            messagebox.showinfo("完了", f"エクスポート: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))


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

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

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import csv
import os
import threading
from datetime import datetime

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


class App082:
    """アンケート集計ツール"""

    QUESTION_TYPES = ["単一選択", "複数選択", "テキスト", "評価(1-5)"]

    def __init__(self, root):
        self.root = root
        self.root.title("アンケート集計ツール")
        self.root.geometry("1060x660")
        self.root.configure(bg="#1e1e1e")
        self._questions = []   # [{"text": ..., "type": ..., "options": [...]}]
        self._responses = []   # [{q_idx: answer, ...}]
        self._build_ui()
        self._load_sample()

    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)

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        ttk.Button(tb, text="📂 JSON読み込み",
                   command=self._load_json).pack(side=tk.LEFT, padx=4)
        ttk.Button(tb, text="📂 CSV読み込み",
                   command=self._load_csv).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="💾 結果をエクスポート",
                   command=self._export).pack(side=tk.LEFT, padx=2)
        ttk.Button(tb, text="➕ 質問追加",
                   command=self._add_question).pack(side=tk.LEFT, padx=8)
        ttk.Button(tb, text="📝 回答を入力",
                   command=self._open_response_form).pack(side=tk.LEFT, padx=2)

        # メイン 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=320)
        paned.add(left, weight=0)
        tk.Label(left, text="質問一覧", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.q_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
                                     selectbackground="#1f6feb",
                                     font=("Arial", 9), relief=tk.FLAT)
        qsb = ttk.Scrollbar(left, command=self.q_listbox.yview)
        self.q_listbox.configure(yscrollcommand=qsb.set)
        qsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.q_listbox.pack(fill=tk.BOTH, expand=True)
        self.q_listbox.bind("<<ListboxSelect>>", self._on_q_select)

        info_f = tk.Frame(left, bg="#1e1e1e")
        info_f.pack(fill=tk.X, pady=4)
        self.resp_count_lbl = tk.Label(info_f, text="回答数: 0",
                                        bg="#1e1e1e", fg="#4fc3f7",
                                        font=("Arial", 10, "bold"))
        self.resp_count_lbl.pack(side=tk.LEFT, padx=4)

        # 右: グラフ + 集計
        right = tk.Frame(paned, bg="#1e1e1e")
        paned.add(right, weight=1)

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

        # 集計テーブル
        tk.Label(right, text="集計結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        cols = ("option", "count", "pct")
        self.result_tree = ttk.Treeview(right, columns=cols,
                                         show="headings", height=6)
        self.result_tree.heading("option", text="選択肢 / 回答")
        self.result_tree.heading("count",  text="件数")
        self.result_tree.heading("pct",    text="割合")
        self.result_tree.column("option", width=250, anchor="w")
        self.result_tree.column("count",  width=60,  anchor="center")
        self.result_tree.column("pct",    width=70,  anchor="center")
        rsb = ttk.Scrollbar(right, command=self.result_tree.yview)
        self.result_tree.configure(yscrollcommand=rsb.set)
        rsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.result_tree.pack(fill=tk.X)

        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 _load_sample(self):
        """サンプルアンケートを自動生成"""
        import random
        self._questions = [
            {"text": "Python の経験年数は?",
             "type": "単一選択",
             "options": ["1年未満", "1〜3年", "3〜5年", "5年以上"]},
            {"text": "使用するライブラリ (複数可)",
             "type": "複数選択",
             "options": ["NumPy", "Pandas", "Matplotlib", "Requests", "Flask", "Django"]},
            {"text": "Python の満足度",
             "type": "評価(1-5)",
             "options": []},
            {"text": "Python で改善してほしい点",
             "type": "テキスト",
             "options": []},
        ]
        # ランダム回答を 20件生成
        for _ in range(20):
            resp = {}
            resp[0] = random.choice(self._questions[0]["options"])
            sel = random.sample(self._questions[1]["options"],
                                 random.randint(1, 3))
            resp[1] = sel
            resp[2] = str(random.randint(2, 5))
            resp[3] = ""
            self._responses.append(resp)
        self._refresh_q_list()

    def _refresh_q_list(self):
        self.q_listbox.delete(0, tk.END)
        for i, q in enumerate(self._questions):
            self.q_listbox.insert(tk.END, f"Q{i+1}. {q['text']}")
        self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")

    def _on_q_select(self, _=None):
        sel = self.q_listbox.curselection()
        if not sel:
            return
        self._show_results(sel[0])

    def _show_results(self, q_idx):
        if q_idx >= len(self._questions):
            return
        q = self._questions[q_idx]
        q_type = q["type"]
        options = q["options"]
        n = len(self._responses)

        counter = {}
        for resp in self._responses:
            ans = resp.get(q_idx, "")
            if q_type == "複数選択" and isinstance(ans, list):
                for a in ans:
                    counter[a] = counter.get(a, 0) + 1
            elif ans:
                counter[str(ans)] = counter.get(str(ans), 0) + 1

        # テーブル
        self.result_tree.delete(*self.result_tree.get_children())
        sorted_items = sorted(counter.items(), key=lambda x: -x[1])
        for opt, cnt in sorted_items:
            pct = cnt / max(1, n) * 100
            self.result_tree.insert("", tk.END,
                                     values=(opt, cnt, f"{pct:.1f}%"))

        # グラフ
        if MATPLOTLIB_AVAILABLE and counter:
            self.ax.clear()
            self.ax.set_facecolor("#1e1e1e")
            labels = [k for k, _ in sorted_items]
            values = [v for _, v in sorted_items]

            if q_type in ("単一選択", "評価(1-5)"):
                self.ax.pie(values, labels=labels, autopct="%1.1f%%",
                             startangle=90,
                             textprops={"fontsize": 7, "color": "#c9d1d9"},
                             colors=["#4fc3f7", "#ef5350", "#26a69a",
                                     "#ffa726", "#ab47bc", "#66bb6a"])
            else:
                colors = ["#4fc3f7"] * len(labels)
                self.ax.barh(labels, values, color=colors)
                self.ax.tick_params(colors="#8b949e", labelsize=7)
                for spine in self.ax.spines.values():
                    spine.set_edgecolor("#30363d")

            self.ax.set_title(f"Q{q_idx+1}. {q['text'][:30]}",
                               color="#c9d1d9", fontsize=9)
            self.fig.tight_layout()
            self.mpl_canvas.draw()

        self.status_var.set(
            f"Q{q_idx+1}: {q['text']}  ({n} 件中 {sum(counter.values())} 件回答)")

    def _add_question(self):
        dlg = tk.Toplevel(self.root)
        dlg.title("質問を追加")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        tk.Label(dlg, text="質問文:", bg="#252526", fg="#ccc").pack(padx=12, pady=(12, 2), anchor="w")
        q_text = tk.Text(dlg, height=3, width=40, bg="#0d1117", fg="#c9d1d9",
                          relief=tk.FLAT, insertbackground="white")
        q_text.pack(padx=12)

        tk.Label(dlg, text="種別:", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        type_var = tk.StringVar(value="単一選択")
        ttk.Combobox(dlg, textvariable=type_var,
                     values=self.QUESTION_TYPES,
                     state="readonly", width=14).pack(padx=12)

        tk.Label(dlg, text="選択肢 (改行区切り):", bg="#252526", fg="#ccc").pack(padx=12, pady=(8, 2), anchor="w")
        opts_text = tk.Text(dlg, height=5, width=40, bg="#0d1117", fg="#c9d1d9",
                             relief=tk.FLAT, insertbackground="white")
        opts_text.pack(padx=12)

        def _ok():
            text = q_text.get("1.0", tk.END).strip()
            if not text:
                return
            opts = [o.strip() for o in opts_text.get("1.0", tk.END).splitlines() if o.strip()]
            self._questions.append({"text": text, "type": type_var.get(), "options": opts})
            self._refresh_q_list()
            dlg.destroy()

        ttk.Button(dlg, text="追加", command=_ok).pack(pady=8)

    def _open_response_form(self):
        if not self._questions:
            messagebox.showwarning("警告", "質問を追加してください")
            return
        dlg = tk.Toplevel(self.root)
        dlg.title("回答入力")
        dlg.configure(bg="#252526")
        dlg.grab_set()

        widgets = []
        for i, q in enumerate(self._questions):
            tk.Label(dlg, text=f"Q{i+1}. {q['text']}", bg="#252526", fg="#ccc",
                     font=("Arial", 9, "bold"),
                     wraplength=400, justify=tk.LEFT).pack(padx=12, pady=(8, 2), anchor="w")
            q_type = q["type"]
            if q_type == "単一選択":
                var = tk.StringVar()
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    tk.Radiobutton(f, text=opt, variable=var, value=opt,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                widgets.append(("single", var))
            elif q_type == "複数選択":
                vars_ = []
                f = tk.Frame(dlg, bg="#252526")
                f.pack(padx=12, anchor="w")
                for opt in q["options"]:
                    v = tk.BooleanVar()
                    tk.Checkbutton(f, text=opt, variable=v,
                                   bg="#252526", fg="#ccc", selectcolor="#3c3c3c",
                                   activebackground="#252526").pack(anchor="w")
                    vars_.append((opt, v))
                widgets.append(("multi", vars_))
            elif q_type == "評価(1-5)":
                var = tk.IntVar(value=3)
                ttk.Scale(dlg, from_=1, to=5, variable=var,
                           orient=tk.HORIZONTAL, length=200).pack(padx=12, anchor="w")
                lbl = tk.Label(dlg, textvariable=var, bg="#252526", fg="#4fc3f7",
                                font=("Arial", 10, "bold"))
                lbl.pack(padx=12, anchor="w")
                widgets.append(("rating", var))
            else:
                txt = tk.Text(dlg, height=2, width=40, bg="#0d1117", fg="#c9d1d9",
                               relief=tk.FLAT, insertbackground="white")
                txt.pack(padx=12, pady=2)
                widgets.append(("text", txt))

        def _submit():
            resp = {}
            for i, (wtype, widget) in enumerate(widgets):
                if wtype == "single":
                    resp[i] = widget.get()
                elif wtype == "multi":
                    resp[i] = [opt for opt, v in widget if v.get()]
                elif wtype == "rating":
                    resp[i] = str(widget.get())
                else:
                    resp[i] = widget.get("1.0", tk.END).strip()
            self._responses.append(resp)
            self.resp_count_lbl.config(text=f"回答数: {len(self._responses)}")
            self.status_var.set(f"回答を受け付けました ({len(self._responses)} 件)")
            dlg.destroy()

        ttk.Button(dlg, text="回答を送信", command=_submit).pack(pady=10)

    def _load_json(self):
        path = filedialog.askopenfilename(filetypes=[("JSON", "*.json")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8") as f:
                data = json.load(f)
            self._questions = data.get("questions", [])
            self._responses = data.get("responses", [])
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _load_csv(self):
        path = filedialog.askopenfilename(filetypes=[("CSV", "*.csv")])
        if not path:
            return
        try:
            with open(path, encoding="utf-8-sig", newline="") as f:
                reader = csv.DictReader(f)
                rows = list(reader)
            if not rows:
                return
            self._questions = [{"text": h, "type": "テキスト", "options": []}
                                for h in rows[0].keys()]
            self._responses = [{i: row[h] for i, h in enumerate(rows[0].keys())}
                                for row in rows]
            self._refresh_q_list()
            self.status_var.set(f"読み込み: {path}  ({len(rows)} 件)")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _export(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON", "*.json"), ("CSV", "*.csv")])
        if not path:
            return
        try:
            if path.endswith(".csv"):
                with open(path, "w", encoding="utf-8-sig", newline="") as f:
                    writer = csv.writer(f)
                    writer.writerow([f"Q{i+1}_{q['text']}"
                                     for i, q in enumerate(self._questions)])
                    for resp in self._responses:
                        row = [str(resp.get(i, "")) for i in range(len(self._questions))]
                        writer.writerow(row)
            else:
                with open(path, "w", encoding="utf-8") as f:
                    json.dump({"questions": self._questions,
                               "responses": self._responses}, f,
                              ensure_ascii=False, indent=2)
            messagebox.showinfo("完了", f"エクスポート: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))


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

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

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

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

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

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

    App082クラスを定義し、__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:保存機能の追加

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

🚀
次に挑戦するアプリ

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