中級者向け No.076

バーコードリーダー

画像ファイルまたはWebカメラからpyzbarでバーコード・QRコードを読み取り内容を表示するツール。

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

1. アプリ概要

画像ファイルまたはWebカメラからpyzbarでバーコード・QRコードを読み取り内容を表示するツール。

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

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

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

2. 機能一覧

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

3. 事前準備・環境

ℹ️
動作確認環境

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

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

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

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

pip install pyzbar opencv-python pillow

4. 完全なソースコード

💡
コードのコピー方法

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

app076.py
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import threading

try:
    import cv2
    CV2_AVAILABLE = True
except ImportError:
    CV2_AVAILABLE = False

try:
    from pyzbar import pyzbar
    PYZBAR_AVAILABLE = True
except ImportError:
    PYZBAR_AVAILABLE = False

try:
    from PIL import Image, ImageTk
    PIL_AVAILABLE = True
except ImportError:
    PIL_AVAILABLE = False


class App076:
    """バーコード・QRコードリーダー"""

    def __init__(self, root):
        self.root = root
        self.root.title("バーコード・QRコードリーダー")
        self.root.geometry("860x580")
        self.root.configure(bg="#1e1e1e")
        self._cap = None
        self._running = False
        self._results = []
        self._build_ui()
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="🔲 バーコード・QRコードリーダー",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        missing = []
        if not CV2_AVAILABLE:   missing.append("opencv-python")
        if not PYZBAR_AVAILABLE: missing.append("pyzbar")
        if not PIL_AVAILABLE:   missing.append("Pillow")
        if missing:
            tk.Label(self.root,
                     text=f"⚠ 必要ライブラリ: pip install {' '.join(missing)}",
                     bg="#fff3cd", fg="#856404", font=("Arial", 9),
                     anchor="w", padx=8).pack(fill=tk.X)

        # コントロール
        ctrl = tk.Frame(self.root, bg="#2d2d2d", pady=6)
        ctrl.pack(fill=tk.X)

        tk.Label(ctrl, text="カメラ:", bg="#2d2d2d", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.cam_var = tk.IntVar(value=0)
        ttk.Spinbox(ctrl, from_=0, to=9, textvariable=self.cam_var,
                    width=4).pack(side=tk.LEFT)
        tk.Button(ctrl, text="▶ カメラ起動", command=self._start_camera,
                  bg="#1565c0", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#0d47a1", bd=0).pack(side=tk.LEFT, padx=8)
        tk.Button(ctrl, text="⏹ 停止", command=self._stop_camera,
                  bg="#3c3c3c", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        ttk.Button(ctrl, text="📂 画像ファイルを読み込む",
                   command=self._from_file).pack(side=tk.LEFT, padx=8)
        ttk.Button(ctrl, text="🗑 履歴クリア",
                   command=self._clear).pack(side=tk.RIGHT, padx=8)

        # メインエリア
        main = tk.Frame(self.root, bg="#1e1e1e")
        main.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)

        # 左: カメラプレビュー
        left = tk.Frame(main, bg="#1e1e1e")
        left.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        tk.Label(left, text="カメラプレビュー", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.canvas = tk.Canvas(left, bg="#0d1117", width=480,
                                 highlightthickness=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)
        self._tk_img = None

        # 右: 読み取り結果
        right = tk.Frame(main, bg="#1e1e1e", width=300)
        right.pack(side=tk.LEFT, fill=tk.Y, padx=(8, 0))
        right.pack_propagate(False)
        tk.Label(right, text="読み取り結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")

        cols = ("type", "data")
        self.tree = ttk.Treeview(right, columns=cols, show="headings", height=18)
        self.tree.heading("type", text="種別")
        self.tree.heading("data", text="データ")
        self.tree.column("type", width=70,  anchor="center")
        self.tree.column("data", width=210, anchor="w")
        tsb = ttk.Scrollbar(right, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.bind("<<TreeviewSelect>>", self._on_select)

        # 詳細テキスト
        tk.Label(right, text="詳細", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        self.detail_text = tk.Text(right, height=4, bg="#0d1117", fg="#c9d1d9",
                                    font=("Arial", 9), relief=tk.FLAT,
                                    state=tk.DISABLED)
        self.detail_text.pack(fill=tk.X)

        self.status_var = tk.StringVar(value="カメラを起動するか画像ファイルを開いてください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── カメラ ──────────────────────────────────────────────
    def _start_camera(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE or not PIL_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar Pillow")
            return
        if self._running:
            return
        cap = cv2.VideoCapture(self.cam_var.get())
        if not cap.isOpened():
            messagebox.showerror("エラー", "カメラを開けませんでした")
            return
        self._cap = cap
        self._running = True
        self.status_var.set("カメラ起動中...")
        threading.Thread(target=self._camera_loop, daemon=True).start()

    def _stop_camera(self):
        self._running = False
        if self._cap:
            self._cap.release()
            self._cap = None
        self.status_var.set("停止")

    def _camera_loop(self):
        seen = set()
        while self._running and self._cap:
            ret, frame = self._cap.read()
            if not ret:
                break
            # デコード
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                code_type = obj.type
                key = (code_type, data)
                if key not in seen:
                    seen.add(key)
                    self.root.after(0, self._add_result, code_type, data)
                # 枠描画
                pts = obj.polygon
                if len(pts) == 4:
                    import numpy as np
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
                cv2.putText(frame, f"{code_type}: {data[:20]}",
                             (obj.rect.left, obj.rect.top - 10),
                             cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

            # 表示
            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(frame_rgb)
            self.canvas.update_idletasks()
            cw = max(1, self.canvas.winfo_width())
            ch = max(1, self.canvas.winfo_height())
            img.thumbnail((cw, ch), Image.NEAREST)
            tk_img = ImageTk.PhotoImage(img)
            self.root.after(0, self._update_canvas, tk_img)

    def _update_canvas(self, tk_img):
        self._tk_img = tk_img
        self.canvas.delete("all")
        cw = self.canvas.winfo_width()
        ch = self.canvas.winfo_height()
        self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")

    # ── ファイル読み込み ─────────────────────────────────────
    def _from_file(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar")
            return
        path = filedialog.askopenfilename(
            filetypes=[("画像", "*.png *.jpg *.jpeg *.bmp *.gif"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            frame = cv2.imread(path)
            if frame is None:
                messagebox.showerror("エラー", "画像を読み込めませんでした")
                return
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                self._add_result(obj.type, data)
                pts = obj.polygon
                if len(pts) == 4:
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
            # プレビュー表示
            if PIL_AVAILABLE:
                frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                img = Image.fromarray(frame_rgb)
                self.canvas.update_idletasks()
                cw = max(100, self.canvas.winfo_width())
                ch = max(100, self.canvas.winfo_height())
                img.thumbnail((cw, ch), Image.LANCZOS if hasattr(Image, "LANCZOS") else Image.ANTIALIAS)
                tk_img = ImageTk.PhotoImage(img)
                self._tk_img = tk_img
                self.canvas.delete("all")
                self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")
            count = len(decoded)
            self.status_var.set(f"読み取り完了: {count} 件検出")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _add_result(self, code_type, data):
        self._results.append((code_type, data))
        self.tree.insert("", tk.END, values=(code_type, data[:60]))
        self.tree.see(self.tree.get_children()[-1])
        self.status_var.set(f"検出: [{code_type}] {data[:40]}")

    def _on_select(self, _=None):
        sel = self.tree.selection()
        if not sel:
            return
        idx = self.tree.index(sel[0])
        if idx < len(self._results):
            code_type, data = self._results[idx]
            self.detail_text.configure(state=tk.NORMAL)
            self.detail_text.delete("1.0", tk.END)
            self.detail_text.insert("1.0", f"種別: {code_type}\n\n{data}")
            self.detail_text.configure(state=tk.DISABLED)

    def _clear(self):
        self._results.clear()
        self.tree.delete(*self.tree.get_children())
        self.detail_text.configure(state=tk.NORMAL)
        self.detail_text.delete("1.0", tk.END)
        self.detail_text.configure(state=tk.DISABLED)

    def _on_close(self):
        self._stop_camera()
        self.root.destroy()


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

5. コード解説

バーコードリーダーのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。

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

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

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

try:
    import cv2
    CV2_AVAILABLE = True
except ImportError:
    CV2_AVAILABLE = False

try:
    from pyzbar import pyzbar
    PYZBAR_AVAILABLE = True
except ImportError:
    PYZBAR_AVAILABLE = False

try:
    from PIL import Image, ImageTk
    PIL_AVAILABLE = True
except ImportError:
    PIL_AVAILABLE = False


class App076:
    """バーコード・QRコードリーダー"""

    def __init__(self, root):
        self.root = root
        self.root.title("バーコード・QRコードリーダー")
        self.root.geometry("860x580")
        self.root.configure(bg="#1e1e1e")
        self._cap = None
        self._running = False
        self._results = []
        self._build_ui()
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="🔲 バーコード・QRコードリーダー",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        missing = []
        if not CV2_AVAILABLE:   missing.append("opencv-python")
        if not PYZBAR_AVAILABLE: missing.append("pyzbar")
        if not PIL_AVAILABLE:   missing.append("Pillow")
        if missing:
            tk.Label(self.root,
                     text=f"⚠ 必要ライブラリ: pip install {' '.join(missing)}",
                     bg="#fff3cd", fg="#856404", font=("Arial", 9),
                     anchor="w", padx=8).pack(fill=tk.X)

        # コントロール
        ctrl = tk.Frame(self.root, bg="#2d2d2d", pady=6)
        ctrl.pack(fill=tk.X)

        tk.Label(ctrl, text="カメラ:", bg="#2d2d2d", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.cam_var = tk.IntVar(value=0)
        ttk.Spinbox(ctrl, from_=0, to=9, textvariable=self.cam_var,
                    width=4).pack(side=tk.LEFT)
        tk.Button(ctrl, text="▶ カメラ起動", command=self._start_camera,
                  bg="#1565c0", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#0d47a1", bd=0).pack(side=tk.LEFT, padx=8)
        tk.Button(ctrl, text="⏹ 停止", command=self._stop_camera,
                  bg="#3c3c3c", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        ttk.Button(ctrl, text="📂 画像ファイルを読み込む",
                   command=self._from_file).pack(side=tk.LEFT, padx=8)
        ttk.Button(ctrl, text="🗑 履歴クリア",
                   command=self._clear).pack(side=tk.RIGHT, padx=8)

        # メインエリア
        main = tk.Frame(self.root, bg="#1e1e1e")
        main.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)

        # 左: カメラプレビュー
        left = tk.Frame(main, bg="#1e1e1e")
        left.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        tk.Label(left, text="カメラプレビュー", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.canvas = tk.Canvas(left, bg="#0d1117", width=480,
                                 highlightthickness=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)
        self._tk_img = None

        # 右: 読み取り結果
        right = tk.Frame(main, bg="#1e1e1e", width=300)
        right.pack(side=tk.LEFT, fill=tk.Y, padx=(8, 0))
        right.pack_propagate(False)
        tk.Label(right, text="読み取り結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")

        cols = ("type", "data")
        self.tree = ttk.Treeview(right, columns=cols, show="headings", height=18)
        self.tree.heading("type", text="種別")
        self.tree.heading("data", text="データ")
        self.tree.column("type", width=70,  anchor="center")
        self.tree.column("data", width=210, anchor="w")
        tsb = ttk.Scrollbar(right, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.bind("<<TreeviewSelect>>", self._on_select)

        # 詳細テキスト
        tk.Label(right, text="詳細", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        self.detail_text = tk.Text(right, height=4, bg="#0d1117", fg="#c9d1d9",
                                    font=("Arial", 9), relief=tk.FLAT,
                                    state=tk.DISABLED)
        self.detail_text.pack(fill=tk.X)

        self.status_var = tk.StringVar(value="カメラを起動するか画像ファイルを開いてください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── カメラ ──────────────────────────────────────────────
    def _start_camera(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE or not PIL_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar Pillow")
            return
        if self._running:
            return
        cap = cv2.VideoCapture(self.cam_var.get())
        if not cap.isOpened():
            messagebox.showerror("エラー", "カメラを開けませんでした")
            return
        self._cap = cap
        self._running = True
        self.status_var.set("カメラ起動中...")
        threading.Thread(target=self._camera_loop, daemon=True).start()

    def _stop_camera(self):
        self._running = False
        if self._cap:
            self._cap.release()
            self._cap = None
        self.status_var.set("停止")

    def _camera_loop(self):
        seen = set()
        while self._running and self._cap:
            ret, frame = self._cap.read()
            if not ret:
                break
            # デコード
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                code_type = obj.type
                key = (code_type, data)
                if key not in seen:
                    seen.add(key)
                    self.root.after(0, self._add_result, code_type, data)
                # 枠描画
                pts = obj.polygon
                if len(pts) == 4:
                    import numpy as np
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
                cv2.putText(frame, f"{code_type}: {data[:20]}",
                             (obj.rect.left, obj.rect.top - 10),
                             cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

            # 表示
            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(frame_rgb)
            self.canvas.update_idletasks()
            cw = max(1, self.canvas.winfo_width())
            ch = max(1, self.canvas.winfo_height())
            img.thumbnail((cw, ch), Image.NEAREST)
            tk_img = ImageTk.PhotoImage(img)
            self.root.after(0, self._update_canvas, tk_img)

    def _update_canvas(self, tk_img):
        self._tk_img = tk_img
        self.canvas.delete("all")
        cw = self.canvas.winfo_width()
        ch = self.canvas.winfo_height()
        self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")

    # ── ファイル読み込み ─────────────────────────────────────
    def _from_file(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar")
            return
        path = filedialog.askopenfilename(
            filetypes=[("画像", "*.png *.jpg *.jpeg *.bmp *.gif"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            frame = cv2.imread(path)
            if frame is None:
                messagebox.showerror("エラー", "画像を読み込めませんでした")
                return
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                self._add_result(obj.type, data)
                pts = obj.polygon
                if len(pts) == 4:
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
            # プレビュー表示
            if PIL_AVAILABLE:
                frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                img = Image.fromarray(frame_rgb)
                self.canvas.update_idletasks()
                cw = max(100, self.canvas.winfo_width())
                ch = max(100, self.canvas.winfo_height())
                img.thumbnail((cw, ch), Image.LANCZOS if hasattr(Image, "LANCZOS") else Image.ANTIALIAS)
                tk_img = ImageTk.PhotoImage(img)
                self._tk_img = tk_img
                self.canvas.delete("all")
                self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")
            count = len(decoded)
            self.status_var.set(f"読み取り完了: {count} 件検出")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _add_result(self, code_type, data):
        self._results.append((code_type, data))
        self.tree.insert("", tk.END, values=(code_type, data[:60]))
        self.tree.see(self.tree.get_children()[-1])
        self.status_var.set(f"検出: [{code_type}] {data[:40]}")

    def _on_select(self, _=None):
        sel = self.tree.selection()
        if not sel:
            return
        idx = self.tree.index(sel[0])
        if idx < len(self._results):
            code_type, data = self._results[idx]
            self.detail_text.configure(state=tk.NORMAL)
            self.detail_text.delete("1.0", tk.END)
            self.detail_text.insert("1.0", f"種別: {code_type}\n\n{data}")
            self.detail_text.configure(state=tk.DISABLED)

    def _clear(self):
        self._results.clear()
        self.tree.delete(*self.tree.get_children())
        self.detail_text.configure(state=tk.NORMAL)
        self.detail_text.delete("1.0", tk.END)
        self.detail_text.configure(state=tk.DISABLED)

    def _on_close(self):
        self._stop_camera()
        self.root.destroy()


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

UIレイアウトの構築

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

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

try:
    import cv2
    CV2_AVAILABLE = True
except ImportError:
    CV2_AVAILABLE = False

try:
    from pyzbar import pyzbar
    PYZBAR_AVAILABLE = True
except ImportError:
    PYZBAR_AVAILABLE = False

try:
    from PIL import Image, ImageTk
    PIL_AVAILABLE = True
except ImportError:
    PIL_AVAILABLE = False


class App076:
    """バーコード・QRコードリーダー"""

    def __init__(self, root):
        self.root = root
        self.root.title("バーコード・QRコードリーダー")
        self.root.geometry("860x580")
        self.root.configure(bg="#1e1e1e")
        self._cap = None
        self._running = False
        self._results = []
        self._build_ui()
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="🔲 バーコード・QRコードリーダー",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        missing = []
        if not CV2_AVAILABLE:   missing.append("opencv-python")
        if not PYZBAR_AVAILABLE: missing.append("pyzbar")
        if not PIL_AVAILABLE:   missing.append("Pillow")
        if missing:
            tk.Label(self.root,
                     text=f"⚠ 必要ライブラリ: pip install {' '.join(missing)}",
                     bg="#fff3cd", fg="#856404", font=("Arial", 9),
                     anchor="w", padx=8).pack(fill=tk.X)

        # コントロール
        ctrl = tk.Frame(self.root, bg="#2d2d2d", pady=6)
        ctrl.pack(fill=tk.X)

        tk.Label(ctrl, text="カメラ:", bg="#2d2d2d", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.cam_var = tk.IntVar(value=0)
        ttk.Spinbox(ctrl, from_=0, to=9, textvariable=self.cam_var,
                    width=4).pack(side=tk.LEFT)
        tk.Button(ctrl, text="▶ カメラ起動", command=self._start_camera,
                  bg="#1565c0", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#0d47a1", bd=0).pack(side=tk.LEFT, padx=8)
        tk.Button(ctrl, text="⏹ 停止", command=self._stop_camera,
                  bg="#3c3c3c", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        ttk.Button(ctrl, text="📂 画像ファイルを読み込む",
                   command=self._from_file).pack(side=tk.LEFT, padx=8)
        ttk.Button(ctrl, text="🗑 履歴クリア",
                   command=self._clear).pack(side=tk.RIGHT, padx=8)

        # メインエリア
        main = tk.Frame(self.root, bg="#1e1e1e")
        main.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)

        # 左: カメラプレビュー
        left = tk.Frame(main, bg="#1e1e1e")
        left.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        tk.Label(left, text="カメラプレビュー", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.canvas = tk.Canvas(left, bg="#0d1117", width=480,
                                 highlightthickness=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)
        self._tk_img = None

        # 右: 読み取り結果
        right = tk.Frame(main, bg="#1e1e1e", width=300)
        right.pack(side=tk.LEFT, fill=tk.Y, padx=(8, 0))
        right.pack_propagate(False)
        tk.Label(right, text="読み取り結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")

        cols = ("type", "data")
        self.tree = ttk.Treeview(right, columns=cols, show="headings", height=18)
        self.tree.heading("type", text="種別")
        self.tree.heading("data", text="データ")
        self.tree.column("type", width=70,  anchor="center")
        self.tree.column("data", width=210, anchor="w")
        tsb = ttk.Scrollbar(right, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.bind("<<TreeviewSelect>>", self._on_select)

        # 詳細テキスト
        tk.Label(right, text="詳細", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        self.detail_text = tk.Text(right, height=4, bg="#0d1117", fg="#c9d1d9",
                                    font=("Arial", 9), relief=tk.FLAT,
                                    state=tk.DISABLED)
        self.detail_text.pack(fill=tk.X)

        self.status_var = tk.StringVar(value="カメラを起動するか画像ファイルを開いてください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── カメラ ──────────────────────────────────────────────
    def _start_camera(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE or not PIL_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar Pillow")
            return
        if self._running:
            return
        cap = cv2.VideoCapture(self.cam_var.get())
        if not cap.isOpened():
            messagebox.showerror("エラー", "カメラを開けませんでした")
            return
        self._cap = cap
        self._running = True
        self.status_var.set("カメラ起動中...")
        threading.Thread(target=self._camera_loop, daemon=True).start()

    def _stop_camera(self):
        self._running = False
        if self._cap:
            self._cap.release()
            self._cap = None
        self.status_var.set("停止")

    def _camera_loop(self):
        seen = set()
        while self._running and self._cap:
            ret, frame = self._cap.read()
            if not ret:
                break
            # デコード
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                code_type = obj.type
                key = (code_type, data)
                if key not in seen:
                    seen.add(key)
                    self.root.after(0, self._add_result, code_type, data)
                # 枠描画
                pts = obj.polygon
                if len(pts) == 4:
                    import numpy as np
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
                cv2.putText(frame, f"{code_type}: {data[:20]}",
                             (obj.rect.left, obj.rect.top - 10),
                             cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

            # 表示
            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(frame_rgb)
            self.canvas.update_idletasks()
            cw = max(1, self.canvas.winfo_width())
            ch = max(1, self.canvas.winfo_height())
            img.thumbnail((cw, ch), Image.NEAREST)
            tk_img = ImageTk.PhotoImage(img)
            self.root.after(0, self._update_canvas, tk_img)

    def _update_canvas(self, tk_img):
        self._tk_img = tk_img
        self.canvas.delete("all")
        cw = self.canvas.winfo_width()
        ch = self.canvas.winfo_height()
        self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")

    # ── ファイル読み込み ─────────────────────────────────────
    def _from_file(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar")
            return
        path = filedialog.askopenfilename(
            filetypes=[("画像", "*.png *.jpg *.jpeg *.bmp *.gif"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            frame = cv2.imread(path)
            if frame is None:
                messagebox.showerror("エラー", "画像を読み込めませんでした")
                return
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                self._add_result(obj.type, data)
                pts = obj.polygon
                if len(pts) == 4:
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
            # プレビュー表示
            if PIL_AVAILABLE:
                frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                img = Image.fromarray(frame_rgb)
                self.canvas.update_idletasks()
                cw = max(100, self.canvas.winfo_width())
                ch = max(100, self.canvas.winfo_height())
                img.thumbnail((cw, ch), Image.LANCZOS if hasattr(Image, "LANCZOS") else Image.ANTIALIAS)
                tk_img = ImageTk.PhotoImage(img)
                self._tk_img = tk_img
                self.canvas.delete("all")
                self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")
            count = len(decoded)
            self.status_var.set(f"読み取り完了: {count} 件検出")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _add_result(self, code_type, data):
        self._results.append((code_type, data))
        self.tree.insert("", tk.END, values=(code_type, data[:60]))
        self.tree.see(self.tree.get_children()[-1])
        self.status_var.set(f"検出: [{code_type}] {data[:40]}")

    def _on_select(self, _=None):
        sel = self.tree.selection()
        if not sel:
            return
        idx = self.tree.index(sel[0])
        if idx < len(self._results):
            code_type, data = self._results[idx]
            self.detail_text.configure(state=tk.NORMAL)
            self.detail_text.delete("1.0", tk.END)
            self.detail_text.insert("1.0", f"種別: {code_type}\n\n{data}")
            self.detail_text.configure(state=tk.DISABLED)

    def _clear(self):
        self._results.clear()
        self.tree.delete(*self.tree.get_children())
        self.detail_text.configure(state=tk.NORMAL)
        self.detail_text.delete("1.0", tk.END)
        self.detail_text.configure(state=tk.DISABLED)

    def _on_close(self):
        self._stop_camera()
        self.root.destroy()


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

イベント処理

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

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

try:
    import cv2
    CV2_AVAILABLE = True
except ImportError:
    CV2_AVAILABLE = False

try:
    from pyzbar import pyzbar
    PYZBAR_AVAILABLE = True
except ImportError:
    PYZBAR_AVAILABLE = False

try:
    from PIL import Image, ImageTk
    PIL_AVAILABLE = True
except ImportError:
    PIL_AVAILABLE = False


class App076:
    """バーコード・QRコードリーダー"""

    def __init__(self, root):
        self.root = root
        self.root.title("バーコード・QRコードリーダー")
        self.root.geometry("860x580")
        self.root.configure(bg="#1e1e1e")
        self._cap = None
        self._running = False
        self._results = []
        self._build_ui()
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="🔲 バーコード・QRコードリーダー",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        missing = []
        if not CV2_AVAILABLE:   missing.append("opencv-python")
        if not PYZBAR_AVAILABLE: missing.append("pyzbar")
        if not PIL_AVAILABLE:   missing.append("Pillow")
        if missing:
            tk.Label(self.root,
                     text=f"⚠ 必要ライブラリ: pip install {' '.join(missing)}",
                     bg="#fff3cd", fg="#856404", font=("Arial", 9),
                     anchor="w", padx=8).pack(fill=tk.X)

        # コントロール
        ctrl = tk.Frame(self.root, bg="#2d2d2d", pady=6)
        ctrl.pack(fill=tk.X)

        tk.Label(ctrl, text="カメラ:", bg="#2d2d2d", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.cam_var = tk.IntVar(value=0)
        ttk.Spinbox(ctrl, from_=0, to=9, textvariable=self.cam_var,
                    width=4).pack(side=tk.LEFT)
        tk.Button(ctrl, text="▶ カメラ起動", command=self._start_camera,
                  bg="#1565c0", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#0d47a1", bd=0).pack(side=tk.LEFT, padx=8)
        tk.Button(ctrl, text="⏹ 停止", command=self._stop_camera,
                  bg="#3c3c3c", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        ttk.Button(ctrl, text="📂 画像ファイルを読み込む",
                   command=self._from_file).pack(side=tk.LEFT, padx=8)
        ttk.Button(ctrl, text="🗑 履歴クリア",
                   command=self._clear).pack(side=tk.RIGHT, padx=8)

        # メインエリア
        main = tk.Frame(self.root, bg="#1e1e1e")
        main.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)

        # 左: カメラプレビュー
        left = tk.Frame(main, bg="#1e1e1e")
        left.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        tk.Label(left, text="カメラプレビュー", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.canvas = tk.Canvas(left, bg="#0d1117", width=480,
                                 highlightthickness=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)
        self._tk_img = None

        # 右: 読み取り結果
        right = tk.Frame(main, bg="#1e1e1e", width=300)
        right.pack(side=tk.LEFT, fill=tk.Y, padx=(8, 0))
        right.pack_propagate(False)
        tk.Label(right, text="読み取り結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")

        cols = ("type", "data")
        self.tree = ttk.Treeview(right, columns=cols, show="headings", height=18)
        self.tree.heading("type", text="種別")
        self.tree.heading("data", text="データ")
        self.tree.column("type", width=70,  anchor="center")
        self.tree.column("data", width=210, anchor="w")
        tsb = ttk.Scrollbar(right, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.bind("<<TreeviewSelect>>", self._on_select)

        # 詳細テキスト
        tk.Label(right, text="詳細", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        self.detail_text = tk.Text(right, height=4, bg="#0d1117", fg="#c9d1d9",
                                    font=("Arial", 9), relief=tk.FLAT,
                                    state=tk.DISABLED)
        self.detail_text.pack(fill=tk.X)

        self.status_var = tk.StringVar(value="カメラを起動するか画像ファイルを開いてください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── カメラ ──────────────────────────────────────────────
    def _start_camera(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE or not PIL_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar Pillow")
            return
        if self._running:
            return
        cap = cv2.VideoCapture(self.cam_var.get())
        if not cap.isOpened():
            messagebox.showerror("エラー", "カメラを開けませんでした")
            return
        self._cap = cap
        self._running = True
        self.status_var.set("カメラ起動中...")
        threading.Thread(target=self._camera_loop, daemon=True).start()

    def _stop_camera(self):
        self._running = False
        if self._cap:
            self._cap.release()
            self._cap = None
        self.status_var.set("停止")

    def _camera_loop(self):
        seen = set()
        while self._running and self._cap:
            ret, frame = self._cap.read()
            if not ret:
                break
            # デコード
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                code_type = obj.type
                key = (code_type, data)
                if key not in seen:
                    seen.add(key)
                    self.root.after(0, self._add_result, code_type, data)
                # 枠描画
                pts = obj.polygon
                if len(pts) == 4:
                    import numpy as np
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
                cv2.putText(frame, f"{code_type}: {data[:20]}",
                             (obj.rect.left, obj.rect.top - 10),
                             cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

            # 表示
            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(frame_rgb)
            self.canvas.update_idletasks()
            cw = max(1, self.canvas.winfo_width())
            ch = max(1, self.canvas.winfo_height())
            img.thumbnail((cw, ch), Image.NEAREST)
            tk_img = ImageTk.PhotoImage(img)
            self.root.after(0, self._update_canvas, tk_img)

    def _update_canvas(self, tk_img):
        self._tk_img = tk_img
        self.canvas.delete("all")
        cw = self.canvas.winfo_width()
        ch = self.canvas.winfo_height()
        self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")

    # ── ファイル読み込み ─────────────────────────────────────
    def _from_file(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar")
            return
        path = filedialog.askopenfilename(
            filetypes=[("画像", "*.png *.jpg *.jpeg *.bmp *.gif"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            frame = cv2.imread(path)
            if frame is None:
                messagebox.showerror("エラー", "画像を読み込めませんでした")
                return
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                self._add_result(obj.type, data)
                pts = obj.polygon
                if len(pts) == 4:
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
            # プレビュー表示
            if PIL_AVAILABLE:
                frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                img = Image.fromarray(frame_rgb)
                self.canvas.update_idletasks()
                cw = max(100, self.canvas.winfo_width())
                ch = max(100, self.canvas.winfo_height())
                img.thumbnail((cw, ch), Image.LANCZOS if hasattr(Image, "LANCZOS") else Image.ANTIALIAS)
                tk_img = ImageTk.PhotoImage(img)
                self._tk_img = tk_img
                self.canvas.delete("all")
                self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")
            count = len(decoded)
            self.status_var.set(f"読み取り完了: {count} 件検出")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _add_result(self, code_type, data):
        self._results.append((code_type, data))
        self.tree.insert("", tk.END, values=(code_type, data[:60]))
        self.tree.see(self.tree.get_children()[-1])
        self.status_var.set(f"検出: [{code_type}] {data[:40]}")

    def _on_select(self, _=None):
        sel = self.tree.selection()
        if not sel:
            return
        idx = self.tree.index(sel[0])
        if idx < len(self._results):
            code_type, data = self._results[idx]
            self.detail_text.configure(state=tk.NORMAL)
            self.detail_text.delete("1.0", tk.END)
            self.detail_text.insert("1.0", f"種別: {code_type}\n\n{data}")
            self.detail_text.configure(state=tk.DISABLED)

    def _clear(self):
        self._results.clear()
        self.tree.delete(*self.tree.get_children())
        self.detail_text.configure(state=tk.NORMAL)
        self.detail_text.delete("1.0", tk.END)
        self.detail_text.configure(state=tk.DISABLED)

    def _on_close(self):
        self._stop_camera()
        self.root.destroy()


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

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

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

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

try:
    import cv2
    CV2_AVAILABLE = True
except ImportError:
    CV2_AVAILABLE = False

try:
    from pyzbar import pyzbar
    PYZBAR_AVAILABLE = True
except ImportError:
    PYZBAR_AVAILABLE = False

try:
    from PIL import Image, ImageTk
    PIL_AVAILABLE = True
except ImportError:
    PIL_AVAILABLE = False


class App076:
    """バーコード・QRコードリーダー"""

    def __init__(self, root):
        self.root = root
        self.root.title("バーコード・QRコードリーダー")
        self.root.geometry("860x580")
        self.root.configure(bg="#1e1e1e")
        self._cap = None
        self._running = False
        self._results = []
        self._build_ui()
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="🔲 バーコード・QRコードリーダー",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        missing = []
        if not CV2_AVAILABLE:   missing.append("opencv-python")
        if not PYZBAR_AVAILABLE: missing.append("pyzbar")
        if not PIL_AVAILABLE:   missing.append("Pillow")
        if missing:
            tk.Label(self.root,
                     text=f"⚠ 必要ライブラリ: pip install {' '.join(missing)}",
                     bg="#fff3cd", fg="#856404", font=("Arial", 9),
                     anchor="w", padx=8).pack(fill=tk.X)

        # コントロール
        ctrl = tk.Frame(self.root, bg="#2d2d2d", pady=6)
        ctrl.pack(fill=tk.X)

        tk.Label(ctrl, text="カメラ:", bg="#2d2d2d", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.cam_var = tk.IntVar(value=0)
        ttk.Spinbox(ctrl, from_=0, to=9, textvariable=self.cam_var,
                    width=4).pack(side=tk.LEFT)
        tk.Button(ctrl, text="▶ カメラ起動", command=self._start_camera,
                  bg="#1565c0", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#0d47a1", bd=0).pack(side=tk.LEFT, padx=8)
        tk.Button(ctrl, text="⏹ 停止", command=self._stop_camera,
                  bg="#3c3c3c", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        ttk.Button(ctrl, text="📂 画像ファイルを読み込む",
                   command=self._from_file).pack(side=tk.LEFT, padx=8)
        ttk.Button(ctrl, text="🗑 履歴クリア",
                   command=self._clear).pack(side=tk.RIGHT, padx=8)

        # メインエリア
        main = tk.Frame(self.root, bg="#1e1e1e")
        main.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)

        # 左: カメラプレビュー
        left = tk.Frame(main, bg="#1e1e1e")
        left.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        tk.Label(left, text="カメラプレビュー", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.canvas = tk.Canvas(left, bg="#0d1117", width=480,
                                 highlightthickness=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)
        self._tk_img = None

        # 右: 読み取り結果
        right = tk.Frame(main, bg="#1e1e1e", width=300)
        right.pack(side=tk.LEFT, fill=tk.Y, padx=(8, 0))
        right.pack_propagate(False)
        tk.Label(right, text="読み取り結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")

        cols = ("type", "data")
        self.tree = ttk.Treeview(right, columns=cols, show="headings", height=18)
        self.tree.heading("type", text="種別")
        self.tree.heading("data", text="データ")
        self.tree.column("type", width=70,  anchor="center")
        self.tree.column("data", width=210, anchor="w")
        tsb = ttk.Scrollbar(right, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.bind("<<TreeviewSelect>>", self._on_select)

        # 詳細テキスト
        tk.Label(right, text="詳細", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        self.detail_text = tk.Text(right, height=4, bg="#0d1117", fg="#c9d1d9",
                                    font=("Arial", 9), relief=tk.FLAT,
                                    state=tk.DISABLED)
        self.detail_text.pack(fill=tk.X)

        self.status_var = tk.StringVar(value="カメラを起動するか画像ファイルを開いてください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── カメラ ──────────────────────────────────────────────
    def _start_camera(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE or not PIL_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar Pillow")
            return
        if self._running:
            return
        cap = cv2.VideoCapture(self.cam_var.get())
        if not cap.isOpened():
            messagebox.showerror("エラー", "カメラを開けませんでした")
            return
        self._cap = cap
        self._running = True
        self.status_var.set("カメラ起動中...")
        threading.Thread(target=self._camera_loop, daemon=True).start()

    def _stop_camera(self):
        self._running = False
        if self._cap:
            self._cap.release()
            self._cap = None
        self.status_var.set("停止")

    def _camera_loop(self):
        seen = set()
        while self._running and self._cap:
            ret, frame = self._cap.read()
            if not ret:
                break
            # デコード
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                code_type = obj.type
                key = (code_type, data)
                if key not in seen:
                    seen.add(key)
                    self.root.after(0, self._add_result, code_type, data)
                # 枠描画
                pts = obj.polygon
                if len(pts) == 4:
                    import numpy as np
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
                cv2.putText(frame, f"{code_type}: {data[:20]}",
                             (obj.rect.left, obj.rect.top - 10),
                             cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

            # 表示
            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(frame_rgb)
            self.canvas.update_idletasks()
            cw = max(1, self.canvas.winfo_width())
            ch = max(1, self.canvas.winfo_height())
            img.thumbnail((cw, ch), Image.NEAREST)
            tk_img = ImageTk.PhotoImage(img)
            self.root.after(0, self._update_canvas, tk_img)

    def _update_canvas(self, tk_img):
        self._tk_img = tk_img
        self.canvas.delete("all")
        cw = self.canvas.winfo_width()
        ch = self.canvas.winfo_height()
        self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")

    # ── ファイル読み込み ─────────────────────────────────────
    def _from_file(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar")
            return
        path = filedialog.askopenfilename(
            filetypes=[("画像", "*.png *.jpg *.jpeg *.bmp *.gif"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            frame = cv2.imread(path)
            if frame is None:
                messagebox.showerror("エラー", "画像を読み込めませんでした")
                return
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                self._add_result(obj.type, data)
                pts = obj.polygon
                if len(pts) == 4:
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
            # プレビュー表示
            if PIL_AVAILABLE:
                frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                img = Image.fromarray(frame_rgb)
                self.canvas.update_idletasks()
                cw = max(100, self.canvas.winfo_width())
                ch = max(100, self.canvas.winfo_height())
                img.thumbnail((cw, ch), Image.LANCZOS if hasattr(Image, "LANCZOS") else Image.ANTIALIAS)
                tk_img = ImageTk.PhotoImage(img)
                self._tk_img = tk_img
                self.canvas.delete("all")
                self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")
            count = len(decoded)
            self.status_var.set(f"読み取り完了: {count} 件検出")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _add_result(self, code_type, data):
        self._results.append((code_type, data))
        self.tree.insert("", tk.END, values=(code_type, data[:60]))
        self.tree.see(self.tree.get_children()[-1])
        self.status_var.set(f"検出: [{code_type}] {data[:40]}")

    def _on_select(self, _=None):
        sel = self.tree.selection()
        if not sel:
            return
        idx = self.tree.index(sel[0])
        if idx < len(self._results):
            code_type, data = self._results[idx]
            self.detail_text.configure(state=tk.NORMAL)
            self.detail_text.delete("1.0", tk.END)
            self.detail_text.insert("1.0", f"種別: {code_type}\n\n{data}")
            self.detail_text.configure(state=tk.DISABLED)

    def _clear(self):
        self._results.clear()
        self.tree.delete(*self.tree.get_children())
        self.detail_text.configure(state=tk.NORMAL)
        self.detail_text.delete("1.0", tk.END)
        self.detail_text.configure(state=tk.DISABLED)

    def _on_close(self):
        self._stop_camera()
        self.root.destroy()


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

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

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

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

try:
    import cv2
    CV2_AVAILABLE = True
except ImportError:
    CV2_AVAILABLE = False

try:
    from pyzbar import pyzbar
    PYZBAR_AVAILABLE = True
except ImportError:
    PYZBAR_AVAILABLE = False

try:
    from PIL import Image, ImageTk
    PIL_AVAILABLE = True
except ImportError:
    PIL_AVAILABLE = False


class App076:
    """バーコード・QRコードリーダー"""

    def __init__(self, root):
        self.root = root
        self.root.title("バーコード・QRコードリーダー")
        self.root.geometry("860x580")
        self.root.configure(bg="#1e1e1e")
        self._cap = None
        self._running = False
        self._results = []
        self._build_ui()
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)

    def _build_ui(self):
        header = tk.Frame(self.root, bg="#252526", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="🔲 バーコード・QRコードリーダー",
                 font=("Noto Sans JP", 12, "bold"),
                 bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)

        missing = []
        if not CV2_AVAILABLE:   missing.append("opencv-python")
        if not PYZBAR_AVAILABLE: missing.append("pyzbar")
        if not PIL_AVAILABLE:   missing.append("Pillow")
        if missing:
            tk.Label(self.root,
                     text=f"⚠ 必要ライブラリ: pip install {' '.join(missing)}",
                     bg="#fff3cd", fg="#856404", font=("Arial", 9),
                     anchor="w", padx=8).pack(fill=tk.X)

        # コントロール
        ctrl = tk.Frame(self.root, bg="#2d2d2d", pady=6)
        ctrl.pack(fill=tk.X)

        tk.Label(ctrl, text="カメラ:", bg="#2d2d2d", fg="#ccc",
                 font=("Arial", 9)).pack(side=tk.LEFT, padx=4)
        self.cam_var = tk.IntVar(value=0)
        ttk.Spinbox(ctrl, from_=0, to=9, textvariable=self.cam_var,
                    width=4).pack(side=tk.LEFT)
        tk.Button(ctrl, text="▶ カメラ起動", command=self._start_camera,
                  bg="#1565c0", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#0d47a1", bd=0).pack(side=tk.LEFT, padx=8)
        tk.Button(ctrl, text="⏹ 停止", command=self._stop_camera,
                  bg="#3c3c3c", fg="white", relief=tk.FLAT,
                  font=("Arial", 11), padx=12, pady=4,
                  activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
        ttk.Button(ctrl, text="📂 画像ファイルを読み込む",
                   command=self._from_file).pack(side=tk.LEFT, padx=8)
        ttk.Button(ctrl, text="🗑 履歴クリア",
                   command=self._clear).pack(side=tk.RIGHT, padx=8)

        # メインエリア
        main = tk.Frame(self.root, bg="#1e1e1e")
        main.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)

        # 左: カメラプレビュー
        left = tk.Frame(main, bg="#1e1e1e")
        left.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        tk.Label(left, text="カメラプレビュー", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")
        self.canvas = tk.Canvas(left, bg="#0d1117", width=480,
                                 highlightthickness=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)
        self._tk_img = None

        # 右: 読み取り結果
        right = tk.Frame(main, bg="#1e1e1e", width=300)
        right.pack(side=tk.LEFT, fill=tk.Y, padx=(8, 0))
        right.pack_propagate(False)
        tk.Label(right, text="読み取り結果", bg="#1e1e1e", fg="#888",
                 font=("Arial", 9)).pack(anchor="w")

        cols = ("type", "data")
        self.tree = ttk.Treeview(right, columns=cols, show="headings", height=18)
        self.tree.heading("type", text="種別")
        self.tree.heading("data", text="データ")
        self.tree.column("type", width=70,  anchor="center")
        self.tree.column("data", width=210, anchor="w")
        tsb = ttk.Scrollbar(right, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tsb.set)
        tsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree.bind("<<TreeviewSelect>>", self._on_select)

        # 詳細テキスト
        tk.Label(right, text="詳細", bg="#1e1e1e", fg="#888",
                 font=("Arial", 8)).pack(anchor="w")
        self.detail_text = tk.Text(right, height=4, bg="#0d1117", fg="#c9d1d9",
                                    font=("Arial", 9), relief=tk.FLAT,
                                    state=tk.DISABLED)
        self.detail_text.pack(fill=tk.X)

        self.status_var = tk.StringVar(value="カメラを起動するか画像ファイルを開いてください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#252526", fg="#858585", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    # ── カメラ ──────────────────────────────────────────────
    def _start_camera(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE or not PIL_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar Pillow")
            return
        if self._running:
            return
        cap = cv2.VideoCapture(self.cam_var.get())
        if not cap.isOpened():
            messagebox.showerror("エラー", "カメラを開けませんでした")
            return
        self._cap = cap
        self._running = True
        self.status_var.set("カメラ起動中...")
        threading.Thread(target=self._camera_loop, daemon=True).start()

    def _stop_camera(self):
        self._running = False
        if self._cap:
            self._cap.release()
            self._cap = None
        self.status_var.set("停止")

    def _camera_loop(self):
        seen = set()
        while self._running and self._cap:
            ret, frame = self._cap.read()
            if not ret:
                break
            # デコード
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                code_type = obj.type
                key = (code_type, data)
                if key not in seen:
                    seen.add(key)
                    self.root.after(0, self._add_result, code_type, data)
                # 枠描画
                pts = obj.polygon
                if len(pts) == 4:
                    import numpy as np
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
                cv2.putText(frame, f"{code_type}: {data[:20]}",
                             (obj.rect.left, obj.rect.top - 10),
                             cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

            # 表示
            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(frame_rgb)
            self.canvas.update_idletasks()
            cw = max(1, self.canvas.winfo_width())
            ch = max(1, self.canvas.winfo_height())
            img.thumbnail((cw, ch), Image.NEAREST)
            tk_img = ImageTk.PhotoImage(img)
            self.root.after(0, self._update_canvas, tk_img)

    def _update_canvas(self, tk_img):
        self._tk_img = tk_img
        self.canvas.delete("all")
        cw = self.canvas.winfo_width()
        ch = self.canvas.winfo_height()
        self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")

    # ── ファイル読み込み ─────────────────────────────────────
    def _from_file(self):
        if not CV2_AVAILABLE or not PYZBAR_AVAILABLE:
            messagebox.showerror("エラー", "pip install opencv-python pyzbar")
            return
        path = filedialog.askopenfilename(
            filetypes=[("画像", "*.png *.jpg *.jpeg *.bmp *.gif"),
                       ("すべて", "*.*")])
        if not path:
            return
        try:
            frame = cv2.imread(path)
            if frame is None:
                messagebox.showerror("エラー", "画像を読み込めませんでした")
                return
            decoded = pyzbar.decode(frame)
            for obj in decoded:
                data = obj.data.decode("utf-8", errors="replace")
                self._add_result(obj.type, data)
                pts = obj.polygon
                if len(pts) == 4:
                    pts_arr = [(p.x, p.y) for p in pts]
                    for i in range(4):
                        cv2.line(frame, pts_arr[i], pts_arr[(i+1)%4],
                                  (0, 255, 0), 2)
            # プレビュー表示
            if PIL_AVAILABLE:
                frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                img = Image.fromarray(frame_rgb)
                self.canvas.update_idletasks()
                cw = max(100, self.canvas.winfo_width())
                ch = max(100, self.canvas.winfo_height())
                img.thumbnail((cw, ch), Image.LANCZOS if hasattr(Image, "LANCZOS") else Image.ANTIALIAS)
                tk_img = ImageTk.PhotoImage(img)
                self._tk_img = tk_img
                self.canvas.delete("all")
                self.canvas.create_image(cw//2, ch//2, image=tk_img, anchor="center")
            count = len(decoded)
            self.status_var.set(f"読み取り完了: {count} 件検出")
        except Exception as e:
            messagebox.showerror("エラー", str(e))

    def _add_result(self, code_type, data):
        self._results.append((code_type, data))
        self.tree.insert("", tk.END, values=(code_type, data[:60]))
        self.tree.see(self.tree.get_children()[-1])
        self.status_var.set(f"検出: [{code_type}] {data[:40]}")

    def _on_select(self, _=None):
        sel = self.tree.selection()
        if not sel:
            return
        idx = self.tree.index(sel[0])
        if idx < len(self._results):
            code_type, data = self._results[idx]
            self.detail_text.configure(state=tk.NORMAL)
            self.detail_text.delete("1.0", tk.END)
            self.detail_text.insert("1.0", f"種別: {code_type}\n\n{data}")
            self.detail_text.configure(state=tk.DISABLED)

    def _clear(self):
        self._results.clear()
        self.tree.delete(*self.tree.get_children())
        self.detail_text.configure(state=tk.NORMAL)
        self.detail_text.delete("1.0", tk.END)
        self.detail_text.configure(state=tk.DISABLED)

    def _on_close(self):
        self._stop_camera()
        self.root.destroy()


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

💡 データの保存機能

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

💡 設定ダイアログ

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

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

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

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

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

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

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

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

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

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

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

9. 練習問題

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

  1. 課題1:機能拡張

    バーコードリーダーに新しい機能を1つ追加してみましょう。

  2. 課題2:UIの改善

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

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

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

🚀
次に挑戦するアプリ

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