中級者向け No.02

シンタックスハイライト付きエディタ

Python・HTMLなど複数言語のシンタックスハイライトを実装したテキストエディタ。正規表現によるトークン解析を学びます。

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

1. アプリ概要

Python・HTMLなど複数言語のシンタックスハイライトを実装したテキストエディタ。正規表現によるトークン解析を学びます。

このアプリは中級カテゴリに分類される実践的なGUIアプリです。使用ライブラリは tkinter(標準ライブラリ) で、難易度は ★★★ です。

Pythonでは tkinter を使うことで、クロスプラットフォームなGUIアプリを簡単に作成できます。このアプリを通じて、ウィジェットの配置・イベント処理・データ管理など、GUI開発の実践的なスキルを習得できます。

ソースコードは完全な動作状態で提供しており、コピーしてそのまま実行できます。まずは実行して動作を確認し、その後コードを読んで仕組みを理解していきましょう。カスタマイズセクションでは機能拡張のアイデアも紹介しています。

GUIアプリ開発は、プログラミングの楽しさを実感できる最も効果的な学習方法のひとつです。アプリを作ることで、変数・関数・クラス・イベント処理など、プログラミングの重要な概念が自然と身についていきます。このアプリをきっかけに、オリジナルアプリの開発にも挑戦してみてください。

2. 機能一覧

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

3. 事前準備・環境

ℹ️
動作確認環境

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

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

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

4. 完全なソースコード

💡
コードのコピー方法

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

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


