中級者向け No.059

マルチタブテキストエディタ

タブ切り替えで複数ファイルを同時編集できる高機能テキストエディタ。Notebookウィジェットによるタブ管理と未保存検知を学ぶ。

🎯 難易度: ★★☆ 普通 📦 ライブラリ: tkinter ⏱️ 制作時間: 30〜90分

1. アプリ概要

タブ切り替えで複数ファイルを同時編集できる高機能テキストエディタ。Notebookウィジェットによるタブ管理と未保存検知を学ぶ。

このアプリはappカテゴリの実践的なPythonアプリです。使用ライブラリは tkinter、難易度は ★★☆ 普通 です。

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

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

2. 機能一覧

  • マルチタブテキストエディタのメイン機能
  • 直感的なGUIインターフェース
  • 入力値のバリデーション
  • エラーハンドリング
  • 結果の見やすい表示
  • クリア機能付き

3. 事前準備・環境

ℹ️
動作確認環境

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

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

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

4. 完全なソースコード

💡
コードのコピー方法

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

app059.py
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import re


class App059:
    """マルチタブテキストエディタ"""

    def __init__(self, root):
        self.root = root
        self.root.title("テキストエディタ")
        self.root.geometry("1000x680")
        self.root.configure(bg="#1e1e1e")
        self._tabs = {}
        self._build_ui()
        self._new_tab()

    def _build_ui(self):
        # メニューバー
        menubar = tk.Menu(self.root, bg="#252526", fg="#ccc",
                          activebackground="#094771", activeforeground="#fff",
                          bd=0)
        self.root.configure(menu=menubar)
        file_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="ファイル", menu=file_m)
        file_m.add_command(label="新規 (Ctrl+N)", command=self._new_tab)
        file_m.add_command(label="開く (Ctrl+O)", command=self._open)
        file_m.add_command(label="保存 (Ctrl+S)", command=self._save)
        file_m.add_command(label="名前を付けて保存", command=self._save_as)
        file_m.add_separator()
        file_m.add_command(label="タブを閉じる (Ctrl+W)", command=self._close_tab)
        file_m.add_command(label="終了", command=self.root.quit)

        edit_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="編集", menu=edit_m)
        edit_m.add_command(label="検索/置換 (Ctrl+H)", command=self._show_search)

        view_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="表示", menu=view_m)
        view_m.add_command(label="行番号 ON/OFF", command=self._toggle_lineno)
        view_m.add_command(label="ワードラップ切替", command=self._toggle_wrap)

        self.root.bind("<Control-n>", lambda e: self._new_tab())
        self.root.bind("<Control-o>", lambda e: self._open())
        self.root.bind("<Control-s>", lambda e: self._save())
        self.root.bind("<Control-w>", lambda e: self._close_tab())
        self.root.bind("<Control-h>", lambda e: self._show_search())

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        for text, cmd in [("📄 新規", self._new_tab), ("📂 開く", self._open),
                           ("💾 保存", self._save)]:
            tk.Button(tb, text=text, command=cmd, bg="#3c3c3c", fg="#ccc",
                      relief=tk.FLAT, font=("Arial", 9), padx=8, pady=2,
                      activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        tk.Label(tb, text="エンコード:", bg="#2d2d2d", fg="#888",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 4))
        self.enc_var = tk.StringVar(value="utf-8")
        ttk.Combobox(tb, textvariable=self.enc_var,
                     values=["utf-8", "utf-8-sig", "shift-jis", "cp932"],
                     state="readonly", width=10).pack(side=tk.LEFT)

        self.cursor_lbl = tk.Label(tb, text="行 1, 列 1", bg="#2d2d2d",
                                    fg="#888", font=("Arial", 9))
        self.cursor_lbl.pack(side=tk.RIGHT, padx=8)
        self.char_lbl = tk.Label(tb, text="0 文字", bg="#2d2d2d",
                                  fg="#888", font=("Arial", 9))
        self.char_lbl.pack(side=tk.RIGHT, padx=8)

        # 検索バー(非表示)
        self.search_bar = tk.Frame(self.root, bg="#252526", pady=4)
        tk.Label(self.search_bar, text="検索:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.search_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.search_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        tk.Label(self.search_bar, text="置換:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.replace_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.replace_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="次へ",
                   command=self._find_next).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="置換",
                   command=self._replace_one).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="全置換",
                   command=self._replace_all).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="✕",
                   command=self._hide_search).pack(side=tk.LEFT, padx=4)
        self._search_visible = False

        # ノートブック
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill=tk.BOTH, expand=True)
        self.notebook.bind("<<NotebookTabChanged>>", self._on_tab_changed)

        # ステータスバー
        self.status_var = tk.StringVar(value="準備完了")
        self._show_lineno = True
        self._wrap_mode = tk.NONE
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#007acc", fg="#fff", font=("Arial", 8),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── タブ管理 ──────────────────────────────────────────────────

    def _new_tab(self, path=None, content=""):
        frame = tk.Frame(self.notebook, bg="#1e1e1e")
        code_area = tk.Frame(frame, bg="#1e1e1e")
        code_area.pack(fill=tk.BOTH, expand=True)

        line_canvas = tk.Canvas(code_area, width=40, bg="#0d1117",
                                 highlightthickness=0)
        line_canvas.pack(side=tk.LEFT, fill=tk.Y)

        text = tk.Text(code_area, bg="#0d1117", fg="#d4d4d4",
                        font=("Courier New", 11), relief=tk.FLAT,
                        insertbackground="#fff",
                        selectbackground="#264f78",
                        undo=True, wrap=self._wrap_mode, tabs=("4m",))
        ysb = ttk.Scrollbar(code_area, command=text.yview)
        xsb = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=text.xview)
        text.configure(yscrollcommand=ysb.set, xscrollcommand=xsb.set)
        ysb.pack(side=tk.RIGHT, fill=tk.Y)
        text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        xsb.pack(fill=tk.X)

        if content:
            text.insert("1.0", content)

        label = os.path.basename(path) if path else "無題"
        self.notebook.add(frame, text=f"  {label}  ")
        tid = id(frame)
        self._tabs[tid] = {
            "path": path, "editor": text,
            "line_canvas": line_canvas,
            "modified": bool(content and not path),
            "frame": frame,
        }

        def on_key(e, t=tid):
            info = self._tabs.get(t)
            if info and not info["modified"]:
                info["modified"] = True
                idx = self.notebook.index(info["frame"])
                cur = self.notebook.tab(idx, "text")
                if not cur.startswith("●"):
                    self.notebook.tab(idx, text="● " + cur.strip())
            self._update_lineno(t)
            self._update_stats(text)

        text.bind("<KeyRelease>", on_key)
        text.bind("<ButtonRelease-1>", lambda e: self._update_stats(text))
        self.notebook.select(frame)
        self._update_lineno(tid)

    def _current(self):
        try:
            frame = self.notebook.nametowidget(self.notebook.select())
            return id(frame), self._tabs.get(id(frame))
        except Exception:
            return None, None

    def _on_tab_changed(self, event=None):
        _, info = self._current()
        if info:
            self.status_var.set(info["path"] or "無題")

    def _close_tab(self):
        tid, info = self._current()
        if not info:
            return
        if info["modified"]:
            name = os.path.basename(info["path"]) if info["path"] else "無題"
            ans = messagebox.askyesnocancel("保存確認",
                                             f"「{name}」の変更を保存しますか?")
            if ans is None:
                return
            if ans:
                self._save()
        frame = info["frame"]
        self.notebook.forget(frame)
        del self._tabs[tid]

    # ── ファイル操作 ──────────────────────────────────────────────

    def _open(self):
        path = filedialog.askopenfilename(
            filetypes=[("テキスト", "*.txt *.py *.md *.csv *.json *.html *.css *.js"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            enc = self.enc_var.get()
            with open(path, encoding=enc, errors="replace") as f:
                content = f.read()
            self._new_tab(path=path, content=content)
            _, info = self._current()
            if info:
                info["modified"] = False
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _save(self):
        tid, info = self._current()
        if not info:
            return
        if not info["path"]:
            self._save_as()
            return
        self._do_save(tid, info, info["path"])

    def _save_as(self):
        tid, info = self._current()
        if not info:
            return
        path = filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=[("テキスト", "*.txt"), ("Python", "*.py"),
                       ("すべて", "*.*")])
        if path:
            self._do_save(tid, info, path)

    def _do_save(self, tid, info, path):
        try:
            enc = self.enc_var.get()
            with open(path, "w", encoding=enc) as f:
                f.write(info["editor"].get("1.0", tk.END))
            info["path"] = path
            info["modified"] = False
            idx = self.notebook.index(info["frame"])
            self.notebook.tab(idx, text=f"  {os.path.basename(path)}  ")
            self.status_var.set(f"保存: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    # ── 表示 ──────────────────────────────────────────────────────

    def _toggle_lineno(self):
        self._show_lineno = not self._show_lineno
        _, info = self._current()
        if info:
            if self._show_lineno:
                info["line_canvas"].pack(before=info["editor"], side=tk.LEFT, fill=tk.Y)
            else:
                info["line_canvas"].pack_forget()

    def _toggle_wrap(self):
        self._wrap_mode = tk.WORD if self._wrap_mode == tk.NONE else tk.NONE
        _, info = self._current()
        if info:
            info["editor"].configure(wrap=self._wrap_mode)

    def _update_lineno(self, tid):
        info = self._tabs.get(tid)
        if not info or not self._show_lineno:
            return
        editor = info["editor"]
        lc = info["line_canvas"]
        lc.delete("all")
        try:
            ln = int(editor.index("@0,0").split(".")[0])
            while True:
                dl = editor.dlineinfo(f"{ln}.0")
                if dl is None:
                    break
                lc.create_text(36, dl[1] + dl[3]//2,
                                text=str(ln), anchor="e",
                                fill="#858585", font=("Courier New", 11))
                ln += 1
        except Exception:
            pass

    def _update_stats(self, editor):
        try:
            pos = editor.index(tk.INSERT).split(".")
            self.cursor_lbl.config(text=f"行 {pos[0]}, 列 {int(pos[1])+1}")
            chars = len(editor.get("1.0", tk.END)) - 1
            self.char_lbl.config(text=f"{chars:,} 文字")
        except Exception:
            pass

    # ── 検索・置換 ────────────────────────────────────────────────

    def _show_search(self):
        if not self._search_visible:
            self.search_bar.pack(fill=tk.X, before=self.notebook)
            self._search_visible = True

    def _hide_search(self):
        if self._search_visible:
            self.search_bar.pack_forget()
            self._search_visible = False

    def _get_editor(self):
        _, info = self._current()
        return info["editor"] if info else None

    def _find_next(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        if not query:
            return
        pos = editor.search(query, tk.INSERT, stopindex=tk.END)
        if not pos:
            pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.mark_set(tk.INSERT, end)
            editor.see(pos)
            editor.tag_remove("sel", "1.0", tk.END)
            editor.tag_add("sel", pos, end)

    def _replace_one(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.delete(pos, end)
            editor.insert(pos, rep)

    def _replace_all(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        content = editor.get("1.0", tk.END)
        count = content.count(query)
        if count:
            editor.delete("1.0", tk.END)
            editor.insert("1.0", content.replace(query, rep))
            self.status_var.set(f"{count} 件置換")


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

5. コード解説

マルチタブテキストエディタのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。

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

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import re


class App059:
    """マルチタブテキストエディタ"""

    def __init__(self, root):
        self.root = root
        self.root.title("テキストエディタ")
        self.root.geometry("1000x680")
        self.root.configure(bg="#1e1e1e")
        self._tabs = {}
        self._build_ui()
        self._new_tab()

    def _build_ui(self):
        # メニューバー
        menubar = tk.Menu(self.root, bg="#252526", fg="#ccc",
                          activebackground="#094771", activeforeground="#fff",
                          bd=0)
        self.root.configure(menu=menubar)
        file_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="ファイル", menu=file_m)
        file_m.add_command(label="新規 (Ctrl+N)", command=self._new_tab)
        file_m.add_command(label="開く (Ctrl+O)", command=self._open)
        file_m.add_command(label="保存 (Ctrl+S)", command=self._save)
        file_m.add_command(label="名前を付けて保存", command=self._save_as)
        file_m.add_separator()
        file_m.add_command(label="タブを閉じる (Ctrl+W)", command=self._close_tab)
        file_m.add_command(label="終了", command=self.root.quit)

        edit_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="編集", menu=edit_m)
        edit_m.add_command(label="検索/置換 (Ctrl+H)", command=self._show_search)

        view_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="表示", menu=view_m)
        view_m.add_command(label="行番号 ON/OFF", command=self._toggle_lineno)
        view_m.add_command(label="ワードラップ切替", command=self._toggle_wrap)

        self.root.bind("<Control-n>", lambda e: self._new_tab())
        self.root.bind("<Control-o>", lambda e: self._open())
        self.root.bind("<Control-s>", lambda e: self._save())
        self.root.bind("<Control-w>", lambda e: self._close_tab())
        self.root.bind("<Control-h>", lambda e: self._show_search())

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        for text, cmd in [("📄 新規", self._new_tab), ("📂 開く", self._open),
                           ("💾 保存", self._save)]:
            tk.Button(tb, text=text, command=cmd, bg="#3c3c3c", fg="#ccc",
                      relief=tk.FLAT, font=("Arial", 9), padx=8, pady=2,
                      activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        tk.Label(tb, text="エンコード:", bg="#2d2d2d", fg="#888",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 4))
        self.enc_var = tk.StringVar(value="utf-8")
        ttk.Combobox(tb, textvariable=self.enc_var,
                     values=["utf-8", "utf-8-sig", "shift-jis", "cp932"],
                     state="readonly", width=10).pack(side=tk.LEFT)

        self.cursor_lbl = tk.Label(tb, text="行 1, 列 1", bg="#2d2d2d",
                                    fg="#888", font=("Arial", 9))
        self.cursor_lbl.pack(side=tk.RIGHT, padx=8)
        self.char_lbl = tk.Label(tb, text="0 文字", bg="#2d2d2d",
                                  fg="#888", font=("Arial", 9))
        self.char_lbl.pack(side=tk.RIGHT, padx=8)

        # 検索バー(非表示)
        self.search_bar = tk.Frame(self.root, bg="#252526", pady=4)
        tk.Label(self.search_bar, text="検索:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.search_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.search_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        tk.Label(self.search_bar, text="置換:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.replace_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.replace_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="次へ",
                   command=self._find_next).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="置換",
                   command=self._replace_one).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="全置換",
                   command=self._replace_all).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="✕",
                   command=self._hide_search).pack(side=tk.LEFT, padx=4)
        self._search_visible = False

        # ノートブック
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill=tk.BOTH, expand=True)
        self.notebook.bind("<<NotebookTabChanged>>", self._on_tab_changed)

        # ステータスバー
        self.status_var = tk.StringVar(value="準備完了")
        self._show_lineno = True
        self._wrap_mode = tk.NONE
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#007acc", fg="#fff", font=("Arial", 8),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── タブ管理 ──────────────────────────────────────────────────

    def _new_tab(self, path=None, content=""):
        frame = tk.Frame(self.notebook, bg="#1e1e1e")
        code_area = tk.Frame(frame, bg="#1e1e1e")
        code_area.pack(fill=tk.BOTH, expand=True)

        line_canvas = tk.Canvas(code_area, width=40, bg="#0d1117",
                                 highlightthickness=0)
        line_canvas.pack(side=tk.LEFT, fill=tk.Y)

        text = tk.Text(code_area, bg="#0d1117", fg="#d4d4d4",
                        font=("Courier New", 11), relief=tk.FLAT,
                        insertbackground="#fff",
                        selectbackground="#264f78",
                        undo=True, wrap=self._wrap_mode, tabs=("4m",))
        ysb = ttk.Scrollbar(code_area, command=text.yview)
        xsb = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=text.xview)
        text.configure(yscrollcommand=ysb.set, xscrollcommand=xsb.set)
        ysb.pack(side=tk.RIGHT, fill=tk.Y)
        text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        xsb.pack(fill=tk.X)

        if content:
            text.insert("1.0", content)

        label = os.path.basename(path) if path else "無題"
        self.notebook.add(frame, text=f"  {label}  ")
        tid = id(frame)
        self._tabs[tid] = {
            "path": path, "editor": text,
            "line_canvas": line_canvas,
            "modified": bool(content and not path),
            "frame": frame,
        }

        def on_key(e, t=tid):
            info = self._tabs.get(t)
            if info and not info["modified"]:
                info["modified"] = True
                idx = self.notebook.index(info["frame"])
                cur = self.notebook.tab(idx, "text")
                if not cur.startswith("●"):
                    self.notebook.tab(idx, text="● " + cur.strip())
            self._update_lineno(t)
            self._update_stats(text)

        text.bind("<KeyRelease>", on_key)
        text.bind("<ButtonRelease-1>", lambda e: self._update_stats(text))
        self.notebook.select(frame)
        self._update_lineno(tid)

    def _current(self):
        try:
            frame = self.notebook.nametowidget(self.notebook.select())
            return id(frame), self._tabs.get(id(frame))
        except Exception:
            return None, None

    def _on_tab_changed(self, event=None):
        _, info = self._current()
        if info:
            self.status_var.set(info["path"] or "無題")

    def _close_tab(self):
        tid, info = self._current()
        if not info:
            return
        if info["modified"]:
            name = os.path.basename(info["path"]) if info["path"] else "無題"
            ans = messagebox.askyesnocancel("保存確認",
                                             f"「{name}」の変更を保存しますか?")
            if ans is None:
                return
            if ans:
                self._save()
        frame = info["frame"]
        self.notebook.forget(frame)
        del self._tabs[tid]

    # ── ファイル操作 ──────────────────────────────────────────────

    def _open(self):
        path = filedialog.askopenfilename(
            filetypes=[("テキスト", "*.txt *.py *.md *.csv *.json *.html *.css *.js"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            enc = self.enc_var.get()
            with open(path, encoding=enc, errors="replace") as f:
                content = f.read()
            self._new_tab(path=path, content=content)
            _, info = self._current()
            if info:
                info["modified"] = False
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _save(self):
        tid, info = self._current()
        if not info:
            return
        if not info["path"]:
            self._save_as()
            return
        self._do_save(tid, info, info["path"])

    def _save_as(self):
        tid, info = self._current()
        if not info:
            return
        path = filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=[("テキスト", "*.txt"), ("Python", "*.py"),
                       ("すべて", "*.*")])
        if path:
            self._do_save(tid, info, path)

    def _do_save(self, tid, info, path):
        try:
            enc = self.enc_var.get()
            with open(path, "w", encoding=enc) as f:
                f.write(info["editor"].get("1.0", tk.END))
            info["path"] = path
            info["modified"] = False
            idx = self.notebook.index(info["frame"])
            self.notebook.tab(idx, text=f"  {os.path.basename(path)}  ")
            self.status_var.set(f"保存: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    # ── 表示 ──────────────────────────────────────────────────────

    def _toggle_lineno(self):
        self._show_lineno = not self._show_lineno
        _, info = self._current()
        if info:
            if self._show_lineno:
                info["line_canvas"].pack(before=info["editor"], side=tk.LEFT, fill=tk.Y)
            else:
                info["line_canvas"].pack_forget()

    def _toggle_wrap(self):
        self._wrap_mode = tk.WORD if self._wrap_mode == tk.NONE else tk.NONE
        _, info = self._current()
        if info:
            info["editor"].configure(wrap=self._wrap_mode)

    def _update_lineno(self, tid):
        info = self._tabs.get(tid)
        if not info or not self._show_lineno:
            return
        editor = info["editor"]
        lc = info["line_canvas"]
        lc.delete("all")
        try:
            ln = int(editor.index("@0,0").split(".")[0])
            while True:
                dl = editor.dlineinfo(f"{ln}.0")
                if dl is None:
                    break
                lc.create_text(36, dl[1] + dl[3]//2,
                                text=str(ln), anchor="e",
                                fill="#858585", font=("Courier New", 11))
                ln += 1
        except Exception:
            pass

    def _update_stats(self, editor):
        try:
            pos = editor.index(tk.INSERT).split(".")
            self.cursor_lbl.config(text=f"行 {pos[0]}, 列 {int(pos[1])+1}")
            chars = len(editor.get("1.0", tk.END)) - 1
            self.char_lbl.config(text=f"{chars:,} 文字")
        except Exception:
            pass

    # ── 検索・置換 ────────────────────────────────────────────────

    def _show_search(self):
        if not self._search_visible:
            self.search_bar.pack(fill=tk.X, before=self.notebook)
            self._search_visible = True

    def _hide_search(self):
        if self._search_visible:
            self.search_bar.pack_forget()
            self._search_visible = False

    def _get_editor(self):
        _, info = self._current()
        return info["editor"] if info else None

    def _find_next(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        if not query:
            return
        pos = editor.search(query, tk.INSERT, stopindex=tk.END)
        if not pos:
            pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.mark_set(tk.INSERT, end)
            editor.see(pos)
            editor.tag_remove("sel", "1.0", tk.END)
            editor.tag_add("sel", pos, end)

    def _replace_one(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.delete(pos, end)
            editor.insert(pos, rep)

    def _replace_all(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        content = editor.get("1.0", tk.END)
        count = content.count(query)
        if count:
            editor.delete("1.0", tk.END)
            editor.insert("1.0", content.replace(query, rep))
            self.status_var.set(f"{count} 件置換")


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

UIレイアウトの構築

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import re


class App059:
    """マルチタブテキストエディタ"""

    def __init__(self, root):
        self.root = root
        self.root.title("テキストエディタ")
        self.root.geometry("1000x680")
        self.root.configure(bg="#1e1e1e")
        self._tabs = {}
        self._build_ui()
        self._new_tab()

    def _build_ui(self):
        # メニューバー
        menubar = tk.Menu(self.root, bg="#252526", fg="#ccc",
                          activebackground="#094771", activeforeground="#fff",
                          bd=0)
        self.root.configure(menu=menubar)
        file_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="ファイル", menu=file_m)
        file_m.add_command(label="新規 (Ctrl+N)", command=self._new_tab)
        file_m.add_command(label="開く (Ctrl+O)", command=self._open)
        file_m.add_command(label="保存 (Ctrl+S)", command=self._save)
        file_m.add_command(label="名前を付けて保存", command=self._save_as)
        file_m.add_separator()
        file_m.add_command(label="タブを閉じる (Ctrl+W)", command=self._close_tab)
        file_m.add_command(label="終了", command=self.root.quit)

        edit_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="編集", menu=edit_m)
        edit_m.add_command(label="検索/置換 (Ctrl+H)", command=self._show_search)

        view_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="表示", menu=view_m)
        view_m.add_command(label="行番号 ON/OFF", command=self._toggle_lineno)
        view_m.add_command(label="ワードラップ切替", command=self._toggle_wrap)

        self.root.bind("<Control-n>", lambda e: self._new_tab())
        self.root.bind("<Control-o>", lambda e: self._open())
        self.root.bind("<Control-s>", lambda e: self._save())
        self.root.bind("<Control-w>", lambda e: self._close_tab())
        self.root.bind("<Control-h>", lambda e: self._show_search())

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        for text, cmd in [("📄 新規", self._new_tab), ("📂 開く", self._open),
                           ("💾 保存", self._save)]:
            tk.Button(tb, text=text, command=cmd, bg="#3c3c3c", fg="#ccc",
                      relief=tk.FLAT, font=("Arial", 9), padx=8, pady=2,
                      activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        tk.Label(tb, text="エンコード:", bg="#2d2d2d", fg="#888",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 4))
        self.enc_var = tk.StringVar(value="utf-8")
        ttk.Combobox(tb, textvariable=self.enc_var,
                     values=["utf-8", "utf-8-sig", "shift-jis", "cp932"],
                     state="readonly", width=10).pack(side=tk.LEFT)

        self.cursor_lbl = tk.Label(tb, text="行 1, 列 1", bg="#2d2d2d",
                                    fg="#888", font=("Arial", 9))
        self.cursor_lbl.pack(side=tk.RIGHT, padx=8)
        self.char_lbl = tk.Label(tb, text="0 文字", bg="#2d2d2d",
                                  fg="#888", font=("Arial", 9))
        self.char_lbl.pack(side=tk.RIGHT, padx=8)

        # 検索バー(非表示)
        self.search_bar = tk.Frame(self.root, bg="#252526", pady=4)
        tk.Label(self.search_bar, text="検索:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.search_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.search_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        tk.Label(self.search_bar, text="置換:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.replace_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.replace_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="次へ",
                   command=self._find_next).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="置換",
                   command=self._replace_one).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="全置換",
                   command=self._replace_all).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="✕",
                   command=self._hide_search).pack(side=tk.LEFT, padx=4)
        self._search_visible = False

        # ノートブック
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill=tk.BOTH, expand=True)
        self.notebook.bind("<<NotebookTabChanged>>", self._on_tab_changed)

        # ステータスバー
        self.status_var = tk.StringVar(value="準備完了")
        self._show_lineno = True
        self._wrap_mode = tk.NONE
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#007acc", fg="#fff", font=("Arial", 8),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── タブ管理 ──────────────────────────────────────────────────

    def _new_tab(self, path=None, content=""):
        frame = tk.Frame(self.notebook, bg="#1e1e1e")
        code_area = tk.Frame(frame, bg="#1e1e1e")
        code_area.pack(fill=tk.BOTH, expand=True)

        line_canvas = tk.Canvas(code_area, width=40, bg="#0d1117",
                                 highlightthickness=0)
        line_canvas.pack(side=tk.LEFT, fill=tk.Y)

        text = tk.Text(code_area, bg="#0d1117", fg="#d4d4d4",
                        font=("Courier New", 11), relief=tk.FLAT,
                        insertbackground="#fff",
                        selectbackground="#264f78",
                        undo=True, wrap=self._wrap_mode, tabs=("4m",))
        ysb = ttk.Scrollbar(code_area, command=text.yview)
        xsb = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=text.xview)
        text.configure(yscrollcommand=ysb.set, xscrollcommand=xsb.set)
        ysb.pack(side=tk.RIGHT, fill=tk.Y)
        text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        xsb.pack(fill=tk.X)

        if content:
            text.insert("1.0", content)

        label = os.path.basename(path) if path else "無題"
        self.notebook.add(frame, text=f"  {label}  ")
        tid = id(frame)
        self._tabs[tid] = {
            "path": path, "editor": text,
            "line_canvas": line_canvas,
            "modified": bool(content and not path),
            "frame": frame,
        }

        def on_key(e, t=tid):
            info = self._tabs.get(t)
            if info and not info["modified"]:
                info["modified"] = True
                idx = self.notebook.index(info["frame"])
                cur = self.notebook.tab(idx, "text")
                if not cur.startswith("●"):
                    self.notebook.tab(idx, text="● " + cur.strip())
            self._update_lineno(t)
            self._update_stats(text)

        text.bind("<KeyRelease>", on_key)
        text.bind("<ButtonRelease-1>", lambda e: self._update_stats(text))
        self.notebook.select(frame)
        self._update_lineno(tid)

    def _current(self):
        try:
            frame = self.notebook.nametowidget(self.notebook.select())
            return id(frame), self._tabs.get(id(frame))
        except Exception:
            return None, None

    def _on_tab_changed(self, event=None):
        _, info = self._current()
        if info:
            self.status_var.set(info["path"] or "無題")

    def _close_tab(self):
        tid, info = self._current()
        if not info:
            return
        if info["modified"]:
            name = os.path.basename(info["path"]) if info["path"] else "無題"
            ans = messagebox.askyesnocancel("保存確認",
                                             f"「{name}」の変更を保存しますか?")
            if ans is None:
                return
            if ans:
                self._save()
        frame = info["frame"]
        self.notebook.forget(frame)
        del self._tabs[tid]

    # ── ファイル操作 ──────────────────────────────────────────────

    def _open(self):
        path = filedialog.askopenfilename(
            filetypes=[("テキスト", "*.txt *.py *.md *.csv *.json *.html *.css *.js"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            enc = self.enc_var.get()
            with open(path, encoding=enc, errors="replace") as f:
                content = f.read()
            self._new_tab(path=path, content=content)
            _, info = self._current()
            if info:
                info["modified"] = False
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _save(self):
        tid, info = self._current()
        if not info:
            return
        if not info["path"]:
            self._save_as()
            return
        self._do_save(tid, info, info["path"])

    def _save_as(self):
        tid, info = self._current()
        if not info:
            return
        path = filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=[("テキスト", "*.txt"), ("Python", "*.py"),
                       ("すべて", "*.*")])
        if path:
            self._do_save(tid, info, path)

    def _do_save(self, tid, info, path):
        try:
            enc = self.enc_var.get()
            with open(path, "w", encoding=enc) as f:
                f.write(info["editor"].get("1.0", tk.END))
            info["path"] = path
            info["modified"] = False
            idx = self.notebook.index(info["frame"])
            self.notebook.tab(idx, text=f"  {os.path.basename(path)}  ")
            self.status_var.set(f"保存: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    # ── 表示 ──────────────────────────────────────────────────────

    def _toggle_lineno(self):
        self._show_lineno = not self._show_lineno
        _, info = self._current()
        if info:
            if self._show_lineno:
                info["line_canvas"].pack(before=info["editor"], side=tk.LEFT, fill=tk.Y)
            else:
                info["line_canvas"].pack_forget()

    def _toggle_wrap(self):
        self._wrap_mode = tk.WORD if self._wrap_mode == tk.NONE else tk.NONE
        _, info = self._current()
        if info:
            info["editor"].configure(wrap=self._wrap_mode)

    def _update_lineno(self, tid):
        info = self._tabs.get(tid)
        if not info or not self._show_lineno:
            return
        editor = info["editor"]
        lc = info["line_canvas"]
        lc.delete("all")
        try:
            ln = int(editor.index("@0,0").split(".")[0])
            while True:
                dl = editor.dlineinfo(f"{ln}.0")
                if dl is None:
                    break
                lc.create_text(36, dl[1] + dl[3]//2,
                                text=str(ln), anchor="e",
                                fill="#858585", font=("Courier New", 11))
                ln += 1
        except Exception:
            pass

    def _update_stats(self, editor):
        try:
            pos = editor.index(tk.INSERT).split(".")
            self.cursor_lbl.config(text=f"行 {pos[0]}, 列 {int(pos[1])+1}")
            chars = len(editor.get("1.0", tk.END)) - 1
            self.char_lbl.config(text=f"{chars:,} 文字")
        except Exception:
            pass

    # ── 検索・置換 ────────────────────────────────────────────────

    def _show_search(self):
        if not self._search_visible:
            self.search_bar.pack(fill=tk.X, before=self.notebook)
            self._search_visible = True

    def _hide_search(self):
        if self._search_visible:
            self.search_bar.pack_forget()
            self._search_visible = False

    def _get_editor(self):
        _, info = self._current()
        return info["editor"] if info else None

    def _find_next(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        if not query:
            return
        pos = editor.search(query, tk.INSERT, stopindex=tk.END)
        if not pos:
            pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.mark_set(tk.INSERT, end)
            editor.see(pos)
            editor.tag_remove("sel", "1.0", tk.END)
            editor.tag_add("sel", pos, end)

    def _replace_one(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.delete(pos, end)
            editor.insert(pos, rep)

    def _replace_all(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        content = editor.get("1.0", tk.END)
        count = content.count(query)
        if count:
            editor.delete("1.0", tk.END)
            editor.insert("1.0", content.replace(query, rep))
            self.status_var.set(f"{count} 件置換")


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

イベント処理

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import re


class App059:
    """マルチタブテキストエディタ"""

    def __init__(self, root):
        self.root = root
        self.root.title("テキストエディタ")
        self.root.geometry("1000x680")
        self.root.configure(bg="#1e1e1e")
        self._tabs = {}
        self._build_ui()
        self._new_tab()

    def _build_ui(self):
        # メニューバー
        menubar = tk.Menu(self.root, bg="#252526", fg="#ccc",
                          activebackground="#094771", activeforeground="#fff",
                          bd=0)
        self.root.configure(menu=menubar)
        file_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="ファイル", menu=file_m)
        file_m.add_command(label="新規 (Ctrl+N)", command=self._new_tab)
        file_m.add_command(label="開く (Ctrl+O)", command=self._open)
        file_m.add_command(label="保存 (Ctrl+S)", command=self._save)
        file_m.add_command(label="名前を付けて保存", command=self._save_as)
        file_m.add_separator()
        file_m.add_command(label="タブを閉じる (Ctrl+W)", command=self._close_tab)
        file_m.add_command(label="終了", command=self.root.quit)

        edit_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="編集", menu=edit_m)
        edit_m.add_command(label="検索/置換 (Ctrl+H)", command=self._show_search)

        view_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="表示", menu=view_m)
        view_m.add_command(label="行番号 ON/OFF", command=self._toggle_lineno)
        view_m.add_command(label="ワードラップ切替", command=self._toggle_wrap)

        self.root.bind("<Control-n>", lambda e: self._new_tab())
        self.root.bind("<Control-o>", lambda e: self._open())
        self.root.bind("<Control-s>", lambda e: self._save())
        self.root.bind("<Control-w>", lambda e: self._close_tab())
        self.root.bind("<Control-h>", lambda e: self._show_search())

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        for text, cmd in [("📄 新規", self._new_tab), ("📂 開く", self._open),
                           ("💾 保存", self._save)]:
            tk.Button(tb, text=text, command=cmd, bg="#3c3c3c", fg="#ccc",
                      relief=tk.FLAT, font=("Arial", 9), padx=8, pady=2,
                      activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        tk.Label(tb, text="エンコード:", bg="#2d2d2d", fg="#888",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 4))
        self.enc_var = tk.StringVar(value="utf-8")
        ttk.Combobox(tb, textvariable=self.enc_var,
                     values=["utf-8", "utf-8-sig", "shift-jis", "cp932"],
                     state="readonly", width=10).pack(side=tk.LEFT)

        self.cursor_lbl = tk.Label(tb, text="行 1, 列 1", bg="#2d2d2d",
                                    fg="#888", font=("Arial", 9))
        self.cursor_lbl.pack(side=tk.RIGHT, padx=8)
        self.char_lbl = tk.Label(tb, text="0 文字", bg="#2d2d2d",
                                  fg="#888", font=("Arial", 9))
        self.char_lbl.pack(side=tk.RIGHT, padx=8)

        # 検索バー(非表示)
        self.search_bar = tk.Frame(self.root, bg="#252526", pady=4)
        tk.Label(self.search_bar, text="検索:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.search_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.search_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        tk.Label(self.search_bar, text="置換:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.replace_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.replace_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="次へ",
                   command=self._find_next).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="置換",
                   command=self._replace_one).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="全置換",
                   command=self._replace_all).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="✕",
                   command=self._hide_search).pack(side=tk.LEFT, padx=4)
        self._search_visible = False

        # ノートブック
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill=tk.BOTH, expand=True)
        self.notebook.bind("<<NotebookTabChanged>>", self._on_tab_changed)

        # ステータスバー
        self.status_var = tk.StringVar(value="準備完了")
        self._show_lineno = True
        self._wrap_mode = tk.NONE
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#007acc", fg="#fff", font=("Arial", 8),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── タブ管理 ──────────────────────────────────────────────────

    def _new_tab(self, path=None, content=""):
        frame = tk.Frame(self.notebook, bg="#1e1e1e")
        code_area = tk.Frame(frame, bg="#1e1e1e")
        code_area.pack(fill=tk.BOTH, expand=True)

        line_canvas = tk.Canvas(code_area, width=40, bg="#0d1117",
                                 highlightthickness=0)
        line_canvas.pack(side=tk.LEFT, fill=tk.Y)

        text = tk.Text(code_area, bg="#0d1117", fg="#d4d4d4",
                        font=("Courier New", 11), relief=tk.FLAT,
                        insertbackground="#fff",
                        selectbackground="#264f78",
                        undo=True, wrap=self._wrap_mode, tabs=("4m",))
        ysb = ttk.Scrollbar(code_area, command=text.yview)
        xsb = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=text.xview)
        text.configure(yscrollcommand=ysb.set, xscrollcommand=xsb.set)
        ysb.pack(side=tk.RIGHT, fill=tk.Y)
        text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        xsb.pack(fill=tk.X)

        if content:
            text.insert("1.0", content)

        label = os.path.basename(path) if path else "無題"
        self.notebook.add(frame, text=f"  {label}  ")
        tid = id(frame)
        self._tabs[tid] = {
            "path": path, "editor": text,
            "line_canvas": line_canvas,
            "modified": bool(content and not path),
            "frame": frame,
        }

        def on_key(e, t=tid):
            info = self._tabs.get(t)
            if info and not info["modified"]:
                info["modified"] = True
                idx = self.notebook.index(info["frame"])
                cur = self.notebook.tab(idx, "text")
                if not cur.startswith("●"):
                    self.notebook.tab(idx, text="● " + cur.strip())
            self._update_lineno(t)
            self._update_stats(text)

        text.bind("<KeyRelease>", on_key)
        text.bind("<ButtonRelease-1>", lambda e: self._update_stats(text))
        self.notebook.select(frame)
        self._update_lineno(tid)

    def _current(self):
        try:
            frame = self.notebook.nametowidget(self.notebook.select())
            return id(frame), self._tabs.get(id(frame))
        except Exception:
            return None, None

    def _on_tab_changed(self, event=None):
        _, info = self._current()
        if info:
            self.status_var.set(info["path"] or "無題")

    def _close_tab(self):
        tid, info = self._current()
        if not info:
            return
        if info["modified"]:
            name = os.path.basename(info["path"]) if info["path"] else "無題"
            ans = messagebox.askyesnocancel("保存確認",
                                             f"「{name}」の変更を保存しますか?")
            if ans is None:
                return
            if ans:
                self._save()
        frame = info["frame"]
        self.notebook.forget(frame)
        del self._tabs[tid]

    # ── ファイル操作 ──────────────────────────────────────────────

    def _open(self):
        path = filedialog.askopenfilename(
            filetypes=[("テキスト", "*.txt *.py *.md *.csv *.json *.html *.css *.js"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            enc = self.enc_var.get()
            with open(path, encoding=enc, errors="replace") as f:
                content = f.read()
            self._new_tab(path=path, content=content)
            _, info = self._current()
            if info:
                info["modified"] = False
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _save(self):
        tid, info = self._current()
        if not info:
            return
        if not info["path"]:
            self._save_as()
            return
        self._do_save(tid, info, info["path"])

    def _save_as(self):
        tid, info = self._current()
        if not info:
            return
        path = filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=[("テキスト", "*.txt"), ("Python", "*.py"),
                       ("すべて", "*.*")])
        if path:
            self._do_save(tid, info, path)

    def _do_save(self, tid, info, path):
        try:
            enc = self.enc_var.get()
            with open(path, "w", encoding=enc) as f:
                f.write(info["editor"].get("1.0", tk.END))
            info["path"] = path
            info["modified"] = False
            idx = self.notebook.index(info["frame"])
            self.notebook.tab(idx, text=f"  {os.path.basename(path)}  ")
            self.status_var.set(f"保存: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    # ── 表示 ──────────────────────────────────────────────────────

    def _toggle_lineno(self):
        self._show_lineno = not self._show_lineno
        _, info = self._current()
        if info:
            if self._show_lineno:
                info["line_canvas"].pack(before=info["editor"], side=tk.LEFT, fill=tk.Y)
            else:
                info["line_canvas"].pack_forget()

    def _toggle_wrap(self):
        self._wrap_mode = tk.WORD if self._wrap_mode == tk.NONE else tk.NONE
        _, info = self._current()
        if info:
            info["editor"].configure(wrap=self._wrap_mode)

    def _update_lineno(self, tid):
        info = self._tabs.get(tid)
        if not info or not self._show_lineno:
            return
        editor = info["editor"]
        lc = info["line_canvas"]
        lc.delete("all")
        try:
            ln = int(editor.index("@0,0").split(".")[0])
            while True:
                dl = editor.dlineinfo(f"{ln}.0")
                if dl is None:
                    break
                lc.create_text(36, dl[1] + dl[3]//2,
                                text=str(ln), anchor="e",
                                fill="#858585", font=("Courier New", 11))
                ln += 1
        except Exception:
            pass

    def _update_stats(self, editor):
        try:
            pos = editor.index(tk.INSERT).split(".")
            self.cursor_lbl.config(text=f"行 {pos[0]}, 列 {int(pos[1])+1}")
            chars = len(editor.get("1.0", tk.END)) - 1
            self.char_lbl.config(text=f"{chars:,} 文字")
        except Exception:
            pass

    # ── 検索・置換 ────────────────────────────────────────────────

    def _show_search(self):
        if not self._search_visible:
            self.search_bar.pack(fill=tk.X, before=self.notebook)
            self._search_visible = True

    def _hide_search(self):
        if self._search_visible:
            self.search_bar.pack_forget()
            self._search_visible = False

    def _get_editor(self):
        _, info = self._current()
        return info["editor"] if info else None

    def _find_next(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        if not query:
            return
        pos = editor.search(query, tk.INSERT, stopindex=tk.END)
        if not pos:
            pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.mark_set(tk.INSERT, end)
            editor.see(pos)
            editor.tag_remove("sel", "1.0", tk.END)
            editor.tag_add("sel", pos, end)

    def _replace_one(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.delete(pos, end)
            editor.insert(pos, rep)

    def _replace_all(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        content = editor.get("1.0", tk.END)
        count = content.count(query)
        if count:
            editor.delete("1.0", tk.END)
            editor.insert("1.0", content.replace(query, rep))
            self.status_var.set(f"{count} 件置換")


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

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

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import re


class App059:
    """マルチタブテキストエディタ"""

    def __init__(self, root):
        self.root = root
        self.root.title("テキストエディタ")
        self.root.geometry("1000x680")
        self.root.configure(bg="#1e1e1e")
        self._tabs = {}
        self._build_ui()
        self._new_tab()

    def _build_ui(self):
        # メニューバー
        menubar = tk.Menu(self.root, bg="#252526", fg="#ccc",
                          activebackground="#094771", activeforeground="#fff",
                          bd=0)
        self.root.configure(menu=menubar)
        file_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="ファイル", menu=file_m)
        file_m.add_command(label="新規 (Ctrl+N)", command=self._new_tab)
        file_m.add_command(label="開く (Ctrl+O)", command=self._open)
        file_m.add_command(label="保存 (Ctrl+S)", command=self._save)
        file_m.add_command(label="名前を付けて保存", command=self._save_as)
        file_m.add_separator()
        file_m.add_command(label="タブを閉じる (Ctrl+W)", command=self._close_tab)
        file_m.add_command(label="終了", command=self.root.quit)

        edit_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="編集", menu=edit_m)
        edit_m.add_command(label="検索/置換 (Ctrl+H)", command=self._show_search)

        view_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="表示", menu=view_m)
        view_m.add_command(label="行番号 ON/OFF", command=self._toggle_lineno)
        view_m.add_command(label="ワードラップ切替", command=self._toggle_wrap)

        self.root.bind("<Control-n>", lambda e: self._new_tab())
        self.root.bind("<Control-o>", lambda e: self._open())
        self.root.bind("<Control-s>", lambda e: self._save())
        self.root.bind("<Control-w>", lambda e: self._close_tab())
        self.root.bind("<Control-h>", lambda e: self._show_search())

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        for text, cmd in [("📄 新規", self._new_tab), ("📂 開く", self._open),
                           ("💾 保存", self._save)]:
            tk.Button(tb, text=text, command=cmd, bg="#3c3c3c", fg="#ccc",
                      relief=tk.FLAT, font=("Arial", 9), padx=8, pady=2,
                      activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        tk.Label(tb, text="エンコード:", bg="#2d2d2d", fg="#888",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 4))
        self.enc_var = tk.StringVar(value="utf-8")
        ttk.Combobox(tb, textvariable=self.enc_var,
                     values=["utf-8", "utf-8-sig", "shift-jis", "cp932"],
                     state="readonly", width=10).pack(side=tk.LEFT)

        self.cursor_lbl = tk.Label(tb, text="行 1, 列 1", bg="#2d2d2d",
                                    fg="#888", font=("Arial", 9))
        self.cursor_lbl.pack(side=tk.RIGHT, padx=8)
        self.char_lbl = tk.Label(tb, text="0 文字", bg="#2d2d2d",
                                  fg="#888", font=("Arial", 9))
        self.char_lbl.pack(side=tk.RIGHT, padx=8)

        # 検索バー(非表示)
        self.search_bar = tk.Frame(self.root, bg="#252526", pady=4)
        tk.Label(self.search_bar, text="検索:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.search_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.search_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        tk.Label(self.search_bar, text="置換:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.replace_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.replace_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="次へ",
                   command=self._find_next).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="置換",
                   command=self._replace_one).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="全置換",
                   command=self._replace_all).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="✕",
                   command=self._hide_search).pack(side=tk.LEFT, padx=4)
        self._search_visible = False

        # ノートブック
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill=tk.BOTH, expand=True)
        self.notebook.bind("<<NotebookTabChanged>>", self._on_tab_changed)

        # ステータスバー
        self.status_var = tk.StringVar(value="準備完了")
        self._show_lineno = True
        self._wrap_mode = tk.NONE
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#007acc", fg="#fff", font=("Arial", 8),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── タブ管理 ──────────────────────────────────────────────────

    def _new_tab(self, path=None, content=""):
        frame = tk.Frame(self.notebook, bg="#1e1e1e")
        code_area = tk.Frame(frame, bg="#1e1e1e")
        code_area.pack(fill=tk.BOTH, expand=True)

        line_canvas = tk.Canvas(code_area, width=40, bg="#0d1117",
                                 highlightthickness=0)
        line_canvas.pack(side=tk.LEFT, fill=tk.Y)

        text = tk.Text(code_area, bg="#0d1117", fg="#d4d4d4",
                        font=("Courier New", 11), relief=tk.FLAT,
                        insertbackground="#fff",
                        selectbackground="#264f78",
                        undo=True, wrap=self._wrap_mode, tabs=("4m",))
        ysb = ttk.Scrollbar(code_area, command=text.yview)
        xsb = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=text.xview)
        text.configure(yscrollcommand=ysb.set, xscrollcommand=xsb.set)
        ysb.pack(side=tk.RIGHT, fill=tk.Y)
        text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        xsb.pack(fill=tk.X)

        if content:
            text.insert("1.0", content)

        label = os.path.basename(path) if path else "無題"
        self.notebook.add(frame, text=f"  {label}  ")
        tid = id(frame)
        self._tabs[tid] = {
            "path": path, "editor": text,
            "line_canvas": line_canvas,
            "modified": bool(content and not path),
            "frame": frame,
        }

        def on_key(e, t=tid):
            info = self._tabs.get(t)
            if info and not info["modified"]:
                info["modified"] = True
                idx = self.notebook.index(info["frame"])
                cur = self.notebook.tab(idx, "text")
                if not cur.startswith("●"):
                    self.notebook.tab(idx, text="● " + cur.strip())
            self._update_lineno(t)
            self._update_stats(text)

        text.bind("<KeyRelease>", on_key)
        text.bind("<ButtonRelease-1>", lambda e: self._update_stats(text))
        self.notebook.select(frame)
        self._update_lineno(tid)

    def _current(self):
        try:
            frame = self.notebook.nametowidget(self.notebook.select())
            return id(frame), self._tabs.get(id(frame))
        except Exception:
            return None, None

    def _on_tab_changed(self, event=None):
        _, info = self._current()
        if info:
            self.status_var.set(info["path"] or "無題")

    def _close_tab(self):
        tid, info = self._current()
        if not info:
            return
        if info["modified"]:
            name = os.path.basename(info["path"]) if info["path"] else "無題"
            ans = messagebox.askyesnocancel("保存確認",
                                             f"「{name}」の変更を保存しますか?")
            if ans is None:
                return
            if ans:
                self._save()
        frame = info["frame"]
        self.notebook.forget(frame)
        del self._tabs[tid]

    # ── ファイル操作 ──────────────────────────────────────────────

    def _open(self):
        path = filedialog.askopenfilename(
            filetypes=[("テキスト", "*.txt *.py *.md *.csv *.json *.html *.css *.js"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            enc = self.enc_var.get()
            with open(path, encoding=enc, errors="replace") as f:
                content = f.read()
            self._new_tab(path=path, content=content)
            _, info = self._current()
            if info:
                info["modified"] = False
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _save(self):
        tid, info = self._current()
        if not info:
            return
        if not info["path"]:
            self._save_as()
            return
        self._do_save(tid, info, info["path"])

    def _save_as(self):
        tid, info = self._current()
        if not info:
            return
        path = filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=[("テキスト", "*.txt"), ("Python", "*.py"),
                       ("すべて", "*.*")])
        if path:
            self._do_save(tid, info, path)

    def _do_save(self, tid, info, path):
        try:
            enc = self.enc_var.get()
            with open(path, "w", encoding=enc) as f:
                f.write(info["editor"].get("1.0", tk.END))
            info["path"] = path
            info["modified"] = False
            idx = self.notebook.index(info["frame"])
            self.notebook.tab(idx, text=f"  {os.path.basename(path)}  ")
            self.status_var.set(f"保存: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    # ── 表示 ──────────────────────────────────────────────────────

    def _toggle_lineno(self):
        self._show_lineno = not self._show_lineno
        _, info = self._current()
        if info:
            if self._show_lineno:
                info["line_canvas"].pack(before=info["editor"], side=tk.LEFT, fill=tk.Y)
            else:
                info["line_canvas"].pack_forget()

    def _toggle_wrap(self):
        self._wrap_mode = tk.WORD if self._wrap_mode == tk.NONE else tk.NONE
        _, info = self._current()
        if info:
            info["editor"].configure(wrap=self._wrap_mode)

    def _update_lineno(self, tid):
        info = self._tabs.get(tid)
        if not info or not self._show_lineno:
            return
        editor = info["editor"]
        lc = info["line_canvas"]
        lc.delete("all")
        try:
            ln = int(editor.index("@0,0").split(".")[0])
            while True:
                dl = editor.dlineinfo(f"{ln}.0")
                if dl is None:
                    break
                lc.create_text(36, dl[1] + dl[3]//2,
                                text=str(ln), anchor="e",
                                fill="#858585", font=("Courier New", 11))
                ln += 1
        except Exception:
            pass

    def _update_stats(self, editor):
        try:
            pos = editor.index(tk.INSERT).split(".")
            self.cursor_lbl.config(text=f"行 {pos[0]}, 列 {int(pos[1])+1}")
            chars = len(editor.get("1.0", tk.END)) - 1
            self.char_lbl.config(text=f"{chars:,} 文字")
        except Exception:
            pass

    # ── 検索・置換 ────────────────────────────────────────────────

    def _show_search(self):
        if not self._search_visible:
            self.search_bar.pack(fill=tk.X, before=self.notebook)
            self._search_visible = True

    def _hide_search(self):
        if self._search_visible:
            self.search_bar.pack_forget()
            self._search_visible = False

    def _get_editor(self):
        _, info = self._current()
        return info["editor"] if info else None

    def _find_next(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        if not query:
            return
        pos = editor.search(query, tk.INSERT, stopindex=tk.END)
        if not pos:
            pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.mark_set(tk.INSERT, end)
            editor.see(pos)
            editor.tag_remove("sel", "1.0", tk.END)
            editor.tag_add("sel", pos, end)

    def _replace_one(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.delete(pos, end)
            editor.insert(pos, rep)

    def _replace_all(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        content = editor.get("1.0", tk.END)
        count = content.count(query)
        if count:
            editor.delete("1.0", tk.END)
            editor.insert("1.0", content.replace(query, rep))
            self.status_var.set(f"{count} 件置換")


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

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

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import re


class App059:
    """マルチタブテキストエディタ"""

    def __init__(self, root):
        self.root = root
        self.root.title("テキストエディタ")
        self.root.geometry("1000x680")
        self.root.configure(bg="#1e1e1e")
        self._tabs = {}
        self._build_ui()
        self._new_tab()

    def _build_ui(self):
        # メニューバー
        menubar = tk.Menu(self.root, bg="#252526", fg="#ccc",
                          activebackground="#094771", activeforeground="#fff",
                          bd=0)
        self.root.configure(menu=menubar)
        file_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="ファイル", menu=file_m)
        file_m.add_command(label="新規 (Ctrl+N)", command=self._new_tab)
        file_m.add_command(label="開く (Ctrl+O)", command=self._open)
        file_m.add_command(label="保存 (Ctrl+S)", command=self._save)
        file_m.add_command(label="名前を付けて保存", command=self._save_as)
        file_m.add_separator()
        file_m.add_command(label="タブを閉じる (Ctrl+W)", command=self._close_tab)
        file_m.add_command(label="終了", command=self.root.quit)

        edit_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="編集", menu=edit_m)
        edit_m.add_command(label="検索/置換 (Ctrl+H)", command=self._show_search)

        view_m = tk.Menu(menubar, tearoff=False, bg="#252526", fg="#ccc",
                         activebackground="#094771", activeforeground="#fff")
        menubar.add_cascade(label="表示", menu=view_m)
        view_m.add_command(label="行番号 ON/OFF", command=self._toggle_lineno)
        view_m.add_command(label="ワードラップ切替", command=self._toggle_wrap)

        self.root.bind("<Control-n>", lambda e: self._new_tab())
        self.root.bind("<Control-o>", lambda e: self._open())
        self.root.bind("<Control-s>", lambda e: self._save())
        self.root.bind("<Control-w>", lambda e: self._close_tab())
        self.root.bind("<Control-h>", lambda e: self._show_search())

        # ツールバー
        tb = tk.Frame(self.root, bg="#2d2d2d", pady=4)
        tb.pack(fill=tk.X)
        for text, cmd in [("📄 新規", self._new_tab), ("📂 開く", self._open),
                           ("💾 保存", self._save)]:
            tk.Button(tb, text=text, command=cmd, bg="#3c3c3c", fg="#ccc",
                      relief=tk.FLAT, font=("Arial", 9), padx=8, pady=2,
                      activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        tk.Label(tb, text="エンコード:", bg="#2d2d2d", fg="#888",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 4))
        self.enc_var = tk.StringVar(value="utf-8")
        ttk.Combobox(tb, textvariable=self.enc_var,
                     values=["utf-8", "utf-8-sig", "shift-jis", "cp932"],
                     state="readonly", width=10).pack(side=tk.LEFT)

        self.cursor_lbl = tk.Label(tb, text="行 1, 列 1", bg="#2d2d2d",
                                    fg="#888", font=("Arial", 9))
        self.cursor_lbl.pack(side=tk.RIGHT, padx=8)
        self.char_lbl = tk.Label(tb, text="0 文字", bg="#2d2d2d",
                                  fg="#888", font=("Arial", 9))
        self.char_lbl.pack(side=tk.RIGHT, padx=8)

        # 検索バー(非表示)
        self.search_bar = tk.Frame(self.root, bg="#252526", pady=4)
        tk.Label(self.search_bar, text="検索:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.search_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.search_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        tk.Label(self.search_bar, text="置換:", bg="#252526", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.replace_var = tk.StringVar()
        ttk.Entry(self.search_bar, textvariable=self.replace_var,
                  width=20).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="次へ",
                   command=self._find_next).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="置換",
                   command=self._replace_one).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="全置換",
                   command=self._replace_all).pack(side=tk.LEFT, padx=2)
        ttk.Button(self.search_bar, text="✕",
                   command=self._hide_search).pack(side=tk.LEFT, padx=4)
        self._search_visible = False

        # ノートブック
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill=tk.BOTH, expand=True)
        self.notebook.bind("<<NotebookTabChanged>>", self._on_tab_changed)

        # ステータスバー
        self.status_var = tk.StringVar(value="準備完了")
        self._show_lineno = True
        self._wrap_mode = tk.NONE
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#007acc", fg="#fff", font=("Arial", 8),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── タブ管理 ──────────────────────────────────────────────────

    def _new_tab(self, path=None, content=""):
        frame = tk.Frame(self.notebook, bg="#1e1e1e")
        code_area = tk.Frame(frame, bg="#1e1e1e")
        code_area.pack(fill=tk.BOTH, expand=True)

        line_canvas = tk.Canvas(code_area, width=40, bg="#0d1117",
                                 highlightthickness=0)
        line_canvas.pack(side=tk.LEFT, fill=tk.Y)

        text = tk.Text(code_area, bg="#0d1117", fg="#d4d4d4",
                        font=("Courier New", 11), relief=tk.FLAT,
                        insertbackground="#fff",
                        selectbackground="#264f78",
                        undo=True, wrap=self._wrap_mode, tabs=("4m",))
        ysb = ttk.Scrollbar(code_area, command=text.yview)
        xsb = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=text.xview)
        text.configure(yscrollcommand=ysb.set, xscrollcommand=xsb.set)
        ysb.pack(side=tk.RIGHT, fill=tk.Y)
        text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        xsb.pack(fill=tk.X)

        if content:
            text.insert("1.0", content)

        label = os.path.basename(path) if path else "無題"
        self.notebook.add(frame, text=f"  {label}  ")
        tid = id(frame)
        self._tabs[tid] = {
            "path": path, "editor": text,
            "line_canvas": line_canvas,
            "modified": bool(content and not path),
            "frame": frame,
        }

        def on_key(e, t=tid):
            info = self._tabs.get(t)
            if info and not info["modified"]:
                info["modified"] = True
                idx = self.notebook.index(info["frame"])
                cur = self.notebook.tab(idx, "text")
                if not cur.startswith("●"):
                    self.notebook.tab(idx, text="● " + cur.strip())
            self._update_lineno(t)
            self._update_stats(text)

        text.bind("<KeyRelease>", on_key)
        text.bind("<ButtonRelease-1>", lambda e: self._update_stats(text))
        self.notebook.select(frame)
        self._update_lineno(tid)

    def _current(self):
        try:
            frame = self.notebook.nametowidget(self.notebook.select())
            return id(frame), self._tabs.get(id(frame))
        except Exception:
            return None, None

    def _on_tab_changed(self, event=None):
        _, info = self._current()
        if info:
            self.status_var.set(info["path"] or "無題")

    def _close_tab(self):
        tid, info = self._current()
        if not info:
            return
        if info["modified"]:
            name = os.path.basename(info["path"]) if info["path"] else "無題"
            ans = messagebox.askyesnocancel("保存確認",
                                             f"「{name}」の変更を保存しますか?")
            if ans is None:
                return
            if ans:
                self._save()
        frame = info["frame"]
        self.notebook.forget(frame)
        del self._tabs[tid]

    # ── ファイル操作 ──────────────────────────────────────────────

    def _open(self):
        path = filedialog.askopenfilename(
            filetypes=[("テキスト", "*.txt *.py *.md *.csv *.json *.html *.css *.js"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            enc = self.enc_var.get()
            with open(path, encoding=enc, errors="replace") as f:
                content = f.read()
            self._new_tab(path=path, content=content)
            _, info = self._current()
            if info:
                info["modified"] = False
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _save(self):
        tid, info = self._current()
        if not info:
            return
        if not info["path"]:
            self._save_as()
            return
        self._do_save(tid, info, info["path"])

    def _save_as(self):
        tid, info = self._current()
        if not info:
            return
        path = filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=[("テキスト", "*.txt"), ("Python", "*.py"),
                       ("すべて", "*.*")])
        if path:
            self._do_save(tid, info, path)

    def _do_save(self, tid, info, path):
        try:
            enc = self.enc_var.get()
            with open(path, "w", encoding=enc) as f:
                f.write(info["editor"].get("1.0", tk.END))
            info["path"] = path
            info["modified"] = False
            idx = self.notebook.index(info["frame"])
            self.notebook.tab(idx, text=f"  {os.path.basename(path)}  ")
            self.status_var.set(f"保存: {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    # ── 表示 ──────────────────────────────────────────────────────

    def _toggle_lineno(self):
        self._show_lineno = not self._show_lineno
        _, info = self._current()
        if info:
            if self._show_lineno:
                info["line_canvas"].pack(before=info["editor"], side=tk.LEFT, fill=tk.Y)
            else:
                info["line_canvas"].pack_forget()

    def _toggle_wrap(self):
        self._wrap_mode = tk.WORD if self._wrap_mode == tk.NONE else tk.NONE
        _, info = self._current()
        if info:
            info["editor"].configure(wrap=self._wrap_mode)

    def _update_lineno(self, tid):
        info = self._tabs.get(tid)
        if not info or not self._show_lineno:
            return
        editor = info["editor"]
        lc = info["line_canvas"]
        lc.delete("all")
        try:
            ln = int(editor.index("@0,0").split(".")[0])
            while True:
                dl = editor.dlineinfo(f"{ln}.0")
                if dl is None:
                    break
                lc.create_text(36, dl[1] + dl[3]//2,
                                text=str(ln), anchor="e",
                                fill="#858585", font=("Courier New", 11))
                ln += 1
        except Exception:
            pass

    def _update_stats(self, editor):
        try:
            pos = editor.index(tk.INSERT).split(".")
            self.cursor_lbl.config(text=f"行 {pos[0]}, 列 {int(pos[1])+1}")
            chars = len(editor.get("1.0", tk.END)) - 1
            self.char_lbl.config(text=f"{chars:,} 文字")
        except Exception:
            pass

    # ── 検索・置換 ────────────────────────────────────────────────

    def _show_search(self):
        if not self._search_visible:
            self.search_bar.pack(fill=tk.X, before=self.notebook)
            self._search_visible = True

    def _hide_search(self):
        if self._search_visible:
            self.search_bar.pack_forget()
            self._search_visible = False

    def _get_editor(self):
        _, info = self._current()
        return info["editor"] if info else None

    def _find_next(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        if not query:
            return
        pos = editor.search(query, tk.INSERT, stopindex=tk.END)
        if not pos:
            pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.mark_set(tk.INSERT, end)
            editor.see(pos)
            editor.tag_remove("sel", "1.0", tk.END)
            editor.tag_add("sel", pos, end)

    def _replace_one(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        pos = editor.search(query, "1.0", stopindex=tk.END)
        if pos:
            end = f"{pos} + {len(query)} chars"
            editor.delete(pos, end)
            editor.insert(pos, rep)

    def _replace_all(self):
        editor = self._get_editor()
        if not editor:
            return
        query = self.search_var.get()
        rep = self.replace_var.get()
        if not query:
            return
        content = editor.get("1.0", tk.END)
        count = content.count(query)
        if count:
            editor.delete("1.0", tk.END)
            editor.insert("1.0", content.replace(query, rep))
            self.status_var.set(f"{count} 件置換")


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

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

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

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

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

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

    App059クラスを定義し、__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 コマンドで必要なライブラリをインストールしてください。

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

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

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

9. 練習問題

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

  1. 課題1:機能拡張

    マルチタブテキストエディタに新しい機能を1つ追加してみましょう。

  2. 課題2:UIの改善

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

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

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

🚀
次に挑戦するアプリ

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