中級者向け No.27

ディレクトリ同期ツール

2つのフォルダを比較して差分をハイライト表示・同期できるツール。filecmpモジュールとshutilの活用を学びます。

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

1. アプリ概要

2つのフォルダを比較して差分をハイライト表示・同期できるツール。filecmpモジュールとshutilの活用を学びます。

このアプリは中級カテゴリに分類される実践的な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. 完全なソースコード

💡
コードのコピー方法

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

app27.py
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import shutil
import filecmp
import threading
from datetime import datetime


class App27:
    """ディレクトリ同期ツール"""

    def __init__(self, root):
        self.root = root
        self.root.title("ディレクトリ同期ツール")
        self.root.geometry("900x600")
        self.root.configure(bg="#f8f9fc")
        self.comparing = False
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#4a148c", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🔄 ディレクトリ同期ツール",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#4a148c", fg="white").pack(side=tk.LEFT, padx=12)

        # フォルダ選択
        dir_frame = ttk.LabelFrame(self.root, text="比較フォルダ", padding=10)
        dir_frame.pack(fill=tk.X, padx=8, pady=6)

        for i, (lbl, attr) in enumerate([("左フォルダ (ソース)", "left"),
                                          ("右フォルダ (ターゲット)", "right")]):
            row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
            row.pack(fill=tk.X, pady=2)
            tk.Label(row, text=f"{lbl}:", bg=row.cget("bg"),
                     width=22, anchor="w").pack(side=tk.LEFT)
            var = tk.StringVar()
            setattr(self, f"{attr}_var", var)
            ttk.Entry(row, textvariable=var, width=50).pack(side=tk.LEFT, padx=4)
            ttk.Button(row, text="📂",
                       command=lambda a=attr: self._browse(a)).pack(side=tk.LEFT)

        btn_row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
        btn_row.pack(fill=tk.X, pady=6)
        ttk.Button(btn_row, text="🔍 比較",
                   command=self._compare).pack(side=tk.LEFT, padx=8)

        self.sync_mode_var = tk.StringVar(value="left_to_right")
        for val, lbl in [("left_to_right", "左→右 (上書きコピー)"),
                          ("right_to_left", "右→左 (上書きコピー)"),
                          ("two_way", "双方向同期")]:
            ttk.Radiobutton(btn_row, text=lbl, variable=self.sync_mode_var,
                            value=val).pack(side=tk.LEFT, padx=6)
        ttk.Button(btn_row, text="✅ 同期実行",
                   command=self._sync).pack(side=tk.RIGHT, padx=8)

        # プログレス
        self.progress_var = tk.IntVar(value=0)
        self.progress = ttk.Progressbar(self.root, variable=self.progress_var)
        self.progress.pack(fill=tk.X, padx=8)

        # 差分結果
        result_frame = ttk.LabelFrame(self.root, text="差分結果", padding=4)
        result_frame.pack(fill=tk.BOTH, expand=True, padx=8, pady=6)
        cols = ("status", "path", "size_l", "date_l",
                "size_r", "date_r", "action")
        self.tree = ttk.Treeview(result_frame, columns=cols,
                                  show="headings", selectmode="extended")
        for c, h, w in [("status", "状態", 80), ("path", "パス", 260),
                         ("size_l", "左サイズ", 80), ("date_l", "左更新日", 130),
                         ("size_r", "右サイズ", 80), ("date_r", "右更新日", 130),
                         ("action", "アクション", 80)]:
            self.tree.heading(c, text=h)
            self.tree.column(c, width=w, minwidth=40)
        h_sb = ttk.Scrollbar(result_frame, orient=tk.HORIZONTAL,
                             command=self.tree.xview)
        v_sb = ttk.Scrollbar(result_frame, orient=tk.VERTICAL,
                             command=self.tree.yview)
        self.tree.configure(xscrollcommand=h_sb.set, yscrollcommand=v_sb.set)
        v_sb.pack(side=tk.RIGHT, fill=tk.Y)
        h_sb.pack(side=tk.BOTTOM, fill=tk.X)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.tag_configure("only_left", background="#e8f5e9")
        self.tree.tag_configure("only_right", background="#fce4ec")
        self.tree.tag_configure("differ", background="#fff3e0")
        self.tree.tag_configure("same", foreground="#aaa")

        self.status_var = tk.StringVar(value="フォルダを選択して比較してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _browse(self, side):
        path = filedialog.askdirectory()
        if path:
            getattr(self, f"{side}_var").set(path)

    def _compare(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "両方のフォルダを選択してください")
            return
        if not os.path.isdir(left) or not os.path.isdir(right):
            messagebox.showerror("エラー", "有効なフォルダを指定してください")
            return
        self.tree.delete(*self.tree.get_children())
        self.progress_var.set(0)
        threading.Thread(target=self._do_compare,
                         args=(left, right), daemon=True).start()

    def _do_compare(self, left, right):
        results = []
        self._collect_diffs(left, right, "", results)
        total = len(results)
        for i, item in enumerate(results):
            self.root.after(0, self._add_row, item)
            pct = int((i + 1) / max(total, 1) * 100)
            self.root.after(0, self.progress_var.set, pct)
        self.root.after(0, self.status_var.set,
                        f"比較完了: {total} 件  "
                        f"({datetime.now().strftime('%H:%M:%S')})")

    def _collect_diffs(self, left_base, right_base, rel, results):
        left_dir = os.path.join(left_base, rel) if rel else left_base
        right_dir = os.path.join(right_base, rel) if rel else right_base

        try:
            left_files = set(os.listdir(left_dir)) if os.path.isdir(left_dir) else set()
        except PermissionError:
            left_files = set()
        try:
            right_files = set(os.listdir(right_dir)) if os.path.isdir(right_dir) else set()
        except PermissionError:
            right_files = set()

        all_files = left_files | right_files
        for name in sorted(all_files):
            rel_path = os.path.join(rel, name) if rel else name
            left_path = os.path.join(left_base, rel_path)
            right_path = os.path.join(right_base, rel_path)
            l_exists = os.path.exists(left_path)
            r_exists = os.path.exists(right_path)
            l_is_dir = os.path.isdir(left_path) if l_exists else False
            r_is_dir = os.path.isdir(right_path) if r_exists else False

            if l_is_dir or r_is_dir:
                self._collect_diffs(left_base, right_base, rel_path, results)
                continue

            if l_exists and not r_exists:
                status = "左のみ"
                tag = "only_left"
                action = "→ コピー"
            elif r_exists and not l_exists:
                status = "右のみ"
                tag = "only_right"
                action = "← コピー"
            else:
                same = filecmp.cmp(left_path, right_path, shallow=False)
                if same:
                    status = "同一"
                    tag = "same"
                    action = "-"
                else:
                    l_newer = os.path.getmtime(left_path) > os.path.getmtime(right_path)
                    status = "差異あり"
                    tag = "differ"
                    action = "→ 更新" if l_newer else "← 更新"
            l_info = self._file_info(left_path) if l_exists else ("", "")
            r_info = self._file_info(right_path) if r_exists else ("", "")
            results.append((status, rel_path,
                             l_info[0], l_info[1],
                             r_info[0], r_info[1],
                             action, tag))

    def _file_info(self, path):
        try:
            stat = os.stat(path)
            size = self._fmt_size(stat.st_size)
            mtime = datetime.fromtimestamp(stat.st_mtime).strftime("%Y/%m/%d %H:%M")
            return size, mtime
        except Exception:
            return "", ""

    def _fmt_size(self, size):
        for unit in ["B", "KB", "MB", "GB"]:
            if size < 1024:
                return f"{size:.0f}{unit}"
            size /= 1024
        return f"{size:.1f}TB"

    def _add_row(self, item):
        *vals, tag = item
        self.tree.insert("", "end", values=vals, tags=(tag,))

    def _sync(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "フォルダを選択してください")
            return
        mode = self.sync_mode_var.get()
        if not messagebox.askyesno("確認",
                                   f"同期を実行しますか?\nモード: {mode}"):
            return
        count = 0
        errors = 0
        for item in self.tree.get_children():
            vals = self.tree.item(item)["values"]
            status, rel_path, *_, action = vals
            left_path = os.path.join(left, rel_path)
            right_path = os.path.join(right, rel_path)
            try:
                if mode == "left_to_right":
                    if status in ("左のみ", "差異あり"):
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                elif mode == "right_to_left":
                    if status in ("右のみ", "差異あり"):
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                elif mode == "two_way":
                    if status == "左のみ":
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                    elif status == "右のみ":
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                    elif status == "差異あり":
                        # 新しい方を古い方に上書き
                        if os.path.getmtime(left_path) > os.path.getmtime(right_path):
                            shutil.copy2(left_path, right_path)
                        else:
                            shutil.copy2(right_path, left_path)
                        count += 1
            except Exception as e:
                errors += 1
        messagebox.showinfo("完了",
                            f"同期完了: {count} 件コピー\nエラー: {errors} 件")
        self._compare()


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

5. コード解説

ディレクトリ同期ツールのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。

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

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import shutil
import filecmp
import threading
from datetime import datetime


class App27:
    """ディレクトリ同期ツール"""

    def __init__(self, root):
        self.root = root
        self.root.title("ディレクトリ同期ツール")
        self.root.geometry("900x600")
        self.root.configure(bg="#f8f9fc")
        self.comparing = False
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#4a148c", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🔄 ディレクトリ同期ツール",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#4a148c", fg="white").pack(side=tk.LEFT, padx=12)

        # フォルダ選択
        dir_frame = ttk.LabelFrame(self.root, text="比較フォルダ", padding=10)
        dir_frame.pack(fill=tk.X, padx=8, pady=6)

        for i, (lbl, attr) in enumerate([("左フォルダ (ソース)", "left"),
                                          ("右フォルダ (ターゲット)", "right")]):
            row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
            row.pack(fill=tk.X, pady=2)
            tk.Label(row, text=f"{lbl}:", bg=row.cget("bg"),
                     width=22, anchor="w").pack(side=tk.LEFT)
            var = tk.StringVar()
            setattr(self, f"{attr}_var", var)
            ttk.Entry(row, textvariable=var, width=50).pack(side=tk.LEFT, padx=4)
            ttk.Button(row, text="📂",
                       command=lambda a=attr: self._browse(a)).pack(side=tk.LEFT)

        btn_row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
        btn_row.pack(fill=tk.X, pady=6)
        ttk.Button(btn_row, text="🔍 比較",
                   command=self._compare).pack(side=tk.LEFT, padx=8)

        self.sync_mode_var = tk.StringVar(value="left_to_right")
        for val, lbl in [("left_to_right", "左→右 (上書きコピー)"),
                          ("right_to_left", "右→左 (上書きコピー)"),
                          ("two_way", "双方向同期")]:
            ttk.Radiobutton(btn_row, text=lbl, variable=self.sync_mode_var,
                            value=val).pack(side=tk.LEFT, padx=6)
        ttk.Button(btn_row, text="✅ 同期実行",
                   command=self._sync).pack(side=tk.RIGHT, padx=8)

        # プログレス
        self.progress_var = tk.IntVar(value=0)
        self.progress = ttk.Progressbar(self.root, variable=self.progress_var)
        self.progress.pack(fill=tk.X, padx=8)

        # 差分結果
        result_frame = ttk.LabelFrame(self.root, text="差分結果", padding=4)
        result_frame.pack(fill=tk.BOTH, expand=True, padx=8, pady=6)
        cols = ("status", "path", "size_l", "date_l",
                "size_r", "date_r", "action")
        self.tree = ttk.Treeview(result_frame, columns=cols,
                                  show="headings", selectmode="extended")
        for c, h, w in [("status", "状態", 80), ("path", "パス", 260),
                         ("size_l", "左サイズ", 80), ("date_l", "左更新日", 130),
                         ("size_r", "右サイズ", 80), ("date_r", "右更新日", 130),
                         ("action", "アクション", 80)]:
            self.tree.heading(c, text=h)
            self.tree.column(c, width=w, minwidth=40)
        h_sb = ttk.Scrollbar(result_frame, orient=tk.HORIZONTAL,
                             command=self.tree.xview)
        v_sb = ttk.Scrollbar(result_frame, orient=tk.VERTICAL,
                             command=self.tree.yview)
        self.tree.configure(xscrollcommand=h_sb.set, yscrollcommand=v_sb.set)
        v_sb.pack(side=tk.RIGHT, fill=tk.Y)
        h_sb.pack(side=tk.BOTTOM, fill=tk.X)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.tag_configure("only_left", background="#e8f5e9")
        self.tree.tag_configure("only_right", background="#fce4ec")
        self.tree.tag_configure("differ", background="#fff3e0")
        self.tree.tag_configure("same", foreground="#aaa")

        self.status_var = tk.StringVar(value="フォルダを選択して比較してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _browse(self, side):
        path = filedialog.askdirectory()
        if path:
            getattr(self, f"{side}_var").set(path)

    def _compare(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "両方のフォルダを選択してください")
            return
        if not os.path.isdir(left) or not os.path.isdir(right):
            messagebox.showerror("エラー", "有効なフォルダを指定してください")
            return
        self.tree.delete(*self.tree.get_children())
        self.progress_var.set(0)
        threading.Thread(target=self._do_compare,
                         args=(left, right), daemon=True).start()

    def _do_compare(self, left, right):
        results = []
        self._collect_diffs(left, right, "", results)
        total = len(results)
        for i, item in enumerate(results):
            self.root.after(0, self._add_row, item)
            pct = int((i + 1) / max(total, 1) * 100)
            self.root.after(0, self.progress_var.set, pct)
        self.root.after(0, self.status_var.set,
                        f"比較完了: {total} 件  "
                        f"({datetime.now().strftime('%H:%M:%S')})")

    def _collect_diffs(self, left_base, right_base, rel, results):
        left_dir = os.path.join(left_base, rel) if rel else left_base
        right_dir = os.path.join(right_base, rel) if rel else right_base

        try:
            left_files = set(os.listdir(left_dir)) if os.path.isdir(left_dir) else set()
        except PermissionError:
            left_files = set()
        try:
            right_files = set(os.listdir(right_dir)) if os.path.isdir(right_dir) else set()
        except PermissionError:
            right_files = set()

        all_files = left_files | right_files
        for name in sorted(all_files):
            rel_path = os.path.join(rel, name) if rel else name
            left_path = os.path.join(left_base, rel_path)
            right_path = os.path.join(right_base, rel_path)
            l_exists = os.path.exists(left_path)
            r_exists = os.path.exists(right_path)
            l_is_dir = os.path.isdir(left_path) if l_exists else False
            r_is_dir = os.path.isdir(right_path) if r_exists else False

            if l_is_dir or r_is_dir:
                self._collect_diffs(left_base, right_base, rel_path, results)
                continue

            if l_exists and not r_exists:
                status = "左のみ"
                tag = "only_left"
                action = "→ コピー"
            elif r_exists and not l_exists:
                status = "右のみ"
                tag = "only_right"
                action = "← コピー"
            else:
                same = filecmp.cmp(left_path, right_path, shallow=False)
                if same:
                    status = "同一"
                    tag = "same"
                    action = "-"
                else:
                    l_newer = os.path.getmtime(left_path) > os.path.getmtime(right_path)
                    status = "差異あり"
                    tag = "differ"
                    action = "→ 更新" if l_newer else "← 更新"
            l_info = self._file_info(left_path) if l_exists else ("", "")
            r_info = self._file_info(right_path) if r_exists else ("", "")
            results.append((status, rel_path,
                             l_info[0], l_info[1],
                             r_info[0], r_info[1],
                             action, tag))

    def _file_info(self, path):
        try:
            stat = os.stat(path)
            size = self._fmt_size(stat.st_size)
            mtime = datetime.fromtimestamp(stat.st_mtime).strftime("%Y/%m/%d %H:%M")
            return size, mtime
        except Exception:
            return "", ""

    def _fmt_size(self, size):
        for unit in ["B", "KB", "MB", "GB"]:
            if size < 1024:
                return f"{size:.0f}{unit}"
            size /= 1024
        return f"{size:.1f}TB"

    def _add_row(self, item):
        *vals, tag = item
        self.tree.insert("", "end", values=vals, tags=(tag,))

    def _sync(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "フォルダを選択してください")
            return
        mode = self.sync_mode_var.get()
        if not messagebox.askyesno("確認",
                                   f"同期を実行しますか?\nモード: {mode}"):
            return
        count = 0
        errors = 0
        for item in self.tree.get_children():
            vals = self.tree.item(item)["values"]
            status, rel_path, *_, action = vals
            left_path = os.path.join(left, rel_path)
            right_path = os.path.join(right, rel_path)
            try:
                if mode == "left_to_right":
                    if status in ("左のみ", "差異あり"):
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                elif mode == "right_to_left":
                    if status in ("右のみ", "差異あり"):
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                elif mode == "two_way":
                    if status == "左のみ":
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                    elif status == "右のみ":
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                    elif status == "差異あり":
                        # 新しい方を古い方に上書き
                        if os.path.getmtime(left_path) > os.path.getmtime(right_path):
                            shutil.copy2(left_path, right_path)
                        else:
                            shutil.copy2(right_path, left_path)
                        count += 1
            except Exception as e:
                errors += 1
        messagebox.showinfo("完了",
                            f"同期完了: {count} 件コピー\nエラー: {errors} 件")
        self._compare()


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

LabelFrameによるセクション分け

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import shutil
import filecmp
import threading
from datetime import datetime


class App27:
    """ディレクトリ同期ツール"""

    def __init__(self, root):
        self.root = root
        self.root.title("ディレクトリ同期ツール")
        self.root.geometry("900x600")
        self.root.configure(bg="#f8f9fc")
        self.comparing = False
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#4a148c", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🔄 ディレクトリ同期ツール",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#4a148c", fg="white").pack(side=tk.LEFT, padx=12)

        # フォルダ選択
        dir_frame = ttk.LabelFrame(self.root, text="比較フォルダ", padding=10)
        dir_frame.pack(fill=tk.X, padx=8, pady=6)

        for i, (lbl, attr) in enumerate([("左フォルダ (ソース)", "left"),
                                          ("右フォルダ (ターゲット)", "right")]):
            row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
            row.pack(fill=tk.X, pady=2)
            tk.Label(row, text=f"{lbl}:", bg=row.cget("bg"),
                     width=22, anchor="w").pack(side=tk.LEFT)
            var = tk.StringVar()
            setattr(self, f"{attr}_var", var)
            ttk.Entry(row, textvariable=var, width=50).pack(side=tk.LEFT, padx=4)
            ttk.Button(row, text="📂",
                       command=lambda a=attr: self._browse(a)).pack(side=tk.LEFT)

        btn_row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
        btn_row.pack(fill=tk.X, pady=6)
        ttk.Button(btn_row, text="🔍 比較",
                   command=self._compare).pack(side=tk.LEFT, padx=8)

        self.sync_mode_var = tk.StringVar(value="left_to_right")
        for val, lbl in [("left_to_right", "左→右 (上書きコピー)"),
                          ("right_to_left", "右→左 (上書きコピー)"),
                          ("two_way", "双方向同期")]:
            ttk.Radiobutton(btn_row, text=lbl, variable=self.sync_mode_var,
                            value=val).pack(side=tk.LEFT, padx=6)
        ttk.Button(btn_row, text="✅ 同期実行",
                   command=self._sync).pack(side=tk.RIGHT, padx=8)

        # プログレス
        self.progress_var = tk.IntVar(value=0)
        self.progress = ttk.Progressbar(self.root, variable=self.progress_var)
        self.progress.pack(fill=tk.X, padx=8)

        # 差分結果
        result_frame = ttk.LabelFrame(self.root, text="差分結果", padding=4)
        result_frame.pack(fill=tk.BOTH, expand=True, padx=8, pady=6)
        cols = ("status", "path", "size_l", "date_l",
                "size_r", "date_r", "action")
        self.tree = ttk.Treeview(result_frame, columns=cols,
                                  show="headings", selectmode="extended")
        for c, h, w in [("status", "状態", 80), ("path", "パス", 260),
                         ("size_l", "左サイズ", 80), ("date_l", "左更新日", 130),
                         ("size_r", "右サイズ", 80), ("date_r", "右更新日", 130),
                         ("action", "アクション", 80)]:
            self.tree.heading(c, text=h)
            self.tree.column(c, width=w, minwidth=40)
        h_sb = ttk.Scrollbar(result_frame, orient=tk.HORIZONTAL,
                             command=self.tree.xview)
        v_sb = ttk.Scrollbar(result_frame, orient=tk.VERTICAL,
                             command=self.tree.yview)
        self.tree.configure(xscrollcommand=h_sb.set, yscrollcommand=v_sb.set)
        v_sb.pack(side=tk.RIGHT, fill=tk.Y)
        h_sb.pack(side=tk.BOTTOM, fill=tk.X)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.tag_configure("only_left", background="#e8f5e9")
        self.tree.tag_configure("only_right", background="#fce4ec")
        self.tree.tag_configure("differ", background="#fff3e0")
        self.tree.tag_configure("same", foreground="#aaa")

        self.status_var = tk.StringVar(value="フォルダを選択して比較してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _browse(self, side):
        path = filedialog.askdirectory()
        if path:
            getattr(self, f"{side}_var").set(path)

    def _compare(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "両方のフォルダを選択してください")
            return
        if not os.path.isdir(left) or not os.path.isdir(right):
            messagebox.showerror("エラー", "有効なフォルダを指定してください")
            return
        self.tree.delete(*self.tree.get_children())
        self.progress_var.set(0)
        threading.Thread(target=self._do_compare,
                         args=(left, right), daemon=True).start()

    def _do_compare(self, left, right):
        results = []
        self._collect_diffs(left, right, "", results)
        total = len(results)
        for i, item in enumerate(results):
            self.root.after(0, self._add_row, item)
            pct = int((i + 1) / max(total, 1) * 100)
            self.root.after(0, self.progress_var.set, pct)
        self.root.after(0, self.status_var.set,
                        f"比較完了: {total} 件  "
                        f"({datetime.now().strftime('%H:%M:%S')})")

    def _collect_diffs(self, left_base, right_base, rel, results):
        left_dir = os.path.join(left_base, rel) if rel else left_base
        right_dir = os.path.join(right_base, rel) if rel else right_base

        try:
            left_files = set(os.listdir(left_dir)) if os.path.isdir(left_dir) else set()
        except PermissionError:
            left_files = set()
        try:
            right_files = set(os.listdir(right_dir)) if os.path.isdir(right_dir) else set()
        except PermissionError:
            right_files = set()

        all_files = left_files | right_files
        for name in sorted(all_files):
            rel_path = os.path.join(rel, name) if rel else name
            left_path = os.path.join(left_base, rel_path)
            right_path = os.path.join(right_base, rel_path)
            l_exists = os.path.exists(left_path)
            r_exists = os.path.exists(right_path)
            l_is_dir = os.path.isdir(left_path) if l_exists else False
            r_is_dir = os.path.isdir(right_path) if r_exists else False

            if l_is_dir or r_is_dir:
                self._collect_diffs(left_base, right_base, rel_path, results)
                continue

            if l_exists and not r_exists:
                status = "左のみ"
                tag = "only_left"
                action = "→ コピー"
            elif r_exists and not l_exists:
                status = "右のみ"
                tag = "only_right"
                action = "← コピー"
            else:
                same = filecmp.cmp(left_path, right_path, shallow=False)
                if same:
                    status = "同一"
                    tag = "same"
                    action = "-"
                else:
                    l_newer = os.path.getmtime(left_path) > os.path.getmtime(right_path)
                    status = "差異あり"
                    tag = "differ"
                    action = "→ 更新" if l_newer else "← 更新"
            l_info = self._file_info(left_path) if l_exists else ("", "")
            r_info = self._file_info(right_path) if r_exists else ("", "")
            results.append((status, rel_path,
                             l_info[0], l_info[1],
                             r_info[0], r_info[1],
                             action, tag))

    def _file_info(self, path):
        try:
            stat = os.stat(path)
            size = self._fmt_size(stat.st_size)
            mtime = datetime.fromtimestamp(stat.st_mtime).strftime("%Y/%m/%d %H:%M")
            return size, mtime
        except Exception:
            return "", ""

    def _fmt_size(self, size):
        for unit in ["B", "KB", "MB", "GB"]:
            if size < 1024:
                return f"{size:.0f}{unit}"
            size /= 1024
        return f"{size:.1f}TB"

    def _add_row(self, item):
        *vals, tag = item
        self.tree.insert("", "end", values=vals, tags=(tag,))

    def _sync(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "フォルダを選択してください")
            return
        mode = self.sync_mode_var.get()
        if not messagebox.askyesno("確認",
                                   f"同期を実行しますか?\nモード: {mode}"):
            return
        count = 0
        errors = 0
        for item in self.tree.get_children():
            vals = self.tree.item(item)["values"]
            status, rel_path, *_, action = vals
            left_path = os.path.join(left, rel_path)
            right_path = os.path.join(right, rel_path)
            try:
                if mode == "left_to_right":
                    if status in ("左のみ", "差異あり"):
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                elif mode == "right_to_left":
                    if status in ("右のみ", "差異あり"):
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                elif mode == "two_way":
                    if status == "左のみ":
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                    elif status == "右のみ":
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                    elif status == "差異あり":
                        # 新しい方を古い方に上書き
                        if os.path.getmtime(left_path) > os.path.getmtime(right_path):
                            shutil.copy2(left_path, right_path)
                        else:
                            shutil.copy2(right_path, left_path)
                        count += 1
            except Exception as e:
                errors += 1
        messagebox.showinfo("完了",
                            f"同期完了: {count} 件コピー\nエラー: {errors} 件")
        self._compare()


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

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

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import shutil
import filecmp
import threading
from datetime import datetime


class App27:
    """ディレクトリ同期ツール"""

    def __init__(self, root):
        self.root = root
        self.root.title("ディレクトリ同期ツール")
        self.root.geometry("900x600")
        self.root.configure(bg="#f8f9fc")
        self.comparing = False
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#4a148c", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🔄 ディレクトリ同期ツール",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#4a148c", fg="white").pack(side=tk.LEFT, padx=12)

        # フォルダ選択
        dir_frame = ttk.LabelFrame(self.root, text="比較フォルダ", padding=10)
        dir_frame.pack(fill=tk.X, padx=8, pady=6)

        for i, (lbl, attr) in enumerate([("左フォルダ (ソース)", "left"),
                                          ("右フォルダ (ターゲット)", "right")]):
            row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
            row.pack(fill=tk.X, pady=2)
            tk.Label(row, text=f"{lbl}:", bg=row.cget("bg"),
                     width=22, anchor="w").pack(side=tk.LEFT)
            var = tk.StringVar()
            setattr(self, f"{attr}_var", var)
            ttk.Entry(row, textvariable=var, width=50).pack(side=tk.LEFT, padx=4)
            ttk.Button(row, text="📂",
                       command=lambda a=attr: self._browse(a)).pack(side=tk.LEFT)

        btn_row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
        btn_row.pack(fill=tk.X, pady=6)
        ttk.Button(btn_row, text="🔍 比較",
                   command=self._compare).pack(side=tk.LEFT, padx=8)

        self.sync_mode_var = tk.StringVar(value="left_to_right")
        for val, lbl in [("left_to_right", "左→右 (上書きコピー)"),
                          ("right_to_left", "右→左 (上書きコピー)"),
                          ("two_way", "双方向同期")]:
            ttk.Radiobutton(btn_row, text=lbl, variable=self.sync_mode_var,
                            value=val).pack(side=tk.LEFT, padx=6)
        ttk.Button(btn_row, text="✅ 同期実行",
                   command=self._sync).pack(side=tk.RIGHT, padx=8)

        # プログレス
        self.progress_var = tk.IntVar(value=0)
        self.progress = ttk.Progressbar(self.root, variable=self.progress_var)
        self.progress.pack(fill=tk.X, padx=8)

        # 差分結果
        result_frame = ttk.LabelFrame(self.root, text="差分結果", padding=4)
        result_frame.pack(fill=tk.BOTH, expand=True, padx=8, pady=6)
        cols = ("status", "path", "size_l", "date_l",
                "size_r", "date_r", "action")
        self.tree = ttk.Treeview(result_frame, columns=cols,
                                  show="headings", selectmode="extended")
        for c, h, w in [("status", "状態", 80), ("path", "パス", 260),
                         ("size_l", "左サイズ", 80), ("date_l", "左更新日", 130),
                         ("size_r", "右サイズ", 80), ("date_r", "右更新日", 130),
                         ("action", "アクション", 80)]:
            self.tree.heading(c, text=h)
            self.tree.column(c, width=w, minwidth=40)
        h_sb = ttk.Scrollbar(result_frame, orient=tk.HORIZONTAL,
                             command=self.tree.xview)
        v_sb = ttk.Scrollbar(result_frame, orient=tk.VERTICAL,
                             command=self.tree.yview)
        self.tree.configure(xscrollcommand=h_sb.set, yscrollcommand=v_sb.set)
        v_sb.pack(side=tk.RIGHT, fill=tk.Y)
        h_sb.pack(side=tk.BOTTOM, fill=tk.X)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.tag_configure("only_left", background="#e8f5e9")
        self.tree.tag_configure("only_right", background="#fce4ec")
        self.tree.tag_configure("differ", background="#fff3e0")
        self.tree.tag_configure("same", foreground="#aaa")

        self.status_var = tk.StringVar(value="フォルダを選択して比較してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _browse(self, side):
        path = filedialog.askdirectory()
        if path:
            getattr(self, f"{side}_var").set(path)

    def _compare(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "両方のフォルダを選択してください")
            return
        if not os.path.isdir(left) or not os.path.isdir(right):
            messagebox.showerror("エラー", "有効なフォルダを指定してください")
            return
        self.tree.delete(*self.tree.get_children())
        self.progress_var.set(0)
        threading.Thread(target=self._do_compare,
                         args=(left, right), daemon=True).start()

    def _do_compare(self, left, right):
        results = []
        self._collect_diffs(left, right, "", results)
        total = len(results)
        for i, item in enumerate(results):
            self.root.after(0, self._add_row, item)
            pct = int((i + 1) / max(total, 1) * 100)
            self.root.after(0, self.progress_var.set, pct)
        self.root.after(0, self.status_var.set,
                        f"比較完了: {total} 件  "
                        f"({datetime.now().strftime('%H:%M:%S')})")

    def _collect_diffs(self, left_base, right_base, rel, results):
        left_dir = os.path.join(left_base, rel) if rel else left_base
        right_dir = os.path.join(right_base, rel) if rel else right_base

        try:
            left_files = set(os.listdir(left_dir)) if os.path.isdir(left_dir) else set()
        except PermissionError:
            left_files = set()
        try:
            right_files = set(os.listdir(right_dir)) if os.path.isdir(right_dir) else set()
        except PermissionError:
            right_files = set()

        all_files = left_files | right_files
        for name in sorted(all_files):
            rel_path = os.path.join(rel, name) if rel else name
            left_path = os.path.join(left_base, rel_path)
            right_path = os.path.join(right_base, rel_path)
            l_exists = os.path.exists(left_path)
            r_exists = os.path.exists(right_path)
            l_is_dir = os.path.isdir(left_path) if l_exists else False
            r_is_dir = os.path.isdir(right_path) if r_exists else False

            if l_is_dir or r_is_dir:
                self._collect_diffs(left_base, right_base, rel_path, results)
                continue

            if l_exists and not r_exists:
                status = "左のみ"
                tag = "only_left"
                action = "→ コピー"
            elif r_exists and not l_exists:
                status = "右のみ"
                tag = "only_right"
                action = "← コピー"
            else:
                same = filecmp.cmp(left_path, right_path, shallow=False)
                if same:
                    status = "同一"
                    tag = "same"
                    action = "-"
                else:
                    l_newer = os.path.getmtime(left_path) > os.path.getmtime(right_path)
                    status = "差異あり"
                    tag = "differ"
                    action = "→ 更新" if l_newer else "← 更新"
            l_info = self._file_info(left_path) if l_exists else ("", "")
            r_info = self._file_info(right_path) if r_exists else ("", "")
            results.append((status, rel_path,
                             l_info[0], l_info[1],
                             r_info[0], r_info[1],
                             action, tag))

    def _file_info(self, path):
        try:
            stat = os.stat(path)
            size = self._fmt_size(stat.st_size)
            mtime = datetime.fromtimestamp(stat.st_mtime).strftime("%Y/%m/%d %H:%M")
            return size, mtime
        except Exception:
            return "", ""

    def _fmt_size(self, size):
        for unit in ["B", "KB", "MB", "GB"]:
            if size < 1024:
                return f"{size:.0f}{unit}"
            size /= 1024
        return f"{size:.1f}TB"

    def _add_row(self, item):
        *vals, tag = item
        self.tree.insert("", "end", values=vals, tags=(tag,))

    def _sync(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "フォルダを選択してください")
            return
        mode = self.sync_mode_var.get()
        if not messagebox.askyesno("確認",
                                   f"同期を実行しますか?\nモード: {mode}"):
            return
        count = 0
        errors = 0
        for item in self.tree.get_children():
            vals = self.tree.item(item)["values"]
            status, rel_path, *_, action = vals
            left_path = os.path.join(left, rel_path)
            right_path = os.path.join(right, rel_path)
            try:
                if mode == "left_to_right":
                    if status in ("左のみ", "差異あり"):
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                elif mode == "right_to_left":
                    if status in ("右のみ", "差異あり"):
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                elif mode == "two_way":
                    if status == "左のみ":
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                    elif status == "右のみ":
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                    elif status == "差異あり":
                        # 新しい方を古い方に上書き
                        if os.path.getmtime(left_path) > os.path.getmtime(right_path):
                            shutil.copy2(left_path, right_path)
                        else:
                            shutil.copy2(right_path, left_path)
                        count += 1
            except Exception as e:
                errors += 1
        messagebox.showinfo("完了",
                            f"同期完了: {count} 件コピー\nエラー: {errors} 件")
        self._compare()


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

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

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import shutil
import filecmp
import threading
from datetime import datetime


class App27:
    """ディレクトリ同期ツール"""

    def __init__(self, root):
        self.root = root
        self.root.title("ディレクトリ同期ツール")
        self.root.geometry("900x600")
        self.root.configure(bg="#f8f9fc")
        self.comparing = False
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#4a148c", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🔄 ディレクトリ同期ツール",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#4a148c", fg="white").pack(side=tk.LEFT, padx=12)

        # フォルダ選択
        dir_frame = ttk.LabelFrame(self.root, text="比較フォルダ", padding=10)
        dir_frame.pack(fill=tk.X, padx=8, pady=6)

        for i, (lbl, attr) in enumerate([("左フォルダ (ソース)", "left"),
                                          ("右フォルダ (ターゲット)", "right")]):
            row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
            row.pack(fill=tk.X, pady=2)
            tk.Label(row, text=f"{lbl}:", bg=row.cget("bg"),
                     width=22, anchor="w").pack(side=tk.LEFT)
            var = tk.StringVar()
            setattr(self, f"{attr}_var", var)
            ttk.Entry(row, textvariable=var, width=50).pack(side=tk.LEFT, padx=4)
            ttk.Button(row, text="📂",
                       command=lambda a=attr: self._browse(a)).pack(side=tk.LEFT)

        btn_row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
        btn_row.pack(fill=tk.X, pady=6)
        ttk.Button(btn_row, text="🔍 比較",
                   command=self._compare).pack(side=tk.LEFT, padx=8)

        self.sync_mode_var = tk.StringVar(value="left_to_right")
        for val, lbl in [("left_to_right", "左→右 (上書きコピー)"),
                          ("right_to_left", "右→左 (上書きコピー)"),
                          ("two_way", "双方向同期")]:
            ttk.Radiobutton(btn_row, text=lbl, variable=self.sync_mode_var,
                            value=val).pack(side=tk.LEFT, padx=6)
        ttk.Button(btn_row, text="✅ 同期実行",
                   command=self._sync).pack(side=tk.RIGHT, padx=8)

        # プログレス
        self.progress_var = tk.IntVar(value=0)
        self.progress = ttk.Progressbar(self.root, variable=self.progress_var)
        self.progress.pack(fill=tk.X, padx=8)

        # 差分結果
        result_frame = ttk.LabelFrame(self.root, text="差分結果", padding=4)
        result_frame.pack(fill=tk.BOTH, expand=True, padx=8, pady=6)
        cols = ("status", "path", "size_l", "date_l",
                "size_r", "date_r", "action")
        self.tree = ttk.Treeview(result_frame, columns=cols,
                                  show="headings", selectmode="extended")
        for c, h, w in [("status", "状態", 80), ("path", "パス", 260),
                         ("size_l", "左サイズ", 80), ("date_l", "左更新日", 130),
                         ("size_r", "右サイズ", 80), ("date_r", "右更新日", 130),
                         ("action", "アクション", 80)]:
            self.tree.heading(c, text=h)
            self.tree.column(c, width=w, minwidth=40)
        h_sb = ttk.Scrollbar(result_frame, orient=tk.HORIZONTAL,
                             command=self.tree.xview)
        v_sb = ttk.Scrollbar(result_frame, orient=tk.VERTICAL,
                             command=self.tree.yview)
        self.tree.configure(xscrollcommand=h_sb.set, yscrollcommand=v_sb.set)
        v_sb.pack(side=tk.RIGHT, fill=tk.Y)
        h_sb.pack(side=tk.BOTTOM, fill=tk.X)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.tag_configure("only_left", background="#e8f5e9")
        self.tree.tag_configure("only_right", background="#fce4ec")
        self.tree.tag_configure("differ", background="#fff3e0")
        self.tree.tag_configure("same", foreground="#aaa")

        self.status_var = tk.StringVar(value="フォルダを選択して比較してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _browse(self, side):
        path = filedialog.askdirectory()
        if path:
            getattr(self, f"{side}_var").set(path)

    def _compare(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "両方のフォルダを選択してください")
            return
        if not os.path.isdir(left) or not os.path.isdir(right):
            messagebox.showerror("エラー", "有効なフォルダを指定してください")
            return
        self.tree.delete(*self.tree.get_children())
        self.progress_var.set(0)
        threading.Thread(target=self._do_compare,
                         args=(left, right), daemon=True).start()

    def _do_compare(self, left, right):
        results = []
        self._collect_diffs(left, right, "", results)
        total = len(results)
        for i, item in enumerate(results):
            self.root.after(0, self._add_row, item)
            pct = int((i + 1) / max(total, 1) * 100)
            self.root.after(0, self.progress_var.set, pct)
        self.root.after(0, self.status_var.set,
                        f"比較完了: {total} 件  "
                        f"({datetime.now().strftime('%H:%M:%S')})")

    def _collect_diffs(self, left_base, right_base, rel, results):
        left_dir = os.path.join(left_base, rel) if rel else left_base
        right_dir = os.path.join(right_base, rel) if rel else right_base

        try:
            left_files = set(os.listdir(left_dir)) if os.path.isdir(left_dir) else set()
        except PermissionError:
            left_files = set()
        try:
            right_files = set(os.listdir(right_dir)) if os.path.isdir(right_dir) else set()
        except PermissionError:
            right_files = set()

        all_files = left_files | right_files
        for name in sorted(all_files):
            rel_path = os.path.join(rel, name) if rel else name
            left_path = os.path.join(left_base, rel_path)
            right_path = os.path.join(right_base, rel_path)
            l_exists = os.path.exists(left_path)
            r_exists = os.path.exists(right_path)
            l_is_dir = os.path.isdir(left_path) if l_exists else False
            r_is_dir = os.path.isdir(right_path) if r_exists else False

            if l_is_dir or r_is_dir:
                self._collect_diffs(left_base, right_base, rel_path, results)
                continue

            if l_exists and not r_exists:
                status = "左のみ"
                tag = "only_left"
                action = "→ コピー"
            elif r_exists and not l_exists:
                status = "右のみ"
                tag = "only_right"
                action = "← コピー"
            else:
                same = filecmp.cmp(left_path, right_path, shallow=False)
                if same:
                    status = "同一"
                    tag = "same"
                    action = "-"
                else:
                    l_newer = os.path.getmtime(left_path) > os.path.getmtime(right_path)
                    status = "差異あり"
                    tag = "differ"
                    action = "→ 更新" if l_newer else "← 更新"
            l_info = self._file_info(left_path) if l_exists else ("", "")
            r_info = self._file_info(right_path) if r_exists else ("", "")
            results.append((status, rel_path,
                             l_info[0], l_info[1],
                             r_info[0], r_info[1],
                             action, tag))

    def _file_info(self, path):
        try:
            stat = os.stat(path)
            size = self._fmt_size(stat.st_size)
            mtime = datetime.fromtimestamp(stat.st_mtime).strftime("%Y/%m/%d %H:%M")
            return size, mtime
        except Exception:
            return "", ""

    def _fmt_size(self, size):
        for unit in ["B", "KB", "MB", "GB"]:
            if size < 1024:
                return f"{size:.0f}{unit}"
            size /= 1024
        return f"{size:.1f}TB"

    def _add_row(self, item):
        *vals, tag = item
        self.tree.insert("", "end", values=vals, tags=(tag,))

    def _sync(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "フォルダを選択してください")
            return
        mode = self.sync_mode_var.get()
        if not messagebox.askyesno("確認",
                                   f"同期を実行しますか?\nモード: {mode}"):
            return
        count = 0
        errors = 0
        for item in self.tree.get_children():
            vals = self.tree.item(item)["values"]
            status, rel_path, *_, action = vals
            left_path = os.path.join(left, rel_path)
            right_path = os.path.join(right, rel_path)
            try:
                if mode == "left_to_right":
                    if status in ("左のみ", "差異あり"):
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                elif mode == "right_to_left":
                    if status in ("右のみ", "差異あり"):
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                elif mode == "two_way":
                    if status == "左のみ":
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                    elif status == "右のみ":
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                    elif status == "差異あり":
                        # 新しい方を古い方に上書き
                        if os.path.getmtime(left_path) > os.path.getmtime(right_path):
                            shutil.copy2(left_path, right_path)
                        else:
                            shutil.copy2(right_path, left_path)
                        count += 1
            except Exception as e:
                errors += 1
        messagebox.showinfo("完了",
                            f"同期完了: {count} 件コピー\nエラー: {errors} 件")
        self._compare()


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

例外処理とmessagebox

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

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import shutil
import filecmp
import threading
from datetime import datetime


class App27:
    """ディレクトリ同期ツール"""

    def __init__(self, root):
        self.root = root
        self.root.title("ディレクトリ同期ツール")
        self.root.geometry("900x600")
        self.root.configure(bg="#f8f9fc")
        self.comparing = False
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#4a148c", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🔄 ディレクトリ同期ツール",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#4a148c", fg="white").pack(side=tk.LEFT, padx=12)

        # フォルダ選択
        dir_frame = ttk.LabelFrame(self.root, text="比較フォルダ", padding=10)
        dir_frame.pack(fill=tk.X, padx=8, pady=6)

        for i, (lbl, attr) in enumerate([("左フォルダ (ソース)", "left"),
                                          ("右フォルダ (ターゲット)", "right")]):
            row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
            row.pack(fill=tk.X, pady=2)
            tk.Label(row, text=f"{lbl}:", bg=row.cget("bg"),
                     width=22, anchor="w").pack(side=tk.LEFT)
            var = tk.StringVar()
            setattr(self, f"{attr}_var", var)
            ttk.Entry(row, textvariable=var, width=50).pack(side=tk.LEFT, padx=4)
            ttk.Button(row, text="📂",
                       command=lambda a=attr: self._browse(a)).pack(side=tk.LEFT)

        btn_row = tk.Frame(dir_frame, bg=dir_frame.cget("background"))
        btn_row.pack(fill=tk.X, pady=6)
        ttk.Button(btn_row, text="🔍 比較",
                   command=self._compare).pack(side=tk.LEFT, padx=8)

        self.sync_mode_var = tk.StringVar(value="left_to_right")
        for val, lbl in [("left_to_right", "左→右 (上書きコピー)"),
                          ("right_to_left", "右→左 (上書きコピー)"),
                          ("two_way", "双方向同期")]:
            ttk.Radiobutton(btn_row, text=lbl, variable=self.sync_mode_var,
                            value=val).pack(side=tk.LEFT, padx=6)
        ttk.Button(btn_row, text="✅ 同期実行",
                   command=self._sync).pack(side=tk.RIGHT, padx=8)

        # プログレス
        self.progress_var = tk.IntVar(value=0)
        self.progress = ttk.Progressbar(self.root, variable=self.progress_var)
        self.progress.pack(fill=tk.X, padx=8)

        # 差分結果
        result_frame = ttk.LabelFrame(self.root, text="差分結果", padding=4)
        result_frame.pack(fill=tk.BOTH, expand=True, padx=8, pady=6)
        cols = ("status", "path", "size_l", "date_l",
                "size_r", "date_r", "action")
        self.tree = ttk.Treeview(result_frame, columns=cols,
                                  show="headings", selectmode="extended")
        for c, h, w in [("status", "状態", 80), ("path", "パス", 260),
                         ("size_l", "左サイズ", 80), ("date_l", "左更新日", 130),
                         ("size_r", "右サイズ", 80), ("date_r", "右更新日", 130),
                         ("action", "アクション", 80)]:
            self.tree.heading(c, text=h)
            self.tree.column(c, width=w, minwidth=40)
        h_sb = ttk.Scrollbar(result_frame, orient=tk.HORIZONTAL,
                             command=self.tree.xview)
        v_sb = ttk.Scrollbar(result_frame, orient=tk.VERTICAL,
                             command=self.tree.yview)
        self.tree.configure(xscrollcommand=h_sb.set, yscrollcommand=v_sb.set)
        v_sb.pack(side=tk.RIGHT, fill=tk.Y)
        h_sb.pack(side=tk.BOTTOM, fill=tk.X)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.tag_configure("only_left", background="#e8f5e9")
        self.tree.tag_configure("only_right", background="#fce4ec")
        self.tree.tag_configure("differ", background="#fff3e0")
        self.tree.tag_configure("same", foreground="#aaa")

        self.status_var = tk.StringVar(value="フォルダを選択して比較してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _browse(self, side):
        path = filedialog.askdirectory()
        if path:
            getattr(self, f"{side}_var").set(path)

    def _compare(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "両方のフォルダを選択してください")
            return
        if not os.path.isdir(left) or not os.path.isdir(right):
            messagebox.showerror("エラー", "有効なフォルダを指定してください")
            return
        self.tree.delete(*self.tree.get_children())
        self.progress_var.set(0)
        threading.Thread(target=self._do_compare,
                         args=(left, right), daemon=True).start()

    def _do_compare(self, left, right):
        results = []
        self._collect_diffs(left, right, "", results)
        total = len(results)
        for i, item in enumerate(results):
            self.root.after(0, self._add_row, item)
            pct = int((i + 1) / max(total, 1) * 100)
            self.root.after(0, self.progress_var.set, pct)
        self.root.after(0, self.status_var.set,
                        f"比較完了: {total} 件  "
                        f"({datetime.now().strftime('%H:%M:%S')})")

    def _collect_diffs(self, left_base, right_base, rel, results):
        left_dir = os.path.join(left_base, rel) if rel else left_base
        right_dir = os.path.join(right_base, rel) if rel else right_base

        try:
            left_files = set(os.listdir(left_dir)) if os.path.isdir(left_dir) else set()
        except PermissionError:
            left_files = set()
        try:
            right_files = set(os.listdir(right_dir)) if os.path.isdir(right_dir) else set()
        except PermissionError:
            right_files = set()

        all_files = left_files | right_files
        for name in sorted(all_files):
            rel_path = os.path.join(rel, name) if rel else name
            left_path = os.path.join(left_base, rel_path)
            right_path = os.path.join(right_base, rel_path)
            l_exists = os.path.exists(left_path)
            r_exists = os.path.exists(right_path)
            l_is_dir = os.path.isdir(left_path) if l_exists else False
            r_is_dir = os.path.isdir(right_path) if r_exists else False

            if l_is_dir or r_is_dir:
                self._collect_diffs(left_base, right_base, rel_path, results)
                continue

            if l_exists and not r_exists:
                status = "左のみ"
                tag = "only_left"
                action = "→ コピー"
            elif r_exists and not l_exists:
                status = "右のみ"
                tag = "only_right"
                action = "← コピー"
            else:
                same = filecmp.cmp(left_path, right_path, shallow=False)
                if same:
                    status = "同一"
                    tag = "same"
                    action = "-"
                else:
                    l_newer = os.path.getmtime(left_path) > os.path.getmtime(right_path)
                    status = "差異あり"
                    tag = "differ"
                    action = "→ 更新" if l_newer else "← 更新"
            l_info = self._file_info(left_path) if l_exists else ("", "")
            r_info = self._file_info(right_path) if r_exists else ("", "")
            results.append((status, rel_path,
                             l_info[0], l_info[1],
                             r_info[0], r_info[1],
                             action, tag))

    def _file_info(self, path):
        try:
            stat = os.stat(path)
            size = self._fmt_size(stat.st_size)
            mtime = datetime.fromtimestamp(stat.st_mtime).strftime("%Y/%m/%d %H:%M")
            return size, mtime
        except Exception:
            return "", ""

    def _fmt_size(self, size):
        for unit in ["B", "KB", "MB", "GB"]:
            if size < 1024:
                return f"{size:.0f}{unit}"
            size /= 1024
        return f"{size:.1f}TB"

    def _add_row(self, item):
        *vals, tag = item
        self.tree.insert("", "end", values=vals, tags=(tag,))

    def _sync(self):
        left = self.left_var.get().strip()
        right = self.right_var.get().strip()
        if not left or not right:
            messagebox.showwarning("警告", "フォルダを選択してください")
            return
        mode = self.sync_mode_var.get()
        if not messagebox.askyesno("確認",
                                   f"同期を実行しますか?\nモード: {mode}"):
            return
        count = 0
        errors = 0
        for item in self.tree.get_children():
            vals = self.tree.item(item)["values"]
            status, rel_path, *_, action = vals
            left_path = os.path.join(left, rel_path)
            right_path = os.path.join(right, rel_path)
            try:
                if mode == "left_to_right":
                    if status in ("左のみ", "差異あり"):
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                elif mode == "right_to_left":
                    if status in ("右のみ", "差異あり"):
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                elif mode == "two_way":
                    if status == "左のみ":
                        os.makedirs(os.path.dirname(right_path), exist_ok=True)
                        shutil.copy2(left_path, right_path)
                        count += 1
                    elif status == "右のみ":
                        os.makedirs(os.path.dirname(left_path), exist_ok=True)
                        shutil.copy2(right_path, left_path)
                        count += 1
                    elif status == "差異あり":
                        # 新しい方を古い方に上書き
                        if os.path.getmtime(left_path) > os.path.getmtime(right_path):
                            shutil.copy2(left_path, right_path)
                        else:
                            shutil.copy2(right_path, left_path)
                        count += 1
            except Exception as e:
                errors += 1
        messagebox.showinfo("完了",
                            f"同期完了: {count} 件コピー\nエラー: {errors} 件")
        self._compare()


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

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

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

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

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

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

    App27クラスを定義し、__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.28に挑戦しましょう。