class App02:
    """シンタックスハイライト付きエディタ"""

    THEMES = {
        "Python": {
            "keyword":   (r"\b(False|None|True|and|as|assert|async|await|break|class|"
                          r"continue|def|del|elif|else|except|finally|for|from|global|"
                          r"if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|"
                          r"try|while|with|yield)\b", "#cc7832"),
            "builtin":   (r"\b(print|len|range|int|float|str|list|dict|set|tuple|bool|"
                          r"type|input|open|enumerate|zip|map|filter|sorted|reversed|"
                          r"abs|max|min|sum|isinstance|hasattr|getattr|setattr)\b", "#8888cc"),
            "string":    (r'("(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\')', "#6a8759"),
            "comment":   (r"(#[^\n]*)", "#808080"),
            "number":    (r"\b(\d+(?:\.\d+)?)\b", "#6897bb"),
            "decorator": (r"(@\w+)", "#bbb529"),
        },
        "HTML": {
            "tag":     (r"(</?[\w!][^>]*>)", "#e8bf6a"),
            "attr":    (r'(\s[\w-]+=)', "#9876aa"),
            "string":  (r'"[^"]*"', "#6a8759"),
            "comment": (r"(<!--.*?-->)", "#808080"),
        },
        "なし": {},
    }

    def __init__(self, root):
        self.root = root
        self.root.title("シンタックスハイライト付きエディタ")
        self.root.geometry("820x580")
        self.root.configure(bg="#2b2b2b")
        self.current_file = None
        self.lang_var = tk.StringVar(value="Python")
        self._build_ui()
        self._insert_sample()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#3c3f41", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="✏️ シンタックスハイライト付きエディタ",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#3c3f41", fg="#a9b7c6").pack(side=tk.LEFT, padx=12)

        toolbar = tk.Frame(self.root, bg="#3c3f41", pady=3)
        toolbar.pack(fill=tk.X)
        for text, cmd in [("📂 開く", self._open_file),
                          ("💾 保存", self._save_file),
                          ("💾 名前を付けて保存", self._save_as)]:
            tk.Button(toolbar, text=text, bg="#4c5052", fg="#a9b7c6",
                      relief=tk.FLAT, font=("Arial", 9), padx=8,
                      activebackground="#555", activeforeground="white",
                      command=cmd).pack(side=tk.LEFT, padx=2)

        tk.Label(toolbar, text="  言語:", bg="#3c3f41",
                 fg="#a9b7c6", font=("Arial", 10)).pack(side=tk.LEFT, padx=(16, 4))
        lang_cb = ttk.Combobox(toolbar, textvariable=self.lang_var,
                               values=list(self.THEMES.keys()),
                               width=10, state="readonly")
        lang_cb.pack(side=tk.LEFT)
        lang_cb.bind("<<ComboboxSelected>>", lambda e: self._highlight())

        editor_frame = tk.Frame(self.root, bg="#2b2b2b")
        editor_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        self.line_nums = tk.Text(editor_frame, width=4, bg="#313335",
                                 fg="#606366", font=("Courier New", 12),
                                 state=tk.DISABLED, relief=tk.FLAT,
                                 padx=4, pady=4, takefocus=0)
        self.line_nums.pack(side=tk.LEFT, fill=tk.Y)

        self.text = tk.Text(editor_frame, bg="#2b2b2b", fg="#a9b7c6",
                            font=("Courier New", 12), insertbackground="white",
                            relief=tk.FLAT, undo=True, padx=8, pady=4,
                            selectbackground="#214283",
                            tabs="    ")
        self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        sb = ttk.Scrollbar(editor_frame, command=self.text.yview)
        sb.pack(side=tk.RIGHT, fill=tk.Y)
        self.text.configure(yscrollcommand=sb.set)
        self.text.bind("<KeyRelease>", self._on_key)

        self._setup_tags()

        self.status_var = tk.StringVar(value="行: 1  列: 1")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#3c3f41", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _setup_tags(self):
        colors = {
            "keyword": "#cc7832", "builtin": "#8888cc",
            "string": "#6a8759", "comment": "#808080",
            "number": "#6897bb", "decorator": "#bbb529",
            "tag": "#e8bf6a", "attr": "#9876aa",
        }
        for name, color in colors.items():
            self.text.tag_configure(name, foreground=color)

    def _on_key(self, event=None):
        self._update_line_nums()
        self._highlight()
        pos = self.text.index(tk.INSERT)
        row, col = pos.split(".")
        self.status_var.set(f"行: {row}  列: {int(col)+1}")

    def _update_line_nums(self):
        content = self.text.get("1.0", tk.END)
        lines = content.count("\n")
        self.line_nums.config(state=tk.NORMAL)
        self.line_nums.delete("1.0", tk.END)
        self.line_nums.insert("1.0", "\n".join(str(i) for i in range(1, lines + 1)))
        self.line_nums.config(state=tk.DISABLED)

    def _highlight(self):
        lang = self.lang_var.get()
        rules = self.THEMES.get(lang, {})
        for tag in ["keyword", "builtin", "string", "comment",
                    "number", "decorator", "tag", "attr"]:
            self.text.tag_remove(tag, "1.0", tk.END)
        content = self.text.get("1.0", tk.END)
        for tag, (pattern, _) in rules.items():
            for m in re.finditer(pattern, content, re.DOTALL):
                start = f"1.0+{m.start()}c"
                end = f"1.0+{m.end()}c"
                self.text.tag_add(tag, start, end)

    def _open_file(self):
        path = filedialog.askopenfilename(
            filetypes=[("Pythonファイル", "*.py"), ("HTMLファイル", "*.html"),
                       ("テキストファイル", "*.txt"), ("すべて", "*.*")])
        if path:
            try:
                with open(path, encoding="utf-8", errors="replace") as f:
                    content = f.read()
                self.text.delete("1.0", tk.END)
                self.text.insert("1.0", content)
                self.current_file = path
                ext = path.rsplit(".", 1)[-1].lower()
                self.lang_var.set("Python" if ext == "py" else
                                  "HTML" if ext in ("html", "htm") else "なし")
                self._highlight()
                self._update_line_nums()
                self.root.title(f"エディタ — {path}")
            except Exception as e:
                messagebox.showerror("エラー", str(e))

    def _save_file(self):
        if self.current_file:
            self._write(self.current_file)
        else:
            self._save_as()

    def _save_as(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".py",
            filetypes=[("Pythonファイル", "*.py"), ("テキストファイル", "*.txt"),
                       ("すべて", "*.*")])
        if path:
            self.current_file = path
            self._write(path)

    def _write(self, path):
        try:
            with open(path, "w", encoding="utf-8") as f:
                f.write(self.text.get("1.0", tk.END))
            self.root.title(f"エディタ — {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _insert_sample(self):
        sample = '''# Pythonサンプルコード
def greet(name: str) -> str:
    """挨拶文を返す関数"""
    if not isinstance(name, str):
        raise TypeError("nameはstr型である必要があります")
    return f"Hello, {name}!"

class Counter:
    """カウンタークラス"""

    def __init__(self, start=0):
        self.count = start

    def increment(self):
        self.count += 1
        return self

    def reset(self):
        self.count = 0

# メイン処理
if __name__ == "__main__":
    counter = Counter(start=10)
    for i in range(5):
        counter.increment()
    print(f"カウント: {counter.count}")
    print(greet("Python"))
'''
        self.text.insert("1.0", sample)
        self._highlight()
        self._update_line_nums()


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

5. コード解説

シンタックスハイライト付きエディタのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。

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

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

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


class App02:
    """シンタックスハイライト付きエディタ"""

    THEMES = {
        "Python": {
            "keyword":   (r"\b(False|None|True|and|as|assert|async|await|break|class|"
                          r"continue|def|del|elif|else|except|finally|for|from|global|"
                          r"if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|"
                          r"try|while|with|yield)\b", "#cc7832"),
            "builtin":   (r"\b(print|len|range|int|float|str|list|dict|set|tuple|bool|"
                          r"type|input|open|enumerate|zip|map|filter|sorted|reversed|"
                          r"abs|max|min|sum|isinstance|hasattr|getattr|setattr)\b", "#8888cc"),
            "string":    (r'("(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\')', "#6a8759"),
            "comment":   (r"(#[^\n]*)", "#808080"),
            "number":    (r"\b(\d+(?:\.\d+)?)\b", "#6897bb"),
            "decorator": (r"(@\w+)", "#bbb529"),
        },
        "HTML": {
            "tag":     (r"(</?[\w!][^>]*>)", "#e8bf6a"),
            "attr":    (r'(\s[\w-]+=)', "#9876aa"),
            "string":  (r'"[^"]*"', "#6a8759"),
            "comment": (r"(<!--.*?-->)", "#808080"),
        },
        "なし": {},
    }

    def __init__(self, root):
        self.root = root
        self.root.title("シンタックスハイライト付きエディタ")
        self.root.geometry("820x580")
        self.root.configure(bg="#2b2b2b")
        self.current_file = None
        self.lang_var = tk.StringVar(value="Python")
        self._build_ui()
        self._insert_sample()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#3c3f41", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="✏️ シンタックスハイライト付きエディタ",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#3c3f41", fg="#a9b7c6").pack(side=tk.LEFT, padx=12)

        toolbar = tk.Frame(self.root, bg="#3c3f41", pady=3)
        toolbar.pack(fill=tk.X)
        for text, cmd in [("📂 開く", self._open_file),
                          ("💾 保存", self._save_file),
                          ("💾 名前を付けて保存", self._save_as)]:
            tk.Button(toolbar, text=text, bg="#4c5052", fg="#a9b7c6",
                      relief=tk.FLAT, font=("Arial", 9), padx=8,
                      activebackground="#555", activeforeground="white",
                      command=cmd).pack(side=tk.LEFT, padx=2)

        tk.Label(toolbar, text="  言語:", bg="#3c3f41",
                 fg="#a9b7c6", font=("Arial", 10)).pack(side=tk.LEFT, padx=(16, 4))
        lang_cb = ttk.Combobox(toolbar, textvariable=self.lang_var,
                               values=list(self.THEMES.keys()),
                               width=10, state="readonly")
        lang_cb.pack(side=tk.LEFT)
        lang_cb.bind("<<ComboboxSelected>>", lambda e: self._highlight())

        editor_frame = tk.Frame(self.root, bg="#2b2b2b")
        editor_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        self.line_nums = tk.Text(editor_frame, width=4, bg="#313335",
                                 fg="#606366", font=("Courier New", 12),
                                 state=tk.DISABLED, relief=tk.FLAT,
                                 padx=4, pady=4, takefocus=0)
        self.line_nums.pack(side=tk.LEFT, fill=tk.Y)

        self.text = tk.Text(editor_frame, bg="#2b2b2b", fg="#a9b7c6",
                            font=("Courier New", 12), insertbackground="white",
                            relief=tk.FLAT, undo=True, padx=8, pady=4,
                            selectbackground="#214283",
                            tabs="    ")
        self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        sb = ttk.Scrollbar(editor_frame, command=self.text.yview)
        sb.pack(side=tk.RIGHT, fill=tk.Y)
        self.text.configure(yscrollcommand=sb.set)
        self.text.bind("<KeyRelease>", self._on_key)

        self._setup_tags()

        self.status_var = tk.StringVar(value="行: 1  列: 1")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#3c3f41", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _setup_tags(self):
        colors = {
            "keyword": "#cc7832", "builtin": "#8888cc",
            "string": "#6a8759", "comment": "#808080",
            "number": "#6897bb", "decorator": "#bbb529",
            "tag": "#e8bf6a", "attr": "#9876aa",
        }
        for name, color in colors.items():
            self.text.tag_configure(name, foreground=color)

    def _on_key(self, event=None):
        self._update_line_nums()
        self._highlight()
        pos = self.text.index(tk.INSERT)
        row, col = pos.split(".")
        self.status_var.set(f"行: {row}  列: {int(col)+1}")

    def _update_line_nums(self):
        content = self.text.get("1.0", tk.END)
        lines = content.count("\n")
        self.line_nums.config(state=tk.NORMAL)
        self.line_nums.delete("1.0", tk.END)
        self.line_nums.insert("1.0", "\n".join(str(i) for i in range(1, lines + 1)))
        self.line_nums.config(state=tk.DISABLED)

    def _highlight(self):
        lang = self.lang_var.get()
        rules = self.THEMES.get(lang, {})
        for tag in ["keyword", "builtin", "string", "comment",
                    "number", "decorator", "tag", "attr"]:
            self.text.tag_remove(tag, "1.0", tk.END)
        content = self.text.get("1.0", tk.END)
        for tag, (pattern, _) in rules.items():
            for m in re.finditer(pattern, content, re.DOTALL):
                start = f"1.0+{m.start()}c"
                end = f"1.0+{m.end()}c"
                self.text.tag_add(tag, start, end)

    def _open_file(self):
        path = filedialog.askopenfilename(
            filetypes=[("Pythonファイル", "*.py"), ("HTMLファイル", "*.html"),
                       ("テキストファイル", "*.txt"), ("すべて", "*.*")])
        if path:
            try:
                with open(path, encoding="utf-8", errors="replace") as f:
                    content = f.read()
                self.text.delete("1.0", tk.END)
                self.text.insert("1.0", content)
                self.current_file = path
                ext = path.rsplit(".", 1)[-1].lower()
                self.lang_var.set("Python" if ext == "py" else
                                  "HTML" if ext in ("html", "htm") else "なし")
                self._highlight()
                self._update_line_nums()
                self.root.title(f"エディタ — {path}")
            except Exception as e:
                messagebox.showerror("エラー", str(e))

    def _save_file(self):
        if self.current_file:
            self._write(self.current_file)
        else:
            self._save_as()

    def _save_as(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".py",
            filetypes=[("Pythonファイル", "*.py"), ("テキストファイル", "*.txt"),
                       ("すべて", "*.*")])
        if path:
            self.current_file = path
            self._write(path)

    def _write(self, path):
        try:
            with open(path, "w", encoding="utf-8") as f:
                f.write(self.text.get("1.0", tk.END))
            self.root.title(f"エディタ — {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _insert_sample(self):
        sample = '''# Pythonサンプルコード
def greet(name: str) -> str:
    """挨拶文を返す関数"""
    if not isinstance(name, str):
        raise TypeError("nameはstr型である必要があります")
    return f"Hello, {name}!"

class Counter:
    """カウンタークラス"""

    def __init__(self, start=0):
        self.count = start

    def increment(self):
        self.count += 1
        return self

    def reset(self):
        self.count = 0

# メイン処理
if __name__ == "__main__":
    counter = Counter(start=10)
    for i in range(5):
        counter.increment()
    print(f"カウント: {counter.count}")
    print(greet("Python"))
'''
        self.text.insert("1.0", sample)
        self._highlight()
        self._update_line_nums()


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

LabelFrameによるセクション分け

ttk.LabelFrame を使うことで、入力エリアと結果エリアを視覚的に分けられます。padding引数でフレーム内の余白を設定し、見やすいレイアウトを実現しています。

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


class App02:
    """シンタックスハイライト付きエディタ"""

    THEMES = {
        "Python": {
            "keyword":   (r"\b(False|None|True|and|as|assert|async|await|break|class|"
                          r"continue|def|del|elif|else|except|finally|for|from|global|"
                          r"if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|"
                          r"try|while|with|yield)\b", "#cc7832"),
            "builtin":   (r"\b(print|len|range|int|float|str|list|dict|set|tuple|bool|"
                          r"type|input|open|enumerate|zip|map|filter|sorted|reversed|"
                          r"abs|max|min|sum|isinstance|hasattr|getattr|setattr)\b", "#8888cc"),
            "string":    (r'("(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\')', "#6a8759"),
            "comment":   (r"(#[^\n]*)", "#808080"),
            "number":    (r"\b(\d+(?:\.\d+)?)\b", "#6897bb"),
            "decorator": (r"(@\w+)", "#bbb529"),
        },
        "HTML": {
            "tag":     (r"(</?[\w!][^>]*>)", "#e8bf6a"),
            "attr":    (r'(\s[\w-]+=)', "#9876aa"),
            "string":  (r'"[^"]*"', "#6a8759"),
            "comment": (r"(<!--.*?-->)", "#808080"),
        },
        "なし": {},
    }

    def __init__(self, root):
        self.root = root
        self.root.title("シンタックスハイライト付きエディタ")
        self.root.geometry("820x580")
        self.root.configure(bg="#2b2b2b")
        self.current_file = None
        self.lang_var = tk.StringVar(value="Python")
        self._build_ui()
        self._insert_sample()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#3c3f41", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="✏️ シンタックスハイライト付きエディタ",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#3c3f41", fg="#a9b7c6").pack(side=tk.LEFT, padx=12)

        toolbar = tk.Frame(self.root, bg="#3c3f41", pady=3)
        toolbar.pack(fill=tk.X)
        for text, cmd in [("📂 開く", self._open_file),
                          ("💾 保存", self._save_file),
                          ("💾 名前を付けて保存", self._save_as)]:
            tk.Button(toolbar, text=text, bg="#4c5052", fg="#a9b7c6",
                      relief=tk.FLAT, font=("Arial", 9), padx=8,
                      activebackground="#555", activeforeground="white",
                      command=cmd).pack(side=tk.LEFT, padx=2)

        tk.Label(toolbar, text="  言語:", bg="#3c3f41",
                 fg="#a9b7c6", font=("Arial", 10)).pack(side=tk.LEFT, padx=(16, 4))
        lang_cb = ttk.Combobox(toolbar, textvariable=self.lang_var,
                               values=list(self.THEMES.keys()),
                               width=10, state="readonly")
        lang_cb.pack(side=tk.LEFT)
        lang_cb.bind("<<ComboboxSelected>>", lambda e: self._highlight())

        editor_frame = tk.Frame(self.root, bg="#2b2b2b")
        editor_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        self.line_nums = tk.Text(editor_frame, width=4, bg="#313335",
                                 fg="#606366", font=("Courier New", 12),
                                 state=tk.DISABLED, relief=tk.FLAT,
                                 padx=4, pady=4, takefocus=0)
        self.line_nums.pack(side=tk.LEFT, fill=tk.Y)

        self.text = tk.Text(editor_frame, bg="#2b2b2b", fg="#a9b7c6",
                            font=("Courier New", 12), insertbackground="white",
                            relief=tk.FLAT, undo=True, padx=8, pady=4,
                            selectbackground="#214283",
                            tabs="    ")
        self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        sb = ttk.Scrollbar(editor_frame, command=self.text.yview)
        sb.pack(side=tk.RIGHT, fill=tk.Y)
        self.text.configure(yscrollcommand=sb.set)
        self.text.bind("<KeyRelease>", self._on_key)

        self._setup_tags()

        self.status_var = tk.StringVar(value="行: 1  列: 1")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#3c3f41", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _setup_tags(self):
        colors = {
            "keyword": "#cc7832", "builtin": "#8888cc",
            "string": "#6a8759", "comment": "#808080",
            "number": "#6897bb", "decorator": "#bbb529",
            "tag": "#e8bf6a", "attr": "#9876aa",
        }
        for name, color in colors.items():
            self.text.tag_configure(name, foreground=color)

    def _on_key(self, event=None):
        self._update_line_nums()
        self._highlight()
        pos = self.text.index(tk.INSERT)
        row, col = pos.split(".")
        self.status_var.set(f"行: {row}  列: {int(col)+1}")

    def _update_line_nums(self):
        content = self.text.get("1.0", tk.END)
        lines = content.count("\n")
        self.line_nums.config(state=tk.NORMAL)
        self.line_nums.delete("1.0", tk.END)
        self.line_nums.insert("1.0", "\n".join(str(i) for i in range(1, lines + 1)))
        self.line_nums.config(state=tk.DISABLED)

    def _highlight(self):
        lang = self.lang_var.get()
        rules = self.THEMES.get(lang, {})
        for tag in ["keyword", "builtin", "string", "comment",
                    "number", "decorator", "tag", "attr"]:
            self.text.tag_remove(tag, "1.0", tk.END)
        content = self.text.get("1.0", tk.END)
        for tag, (pattern, _) in rules.items():
            for m in re.finditer(pattern, content, re.DOTALL):
                start = f"1.0+{m.start()}c"
                end = f"1.0+{m.end()}c"
                self.text.tag_add(tag, start, end)

    def _open_file(self):
        path = filedialog.askopenfilename(
            filetypes=[("Pythonファイル", "*.py"), ("HTMLファイル", "*.html"),
                       ("テキストファイル", "*.txt"), ("すべて", "*.*")])
        if path:
            try:
                with open(path, encoding="utf-8", errors="replace") as f:
                    content = f.read()
                self.text.delete("1.0", tk.END)
                self.text.insert("1.0", content)
                self.current_file = path
                ext = path.rsplit(".", 1)[-1].lower()
                self.lang_var.set("Python" if ext == "py" else
                                  "HTML" if ext in ("html", "htm") else "なし")
                self._highlight()
                self._update_line_nums()
                self.root.title(f"エディタ — {path}")
            except Exception as e:
                messagebox.showerror("エラー", str(e))

    def _save_file(self):
        if self.current_file:
            self._write(self.current_file)
        else:
            self._save_as()

    def _save_as(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".py",
            filetypes=[("Pythonファイル", "*.py"), ("テキストファイル", "*.txt"),
                       ("すべて", "*.*")])
        if path:
            self.current_file = path
            self._write(path)

    def _write(self, path):
        try:
            with open(path, "w", encoding="utf-8") as f:
                f.write(self.text.get("1.0", tk.END))
            self.root.title(f"エディタ — {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _insert_sample(self):
        sample = '''# Pythonサンプルコード
def greet(name: str) -> str:
    """挨拶文を返す関数"""
    if not isinstance(name, str):
        raise TypeError("nameはstr型である必要があります")
    return f"Hello, {name}!"

class Counter:
    """カウンタークラス"""

    def __init__(self, start=0):
        self.count = start

    def increment(self):
        self.count += 1
        return self

    def reset(self):
        self.count = 0

# メイン処理
if __name__ == "__main__":
    counter = Counter(start=10)
    for i in range(5):
        counter.increment()
    print(f"カウント: {counter.count}")
    print(greet("Python"))
'''
        self.text.insert("1.0", sample)
        self._highlight()
        self._update_line_nums()


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

Entryウィジェットとイベントバインド

ttk.Entryで入力フィールドを作成します。bind('', ...)でEnterキー押下時に処理を実行できます。これにより、マウスを使わずキーボードだけで操作できるUXが実現できます。

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


class App02:
    """シンタックスハイライト付きエディタ"""

    THEMES = {
        "Python": {
            "keyword":   (r"\b(False|None|True|and|as|assert|async|await|break|class|"
                          r"continue|def|del|elif|else|except|finally|for|from|global|"
                          r"if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|"
                          r"try|while|with|yield)\b", "#cc7832"),
            "builtin":   (r"\b(print|len|range|int|float|str|list|dict|set|tuple|bool|"
                          r"type|input|open|enumerate|zip|map|filter|sorted|reversed|"
                          r"abs|max|min|sum|isinstance|hasattr|getattr|setattr)\b", "#8888cc"),
            "string":    (r'("(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\')', "#6a8759"),
            "comment":   (r"(#[^\n]*)", "#808080"),
            "number":    (r"\b(\d+(?:\.\d+)?)\b", "#6897bb"),
            "decorator": (r"(@\w+)", "#bbb529"),
        },
        "HTML": {
            "tag":     (r"(</?[\w!][^>]*>)", "#e8bf6a"),
            "attr":    (r'(\s[\w-]+=)', "#9876aa"),
            "string":  (r'"[^"]*"', "#6a8759"),
            "comment": (r"(<!--.*?-->)", "#808080"),
        },
        "なし": {},
    }

    def __init__(self, root):
        self.root = root
        self.root.title("シンタックスハイライト付きエディタ")
        self.root.geometry("820x580")
        self.root.configure(bg="#2b2b2b")
        self.current_file = None
        self.lang_var = tk.StringVar(value="Python")
        self._build_ui()
        self._insert_sample()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#3c3f41", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="✏️ シンタックスハイライト付きエディタ",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#3c3f41", fg="#a9b7c6").pack(side=tk.LEFT, padx=12)

        toolbar = tk.Frame(self.root, bg="#3c3f41", pady=3)
        toolbar.pack(fill=tk.X)
        for text, cmd in [("📂 開く", self._open_file),
                          ("💾 保存", self._save_file),
                          ("💾 名前を付けて保存", self._save_as)]:
            tk.Button(toolbar, text=text, bg="#4c5052", fg="#a9b7c6",
                      relief=tk.FLAT, font=("Arial", 9), padx=8,
                      activebackground="#555", activeforeground="white",
                      command=cmd).pack(side=tk.LEFT, padx=2)

        tk.Label(toolbar, text="  言語:", bg="#3c3f41",
                 fg="#a9b7c6", font=("Arial", 10)).pack(side=tk.LEFT, padx=(16, 4))
        lang_cb = ttk.Combobox(toolbar, textvariable=self.lang_var,
                               values=list(self.THEMES.keys()),
                               width=10, state="readonly")
        lang_cb.pack(side=tk.LEFT)
        lang_cb.bind("<<ComboboxSelected>>", lambda e: self._highlight())

        editor_frame = tk.Frame(self.root, bg="#2b2b2b")
        editor_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        self.line_nums = tk.Text(editor_frame, width=4, bg="#313335",
                                 fg="#606366", font=("Courier New", 12),
                                 state=tk.DISABLED, relief=tk.FLAT,
                                 padx=4, pady=4, takefocus=0)
        self.line_nums.pack(side=tk.LEFT, fill=tk.Y)

        self.text = tk.Text(editor_frame, bg="#2b2b2b", fg="#a9b7c6",
                            font=("Courier New", 12), insertbackground="white",
                            relief=tk.FLAT, undo=True, padx=8, pady=4,
                            selectbackground="#214283",
                            tabs="    ")
        self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        sb = ttk.Scrollbar(editor_frame, command=self.text.yview)
        sb.pack(side=tk.RIGHT, fill=tk.Y)
        self.text.configure(yscrollcommand=sb.set)
        self.text.bind("<KeyRelease>", self._on_key)

        self._setup_tags()

        self.status_var = tk.StringVar(value="行: 1  列: 1")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#3c3f41", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _setup_tags(self):
        colors = {
            "keyword": "#cc7832", "builtin": "#8888cc",
            "string": "#6a8759", "comment": "#808080",
            "number": "#6897bb", "decorator": "#bbb529",
            "tag": "#e8bf6a", "attr": "#9876aa",
        }
        for name, color in colors.items():
            self.text.tag_configure(name, foreground=color)

    def _on_key(self, event=None):
        self._update_line_nums()
        self._highlight()
        pos = self.text.index(tk.INSERT)
        row, col = pos.split(".")
        self.status_var.set(f"行: {row}  列: {int(col)+1}")

    def _update_line_nums(self):
        content = self.text.get("1.0", tk.END)
        lines = content.count("\n")
        self.line_nums.config(state=tk.NORMAL)
        self.line_nums.delete("1.0", tk.END)
        self.line_nums.insert("1.0", "\n".join(str(i) for i in range(1, lines + 1)))
        self.line_nums.config(state=tk.DISABLED)

    def _highlight(self):
        lang = self.lang_var.get()
        rules = self.THEMES.get(lang, {})
        for tag in ["keyword", "builtin", "string", "comment",
                    "number", "decorator", "tag", "attr"]:
            self.text.tag_remove(tag, "1.0", tk.END)
        content = self.text.get("1.0", tk.END)
        for tag, (pattern, _) in rules.items():
            for m in re.finditer(pattern, content, re.DOTALL):
                start = f"1.0+{m.start()}c"
                end = f"1.0+{m.end()}c"
                self.text.tag_add(tag, start, end)

    def _open_file(self):
        path = filedialog.askopenfilename(
            filetypes=[("Pythonファイル", "*.py"), ("HTMLファイル", "*.html"),
                       ("テキストファイル", "*.txt"), ("すべて", "*.*")])
        if path:
            try:
                with open(path, encoding="utf-8", errors="replace") as f:
                    content = f.read()
                self.text.delete("1.0", tk.END)
                self.text.insert("1.0", content)
                self.current_file = path
                ext = path.rsplit(".", 1)[-1].lower()
                self.lang_var.set("Python" if ext == "py" else
                                  "HTML" if ext in ("html", "htm") else "なし")
                self._highlight()
                self._update_line_nums()
                self.root.title(f"エディタ — {path}")
            except Exception as e:
                messagebox.showerror("エラー", str(e))

    def _save_file(self):
        if self.current_file:
            self._write(self.current_file)
        else:
            self._save_as()

    def _save_as(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".py",
            filetypes=[("Pythonファイル", "*.py"), ("テキストファイル", "*.txt"),
                       ("すべて", "*.*")])
        if path:
            self.current_file = path
            self._write(path)

    def _write(self, path):
        try:
            with open(path, "w", encoding="utf-8") as f:
                f.write(self.text.get("1.0", tk.END))
            self.root.title(f"エディタ — {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _insert_sample(self):
        sample = '''# Pythonサンプルコード
def greet(name: str) -> str:
    """挨拶文を返す関数"""
    if not isinstance(name, str):
        raise TypeError("nameはstr型である必要があります")
    return f"Hello, {name}!"

class Counter:
    """カウンタークラス"""

    def __init__(self, start=0):
        self.count = start

    def increment(self):
        self.count += 1
        return self

    def reset(self):
        self.count = 0

# メイン処理
if __name__ == "__main__":
    counter = Counter(start=10)
    for i in range(5):
        counter.increment()
    print(f"カウント: {counter.count}")
    print(greet("Python"))
'''
        self.text.insert("1.0", sample)
        self._highlight()
        self._update_line_nums()


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

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

結果表示にはtk.Textウィジェットを使います。state=tk.DISABLEDでユーザーが直接編集できないようにし、表示前にNORMALに切り替えてからinsert()で内容を更新します。

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


class App02:
    """シンタックスハイライト付きエディタ"""

    THEMES = {
        "Python": {
            "keyword":   (r"\b(False|None|True|and|as|assert|async|await|break|class|"
                          r"continue|def|del|elif|else|except|finally|for|from|global|"
                          r"if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|"
                          r"try|while|with|yield)\b", "#cc7832"),
            "builtin":   (r"\b(print|len|range|int|float|str|list|dict|set|tuple|bool|"
                          r"type|input|open|enumerate|zip|map|filter|sorted|reversed|"
                          r"abs|max|min|sum|isinstance|hasattr|getattr|setattr)\b", "#8888cc"),
            "string":    (r'("(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\')', "#6a8759"),
            "comment":   (r"(#[^\n]*)", "#808080"),
            "number":    (r"\b(\d+(?:\.\d+)?)\b", "#6897bb"),
            "decorator": (r"(@\w+)", "#bbb529"),
        },
        "HTML": {
            "tag":     (r"(</?[\w!][^>]*>)", "#e8bf6a"),
            "attr":    (r'(\s[\w-]+=)', "#9876aa"),
            "string":  (r'"[^"]*"', "#6a8759"),
            "comment": (r"(<!--.*?-->)", "#808080"),
        },
        "なし": {},
    }

    def __init__(self, root):
        self.root = root
        self.root.title("シンタックスハイライト付きエディタ")
        self.root.geometry("820x580")
        self.root.configure(bg="#2b2b2b")
        self.current_file = None
        self.lang_var = tk.StringVar(value="Python")
        self._build_ui()
        self._insert_sample()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#3c3f41", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="✏️ シンタックスハイライト付きエディタ",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#3c3f41", fg="#a9b7c6").pack(side=tk.LEFT, padx=12)

        toolbar = tk.Frame(self.root, bg="#3c3f41", pady=3)
        toolbar.pack(fill=tk.X)
        for text, cmd in [("📂 開く", self._open_file),
                          ("💾 保存", self._save_file),
                          ("💾 名前を付けて保存", self._save_as)]:
            tk.Button(toolbar, text=text, bg="#4c5052", fg="#a9b7c6",
                      relief=tk.FLAT, font=("Arial", 9), padx=8,
                      activebackground="#555", activeforeground="white",
                      command=cmd).pack(side=tk.LEFT, padx=2)

        tk.Label(toolbar, text="  言語:", bg="#3c3f41",
                 fg="#a9b7c6", font=("Arial", 10)).pack(side=tk.LEFT, padx=(16, 4))
        lang_cb = ttk.Combobox(toolbar, textvariable=self.lang_var,
                               values=list(self.THEMES.keys()),
                               width=10, state="readonly")
        lang_cb.pack(side=tk.LEFT)
        lang_cb.bind("<<ComboboxSelected>>", lambda e: self._highlight())

        editor_frame = tk.Frame(self.root, bg="#2b2b2b")
        editor_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        self.line_nums = tk.Text(editor_frame, width=4, bg="#313335",
                                 fg="#606366", font=("Courier New", 12),
                                 state=tk.DISABLED, relief=tk.FLAT,
                                 padx=4, pady=4, takefocus=0)
        self.line_nums.pack(side=tk.LEFT, fill=tk.Y)

        self.text = tk.Text(editor_frame, bg="#2b2b2b", fg="#a9b7c6",
                            font=("Courier New", 12), insertbackground="white",
                            relief=tk.FLAT, undo=True, padx=8, pady=4,
                            selectbackground="#214283",
                            tabs="    ")
        self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        sb = ttk.Scrollbar(editor_frame, command=self.text.yview)
        sb.pack(side=tk.RIGHT, fill=tk.Y)
        self.text.configure(yscrollcommand=sb.set)
        self.text.bind("<KeyRelease>", self._on_key)

        self._setup_tags()

        self.status_var = tk.StringVar(value="行: 1  列: 1")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#3c3f41", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _setup_tags(self):
        colors = {
            "keyword": "#cc7832", "builtin": "#8888cc",
            "string": "#6a8759", "comment": "#808080",
            "number": "#6897bb", "decorator": "#bbb529",
            "tag": "#e8bf6a", "attr": "#9876aa",
        }
        for name, color in colors.items():
            self.text.tag_configure(name, foreground=color)

    def _on_key(self, event=None):
        self._update_line_nums()
        self._highlight()
        pos = self.text.index(tk.INSERT)
        row, col = pos.split(".")
        self.status_var.set(f"行: {row}  列: {int(col)+1}")

    def _update_line_nums(self):
        content = self.text.get("1.0", tk.END)
        lines = content.count("\n")
        self.line_nums.config(state=tk.NORMAL)
        self.line_nums.delete("1.0", tk.END)
        self.line_nums.insert("1.0", "\n".join(str(i) for i in range(1, lines + 1)))
        self.line_nums.config(state=tk.DISABLED)

    def _highlight(self):
        lang = self.lang_var.get()
        rules = self.THEMES.get(lang, {})
        for tag in ["keyword", "builtin", "string", "comment",
                    "number", "decorator", "tag", "attr"]:
            self.text.tag_remove(tag, "1.0", tk.END)
        content = self.text.get("1.0", tk.END)
        for tag, (pattern, _) in rules.items():
            for m in re.finditer(pattern, content, re.DOTALL):
                start = f"1.0+{m.start()}c"
                end = f"1.0+{m.end()}c"
                self.text.tag_add(tag, start, end)

    def _open_file(self):
        path = filedialog.askopenfilename(
            filetypes=[("Pythonファイル", "*.py"), ("HTMLファイル", "*.html"),
                       ("テキストファイル", "*.txt"), ("すべて", "*.*")])
        if path:
            try:
                with open(path, encoding="utf-8", errors="replace") as f:
                    content = f.read()
                self.text.delete("1.0", tk.END)
                self.text.insert("1.0", content)
                self.current_file = path
                ext = path.rsplit(".", 1)[-1].lower()
                self.lang_var.set("Python" if ext == "py" else
                                  "HTML" if ext in ("html", "htm") else "なし")
                self._highlight()
                self._update_line_nums()
                self.root.title(f"エディタ — {path}")
            except Exception as e:
                messagebox.showerror("エラー", str(e))

    def _save_file(self):
        if self.current_file:
            self._write(self.current_file)
        else:
            self._save_as()

    def _save_as(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".py",
            filetypes=[("Pythonファイル", "*.py"), ("テキストファイル", "*.txt"),
                       ("すべて", "*.*")])
        if path:
            self.current_file = path
            self._write(path)

    def _write(self, path):
        try:
            with open(path, "w", encoding="utf-8") as f:
                f.write(self.text.get("1.0", tk.END))
            self.root.title(f"エディタ — {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _insert_sample(self):
        sample = '''# Pythonサンプルコード
def greet(name: str) -> str:
    """挨拶文を返す関数"""
    if not isinstance(name, str):
        raise TypeError("nameはstr型である必要があります")
    return f"Hello, {name}!"

class Counter:
    """カウンタークラス"""

    def __init__(self, start=0):
        self.count = start

    def increment(self):
        self.count += 1
        return self

    def reset(self):
        self.count = 0

# メイン処理
if __name__ == "__main__":
    counter = Counter(start=10)
    for i in range(5):
        counter.increment()
    print(f"カウント: {counter.count}")
    print(greet("Python"))
'''
        self.text.insert("1.0", sample)
        self._highlight()
        self._update_line_nums()


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

例外処理とmessagebox

try-except で ValueError と Exception を捕捉し、messagebox.showerror() でユーザーにわかりやすいエラーメッセージを表示します。入力バリデーションは必ず実装しましょう。

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


class App02:
    """シンタックスハイライト付きエディタ"""

    THEMES = {
        "Python": {
            "keyword":   (r"\b(False|None|True|and|as|assert|async|await|break|class|"
                          r"continue|def|del|elif|else|except|finally|for|from|global|"
                          r"if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|"
                          r"try|while|with|yield)\b", "#cc7832"),
            "builtin":   (r"\b(print|len|range|int|float|str|list|dict|set|tuple|bool|"
                          r"type|input|open|enumerate|zip|map|filter|sorted|reversed|"
                          r"abs|max|min|sum|isinstance|hasattr|getattr|setattr)\b", "#8888cc"),
            "string":    (r'("(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\')', "#6a8759"),
            "comment":   (r"(#[^\n]*)", "#808080"),
            "number":    (r"\b(\d+(?:\.\d+)?)\b", "#6897bb"),
            "decorator": (r"(@\w+)", "#bbb529"),
        },
        "HTML": {
            "tag":     (r"(</?[\w!][^>]*>)", "#e8bf6a"),
            "attr":    (r'(\s[\w-]+=)', "#9876aa"),
            "string":  (r'"[^"]*"', "#6a8759"),
            "comment": (r"(<!--.*?-->)", "#808080"),
        },
        "なし": {},
    }

    def __init__(self, root):
        self.root = root
        self.root.title("シンタックスハイライト付きエディタ")
        self.root.geometry("820x580")
        self.root.configure(bg="#2b2b2b")
        self.current_file = None
        self.lang_var = tk.StringVar(value="Python")
        self._build_ui()
        self._insert_sample()

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#3c3f41", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="✏️ シンタックスハイライト付きエディタ",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#3c3f41", fg="#a9b7c6").pack(side=tk.LEFT, padx=12)

        toolbar = tk.Frame(self.root, bg="#3c3f41", pady=3)
        toolbar.pack(fill=tk.X)
        for text, cmd in [("📂 開く", self._open_file),
                          ("💾 保存", self._save_file),
                          ("💾 名前を付けて保存", self._save_as)]:
            tk.Button(toolbar, text=text, bg="#4c5052", fg="#a9b7c6",
                      relief=tk.FLAT, font=("Arial", 9), padx=8,
                      activebackground="#555", activeforeground="white",
                      command=cmd).pack(side=tk.LEFT, padx=2)

        tk.Label(toolbar, text="  言語:", bg="#3c3f41",
                 fg="#a9b7c6", font=("Arial", 10)).pack(side=tk.LEFT, padx=(16, 4))
        lang_cb = ttk.Combobox(toolbar, textvariable=self.lang_var,
                               values=list(self.THEMES.keys()),
                               width=10, state="readonly")
        lang_cb.pack(side=tk.LEFT)
        lang_cb.bind("<<ComboboxSelected>>", lambda e: self._highlight())

        editor_frame = tk.Frame(self.root, bg="#2b2b2b")
        editor_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)

        self.line_nums = tk.Text(editor_frame, width=4, bg="#313335",
                                 fg="#606366", font=("Courier New", 12),
                                 state=tk.DISABLED, relief=tk.FLAT,
                                 padx=4, pady=4, takefocus=0)
        self.line_nums.pack(side=tk.LEFT, fill=tk.Y)

        self.text = tk.Text(editor_frame, bg="#2b2b2b", fg="#a9b7c6",
                            font=("Courier New", 12), insertbackground="white",
                            relief=tk.FLAT, undo=True, padx=8, pady=4,
                            selectbackground="#214283",
                            tabs="    ")
        self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        sb = ttk.Scrollbar(editor_frame, command=self.text.yview)
        sb.pack(side=tk.RIGHT, fill=tk.Y)
        self.text.configure(yscrollcommand=sb.set)
        self.text.bind("<KeyRelease>", self._on_key)

        self._setup_tags()

        self.status_var = tk.StringVar(value="行: 1  列: 1")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#3c3f41", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _setup_tags(self):
        colors = {
            "keyword": "#cc7832", "builtin": "#8888cc",
            "string": "#6a8759", "comment": "#808080",
            "number": "#6897bb", "decorator": "#bbb529",
            "tag": "#e8bf6a", "attr": "#9876aa",
        }
        for name, color in colors.items():
            self.text.tag_configure(name, foreground=color)

    def _on_key(self, event=None):
        self._update_line_nums()
        self._highlight()
        pos = self.text.index(tk.INSERT)
        row, col = pos.split(".")
        self.status_var.set(f"行: {row}  列: {int(col)+1}")

    def _update_line_nums(self):
        content = self.text.get("1.0", tk.END)
        lines = content.count("\n")
        self.line_nums.config(state=tk.NORMAL)
        self.line_nums.delete("1.0", tk.END)
        self.line_nums.insert("1.0", "\n".join(str(i) for i in range(1, lines + 1)))
        self.line_nums.config(state=tk.DISABLED)

    def _highlight(self):
        lang = self.lang_var.get()
        rules = self.THEMES.get(lang, {})
        for tag in ["keyword", "builtin", "string", "comment",
                    "number", "decorator", "tag", "attr"]:
            self.text.tag_remove(tag, "1.0", tk.END)
        content = self.text.get("1.0", tk.END)
        for tag, (pattern, _) in rules.items():
            for m in re.finditer(pattern, content, re.DOTALL):
                start = f"1.0+{m.start()}c"
                end = f"1.0+{m.end()}c"
                self.text.tag_add(tag, start, end)

    def _open_file(self):
        path = filedialog.askopenfilename(
            filetypes=[("Pythonファイル", "*.py"), ("HTMLファイル", "*.html"),
                       ("テキストファイル", "*.txt"), ("すべて", "*.*")])
        if path:
            try:
                with open(path, encoding="utf-8", errors="replace") as f:
                    content = f.read()
                self.text.delete("1.0", tk.END)
                self.text.insert("1.0", content)
                self.current_file = path
                ext = path.rsplit(".", 1)[-1].lower()
                self.lang_var.set("Python" if ext == "py" else
                                  "HTML" if ext in ("html", "htm") else "なし")
                self._highlight()
                self._update_line_nums()
                self.root.title(f"エディタ — {path}")
            except Exception as e:
                messagebox.showerror("エラー", str(e))

    def _save_file(self):
        if self.current_file:
            self._write(self.current_file)
        else:
            self._save_as()

    def _save_as(self):
        path = filedialog.asksaveasfilename(
            defaultextension=".py",
            filetypes=[("Pythonファイル", "*.py"), ("テキストファイル", "*.txt"),
                       ("すべて", "*.*")])
        if path:
            self.current_file = path
            self._write(path)

    def _write(self, path):
        try:
            with open(path, "w", encoding="utf-8") as f:
                f.write(self.text.get("1.0", tk.END))
            self.root.title(f"エディタ — {path}")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _insert_sample(self):
        sample = '''# Pythonサンプルコード
def greet(name: str) -> str:
    """挨拶文を返す関数"""
    if not isinstance(name, str):
        raise TypeError("nameはstr型である必要があります")
    return f"Hello, {name}!"

class Counter:
    """カウンタークラス"""

    def __init__(self, start=0):
        self.count = start

    def increment(self):
        self.count += 1
        return self

    def reset(self):
        self.count = 0

# メイン処理
if __name__ == "__main__":
    counter = Counter(start=10)
    for i in range(5):
        counter.increment()
    print(f"カウント: {counter.count}")
    print(greet("Python"))
'''
        self.text.insert("1.0", sample)
        self._highlight()
        self._update_line_nums()


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

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

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

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

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

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

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

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

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

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

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

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

    _calculate()メソッドに計算・処理ロジックを実装します。

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

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

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

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

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

基本機能を習得したら、以下のカスタマイズに挑戦してみましょう。少しずつ機能を追加することで、Pythonのスキルが飛躍的に向上します。

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

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

💡 データのエクスポート機能

計算結果をCSV・TXTファイルに保存するエクスポート機能を追加しましょう。filedialog.asksaveasfilename()でファイル保存ダイアログが使えます。

💡 入力履歴機能

以前の入力値を覚えておいてComboboxのドロップダウンで再選択できる履歴機能を追加しましょう。

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

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

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

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

❌ ウィンドウのサイズが変更できない

原因:resizable(False, False)が設定されています。

解決法:resizable(True, True)に変更してください。

9. 練習問題

アプリの理解を深めるための練習問題です。難易度順に挑戦してみてください。

  1. 課題1:機能拡張

    シンタックスハイライト付きエディタに新しい機能を1つ追加してみましょう。どんな機能があると便利か考えてから実装してください。

  2. 課題2:UIの改善

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

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

    入力値や計算結果をファイルに保存する機能を追加しましょう。jsonやcsvモジュールを使います。

🚀
次に挑戦するアプリ

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