スクリーンショットツール
範囲選択・全画面・ウィンドウキャプチャができるスクリーンショットツール。pyscreenshotとPillowの活用を学びます。
1. アプリ概要
範囲選択・全画面・ウィンドウキャプチャができるスクリーンショットツール。pyscreenshotとPillowの活用を学びます。
このアプリは中級カテゴリに分類される実践的なGUIアプリです。使用ライブラリは tkinter(標準ライブラリ)・Pillow・pyscreenshot で、難易度は ★★☆ です。
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+
インストールが必要なライブラリ
pip install pillow
4. 完全なソースコード
右上の「コピー」ボタンをクリックするとコードをクリップボードにコピーできます。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import threading
import time
from datetime import datetime
try:
from PIL import Image, ImageTk, ImageGrab
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
try:
import pyscreenshot as ImageGrabExt
PYSCREENSHOT_AVAILABLE = True
except ImportError:
PYSCREENSHOT_AVAILABLE = False
class App31:
"""スクリーンショットツール"""
def __init__(self, root):
self.root = root
self.root.title("スクリーンショットツール")
self.root.geometry("820x620")
self.root.configure(bg="#1e1e1e")
self._screenshots = []
self._current_img = None
self._tk_img = None
self._build_ui()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#252526", pady=8)
header.pack(fill=tk.X)
tk.Label(header, text="📸 スクリーンショットツール",
font=("Noto Sans JP", 13, "bold"),
bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PIL_AVAILABLE:
tk.Label(self.root,
text="⚠ Pillow が未インストールです (pip install Pillow)。",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# ツールバー
toolbar = tk.Frame(self.root, bg="#2d2d30", pady=6)
toolbar.pack(fill=tk.X)
btn_s = {"bg": "#3c3c3c", "fg": "white", "relief": tk.FLAT,
"font": ("Arial", 10), "padx": 12, "pady=4",
"activebackground": "#505050", "bd": 0}
tk.Button(toolbar, text="📸 全画面",
command=self._capture_fullscreen,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="⏱ 遅延撮影 (3秒)",
command=self._capture_delayed,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="🖼 ファイルを開く",
command=self._open_image,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
# 遅延秒数
tk.Label(toolbar, text="遅延:", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 2))
self.delay_var = tk.IntVar(value=3)
ttk.Spinbox(toolbar, from_=1, to=30, textvariable=self.delay_var,
width=4).pack(side=tk.LEFT)
tk.Label(toolbar, text="秒", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=2)
tk.Button(toolbar, text="💾 保存",
command=self._save_image,
bg="#0288d1", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#0277bd", bd=0).pack(side=tk.RIGHT, padx=8)
tk.Button(toolbar, text="🗑 削除",
command=self._delete_selected,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#b71c1c", bd=0).pack(side=tk.RIGHT, padx=4)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: サムネイルリスト
left = tk.Frame(paned, bg="#252526")
paned.add(left, weight=1)
tk.Label(left, text="キャプチャ一覧", bg="#252526", fg="#858585",
font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
self.thumb_listbox = tk.Listbox(left, bg="#1e1e1e", fg="#c9d1d9",
font=("Arial", 10), selectmode=tk.SINGLE,
activestyle="none")
sb = ttk.Scrollbar(left, command=self.thumb_listbox.yview)
self.thumb_listbox.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.thumb_listbox.pack(fill=tk.BOTH, expand=True)
self.thumb_listbox.bind("<<ListboxSelect>>", self._on_select)
# 右: プレビュー
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=4)
# 画像情報
self.info_var = tk.StringVar(value="")
tk.Label(right, textvariable=self.info_var, bg="#0d1117",
fg="#8b949e", font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
# キャンバス (スクロール)
canvas_f = tk.Frame(right, bg="#0d1117")
canvas_f.pack(fill=tk.BOTH, expand=True)
h_sb = ttk.Scrollbar(canvas_f, orient=tk.HORIZONTAL)
v_sb = ttk.Scrollbar(canvas_f, orient=tk.VERTICAL)
self.canvas = tk.Canvas(canvas_f, bg="#0d1117", highlightthickness=0,
xscrollcommand=h_sb.set,
yscrollcommand=v_sb.set)
h_sb.configure(command=self.canvas.xview)
v_sb.configure(command=self.canvas.yview)
v_sb.pack(side=tk.RIGHT, fill=tk.Y)
h_sb.pack(side=tk.BOTTOM, fill=tk.X)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas_img_id = None
# ズーム
zoom_f = tk.Frame(right, bg="#252526")
zoom_f.pack(fill=tk.X)
tk.Label(zoom_f, text="ズーム:", bg="#252526", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=6)
self.zoom_var = tk.DoubleVar(value=1.0)
zoom_scale = ttk.Scale(zoom_f, from_=0.1, to=3.0,
variable=self.zoom_var, orient=tk.HORIZONTAL,
length=200, command=lambda v: self._update_canvas())
zoom_scale.pack(side=tk.LEFT, padx=4)
self.zoom_label = tk.Label(zoom_f, text="100%", bg="#252526", fg="#ccc",
font=("Arial", 9))
self.zoom_label.pack(side=tk.LEFT, padx=4)
# 編集ボタン
edit_f = tk.Frame(right, bg="#252526")
edit_f.pack(fill=tk.X, pady=2)
for text, cmd in [("↻ 90°回転", self._rotate),
("↔ 左右反転", self._flip_h),
("↕ 上下反転", self._flip_v),
("⬛ グレー", self._grayscale)]:
tk.Button(edit_f, text=text, command=cmd,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=8, pady=2,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
# ステータスバー
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 _capture_fullscreen(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
self.status_var.set("キャプチャ中...")
threading.Thread(target=self._do_capture, daemon=True).start()
def _capture_delayed(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
delay = self.delay_var.get()
self.status_var.set(f"{delay}秒後にキャプチャします...")
threading.Thread(target=self._do_capture_delayed,
args=(delay,), daemon=True).start()
def _do_capture(self):
time.sleep(0.2) # ウィンドウが隠れるのを待つ
try:
img = ImageGrab.grab()
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _do_capture_delayed(self, delay):
for i in range(delay, 0, -1):
self.root.after(0, self.status_var.set, f"キャプチャまで {i} 秒...")
time.sleep(1)
self.root.after(0, self.root.withdraw) # ウィンドウを隠す
time.sleep(0.3)
try:
img = ImageGrab.grab()
self.root.after(0, self.root.deiconify)
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.root.deiconify)
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _add_screenshot(self, img):
timestamp = datetime.now().strftime("%H:%M:%S")
w, h = img.size
entry = {"img": img, "time": timestamp, "name": f"capture_{timestamp}"}
self._screenshots.insert(0, entry)
label = f"[{timestamp}] {w}×{h}"
self.thumb_listbox.insert(0, label)
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"キャプチャ完了: {w}×{h} px")
def _open_image(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
path = filedialog.askopenfilename(
filetypes=[("画像ファイル", "*.png *.jpg *.jpeg *.bmp *.gif *.webp"),
("すべて", "*.*")])
if path:
try:
img = Image.open(path)
img.load()
name = os.path.basename(path)
timestamp = datetime.now().strftime("%H:%M:%S")
entry = {"img": img.copy(), "time": timestamp, "name": name}
self._screenshots.insert(0, entry)
w, h = img.size
self.thumb_listbox.insert(0, f"[{timestamp}] {name} {w}×{h}")
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"開きました: {name}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _on_select(self, event):
sel = self.thumb_listbox.curselection()
if sel and sel[0] < len(self._screenshots):
self._current_img = self._screenshots[sel[0]]["img"]
self._update_canvas()
def _update_canvas(self):
if not PIL_AVAILABLE or self._current_img is None:
return
zoom = self.zoom_var.get()
self.zoom_label.config(text=f"{int(zoom*100)}%")
img = self._current_img
w, h = img.size
new_w = max(1, int(w * zoom))
new_h = max(1, int(h * zoom))
resized = img.resize((new_w, new_h), Image.LANCZOS)
self._tk_img = ImageTk.PhotoImage(resized)
self.canvas.delete("all")
self.canvas.create_image(0, 0, anchor="nw", image=self._tk_img)
self.canvas.configure(scrollregion=(0, 0, new_w, new_h))
self.info_var.set(f"サイズ: {w}×{h} px | 表示: {new_w}×{new_h} px")
def _save_image(self):
if self._current_img is None:
messagebox.showwarning("警告", "保存する画像がありません")
return
path = filedialog.asksaveasfilename(
defaultextension=".png",
filetypes=[("PNG", "*.png"), ("JPEG", "*.jpg"), ("BMP", "*.bmp")])
if path:
try:
self._current_img.save(path)
self.status_var.set(f"保存しました: {path}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _delete_selected(self):
sel = self.thumb_listbox.curselection()
if sel:
idx = sel[0]
self.thumb_listbox.delete(idx)
if idx < len(self._screenshots):
self._screenshots.pop(idx)
self._current_img = None
self.canvas.delete("all")
self.info_var.set("")
# 次の項目を選択
if self._screenshots:
new_idx = min(idx, len(self._screenshots) - 1)
self.thumb_listbox.selection_set(new_idx)
self._current_img = self._screenshots[new_idx]["img"]
self._update_canvas()
def _rotate(self):
if self._current_img:
self._current_img = self._current_img.rotate(-90, expand=True)
self._update_canvas()
def _flip_h(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_LEFT_RIGHT)
self._update_canvas()
def _flip_v(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_TOP_BOTTOM)
self._update_canvas()
def _grayscale(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.convert("L").convert("RGB")
self._update_canvas()
if __name__ == "__main__":
root = tk.Tk()
app = App31(root)
root.mainloop()
5. コード解説
スクリーンショットツールのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。
クラス設計とコンストラクタ
App31クラスにアプリの全機能をまとめています。__init__メソッドでウィンドウの基本設定を行い、_build_ui()でUI構築、process()でメイン処理を担当します。この分離により、各メソッドの責任が明確になりコードが読みやすくなります。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import threading
import time
from datetime import datetime
try:
from PIL import Image, ImageTk, ImageGrab
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
try:
import pyscreenshot as ImageGrabExt
PYSCREENSHOT_AVAILABLE = True
except ImportError:
PYSCREENSHOT_AVAILABLE = False
class App31:
"""スクリーンショットツール"""
def __init__(self, root):
self.root = root
self.root.title("スクリーンショットツール")
self.root.geometry("820x620")
self.root.configure(bg="#1e1e1e")
self._screenshots = []
self._current_img = None
self._tk_img = None
self._build_ui()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#252526", pady=8)
header.pack(fill=tk.X)
tk.Label(header, text="📸 スクリーンショットツール",
font=("Noto Sans JP", 13, "bold"),
bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PIL_AVAILABLE:
tk.Label(self.root,
text="⚠ Pillow が未インストールです (pip install Pillow)。",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# ツールバー
toolbar = tk.Frame(self.root, bg="#2d2d30", pady=6)
toolbar.pack(fill=tk.X)
btn_s = {"bg": "#3c3c3c", "fg": "white", "relief": tk.FLAT,
"font": ("Arial", 10), "padx": 12, "pady=4",
"activebackground": "#505050", "bd": 0}
tk.Button(toolbar, text="📸 全画面",
command=self._capture_fullscreen,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="⏱ 遅延撮影 (3秒)",
command=self._capture_delayed,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="🖼 ファイルを開く",
command=self._open_image,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
# 遅延秒数
tk.Label(toolbar, text="遅延:", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 2))
self.delay_var = tk.IntVar(value=3)
ttk.Spinbox(toolbar, from_=1, to=30, textvariable=self.delay_var,
width=4).pack(side=tk.LEFT)
tk.Label(toolbar, text="秒", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=2)
tk.Button(toolbar, text="💾 保存",
command=self._save_image,
bg="#0288d1", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#0277bd", bd=0).pack(side=tk.RIGHT, padx=8)
tk.Button(toolbar, text="🗑 削除",
command=self._delete_selected,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#b71c1c", bd=0).pack(side=tk.RIGHT, padx=4)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: サムネイルリスト
left = tk.Frame(paned, bg="#252526")
paned.add(left, weight=1)
tk.Label(left, text="キャプチャ一覧", bg="#252526", fg="#858585",
font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
self.thumb_listbox = tk.Listbox(left, bg="#1e1e1e", fg="#c9d1d9",
font=("Arial", 10), selectmode=tk.SINGLE,
activestyle="none")
sb = ttk.Scrollbar(left, command=self.thumb_listbox.yview)
self.thumb_listbox.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.thumb_listbox.pack(fill=tk.BOTH, expand=True)
self.thumb_listbox.bind("<<ListboxSelect>>", self._on_select)
# 右: プレビュー
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=4)
# 画像情報
self.info_var = tk.StringVar(value="")
tk.Label(right, textvariable=self.info_var, bg="#0d1117",
fg="#8b949e", font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
# キャンバス (スクロール)
canvas_f = tk.Frame(right, bg="#0d1117")
canvas_f.pack(fill=tk.BOTH, expand=True)
h_sb = ttk.Scrollbar(canvas_f, orient=tk.HORIZONTAL)
v_sb = ttk.Scrollbar(canvas_f, orient=tk.VERTICAL)
self.canvas = tk.Canvas(canvas_f, bg="#0d1117", highlightthickness=0,
xscrollcommand=h_sb.set,
yscrollcommand=v_sb.set)
h_sb.configure(command=self.canvas.xview)
v_sb.configure(command=self.canvas.yview)
v_sb.pack(side=tk.RIGHT, fill=tk.Y)
h_sb.pack(side=tk.BOTTOM, fill=tk.X)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas_img_id = None
# ズーム
zoom_f = tk.Frame(right, bg="#252526")
zoom_f.pack(fill=tk.X)
tk.Label(zoom_f, text="ズーム:", bg="#252526", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=6)
self.zoom_var = tk.DoubleVar(value=1.0)
zoom_scale = ttk.Scale(zoom_f, from_=0.1, to=3.0,
variable=self.zoom_var, orient=tk.HORIZONTAL,
length=200, command=lambda v: self._update_canvas())
zoom_scale.pack(side=tk.LEFT, padx=4)
self.zoom_label = tk.Label(zoom_f, text="100%", bg="#252526", fg="#ccc",
font=("Arial", 9))
self.zoom_label.pack(side=tk.LEFT, padx=4)
# 編集ボタン
edit_f = tk.Frame(right, bg="#252526")
edit_f.pack(fill=tk.X, pady=2)
for text, cmd in [("↻ 90°回転", self._rotate),
("↔ 左右反転", self._flip_h),
("↕ 上下反転", self._flip_v),
("⬛ グレー", self._grayscale)]:
tk.Button(edit_f, text=text, command=cmd,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=8, pady=2,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
# ステータスバー
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 _capture_fullscreen(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
self.status_var.set("キャプチャ中...")
threading.Thread(target=self._do_capture, daemon=True).start()
def _capture_delayed(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
delay = self.delay_var.get()
self.status_var.set(f"{delay}秒後にキャプチャします...")
threading.Thread(target=self._do_capture_delayed,
args=(delay,), daemon=True).start()
def _do_capture(self):
time.sleep(0.2) # ウィンドウが隠れるのを待つ
try:
img = ImageGrab.grab()
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _do_capture_delayed(self, delay):
for i in range(delay, 0, -1):
self.root.after(0, self.status_var.set, f"キャプチャまで {i} 秒...")
time.sleep(1)
self.root.after(0, self.root.withdraw) # ウィンドウを隠す
time.sleep(0.3)
try:
img = ImageGrab.grab()
self.root.after(0, self.root.deiconify)
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.root.deiconify)
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _add_screenshot(self, img):
timestamp = datetime.now().strftime("%H:%M:%S")
w, h = img.size
entry = {"img": img, "time": timestamp, "name": f"capture_{timestamp}"}
self._screenshots.insert(0, entry)
label = f"[{timestamp}] {w}×{h}"
self.thumb_listbox.insert(0, label)
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"キャプチャ完了: {w}×{h} px")
def _open_image(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
path = filedialog.askopenfilename(
filetypes=[("画像ファイル", "*.png *.jpg *.jpeg *.bmp *.gif *.webp"),
("すべて", "*.*")])
if path:
try:
img = Image.open(path)
img.load()
name = os.path.basename(path)
timestamp = datetime.now().strftime("%H:%M:%S")
entry = {"img": img.copy(), "time": timestamp, "name": name}
self._screenshots.insert(0, entry)
w, h = img.size
self.thumb_listbox.insert(0, f"[{timestamp}] {name} {w}×{h}")
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"開きました: {name}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _on_select(self, event):
sel = self.thumb_listbox.curselection()
if sel and sel[0] < len(self._screenshots):
self._current_img = self._screenshots[sel[0]]["img"]
self._update_canvas()
def _update_canvas(self):
if not PIL_AVAILABLE or self._current_img is None:
return
zoom = self.zoom_var.get()
self.zoom_label.config(text=f"{int(zoom*100)}%")
img = self._current_img
w, h = img.size
new_w = max(1, int(w * zoom))
new_h = max(1, int(h * zoom))
resized = img.resize((new_w, new_h), Image.LANCZOS)
self._tk_img = ImageTk.PhotoImage(resized)
self.canvas.delete("all")
self.canvas.create_image(0, 0, anchor="nw", image=self._tk_img)
self.canvas.configure(scrollregion=(0, 0, new_w, new_h))
self.info_var.set(f"サイズ: {w}×{h} px | 表示: {new_w}×{new_h} px")
def _save_image(self):
if self._current_img is None:
messagebox.showwarning("警告", "保存する画像がありません")
return
path = filedialog.asksaveasfilename(
defaultextension=".png",
filetypes=[("PNG", "*.png"), ("JPEG", "*.jpg"), ("BMP", "*.bmp")])
if path:
try:
self._current_img.save(path)
self.status_var.set(f"保存しました: {path}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _delete_selected(self):
sel = self.thumb_listbox.curselection()
if sel:
idx = sel[0]
self.thumb_listbox.delete(idx)
if idx < len(self._screenshots):
self._screenshots.pop(idx)
self._current_img = None
self.canvas.delete("all")
self.info_var.set("")
# 次の項目を選択
if self._screenshots:
new_idx = min(idx, len(self._screenshots) - 1)
self.thumb_listbox.selection_set(new_idx)
self._current_img = self._screenshots[new_idx]["img"]
self._update_canvas()
def _rotate(self):
if self._current_img:
self._current_img = self._current_img.rotate(-90, expand=True)
self._update_canvas()
def _flip_h(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_LEFT_RIGHT)
self._update_canvas()
def _flip_v(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_TOP_BOTTOM)
self._update_canvas()
def _grayscale(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.convert("L").convert("RGB")
self._update_canvas()
if __name__ == "__main__":
root = tk.Tk()
app = App31(root)
root.mainloop()
LabelFrameによるセクション分け
ttk.LabelFrame を使うことで、入力エリアと結果エリアを視覚的に分けられます。padding引数でフレーム内の余白を設定し、見やすいレイアウトを実現しています。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import threading
import time
from datetime import datetime
try:
from PIL import Image, ImageTk, ImageGrab
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
try:
import pyscreenshot as ImageGrabExt
PYSCREENSHOT_AVAILABLE = True
except ImportError:
PYSCREENSHOT_AVAILABLE = False
class App31:
"""スクリーンショットツール"""
def __init__(self, root):
self.root = root
self.root.title("スクリーンショットツール")
self.root.geometry("820x620")
self.root.configure(bg="#1e1e1e")
self._screenshots = []
self._current_img = None
self._tk_img = None
self._build_ui()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#252526", pady=8)
header.pack(fill=tk.X)
tk.Label(header, text="📸 スクリーンショットツール",
font=("Noto Sans JP", 13, "bold"),
bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PIL_AVAILABLE:
tk.Label(self.root,
text="⚠ Pillow が未インストールです (pip install Pillow)。",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# ツールバー
toolbar = tk.Frame(self.root, bg="#2d2d30", pady=6)
toolbar.pack(fill=tk.X)
btn_s = {"bg": "#3c3c3c", "fg": "white", "relief": tk.FLAT,
"font": ("Arial", 10), "padx": 12, "pady=4",
"activebackground": "#505050", "bd": 0}
tk.Button(toolbar, text="📸 全画面",
command=self._capture_fullscreen,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="⏱ 遅延撮影 (3秒)",
command=self._capture_delayed,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="🖼 ファイルを開く",
command=self._open_image,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
# 遅延秒数
tk.Label(toolbar, text="遅延:", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 2))
self.delay_var = tk.IntVar(value=3)
ttk.Spinbox(toolbar, from_=1, to=30, textvariable=self.delay_var,
width=4).pack(side=tk.LEFT)
tk.Label(toolbar, text="秒", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=2)
tk.Button(toolbar, text="💾 保存",
command=self._save_image,
bg="#0288d1", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#0277bd", bd=0).pack(side=tk.RIGHT, padx=8)
tk.Button(toolbar, text="🗑 削除",
command=self._delete_selected,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#b71c1c", bd=0).pack(side=tk.RIGHT, padx=4)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: サムネイルリスト
left = tk.Frame(paned, bg="#252526")
paned.add(left, weight=1)
tk.Label(left, text="キャプチャ一覧", bg="#252526", fg="#858585",
font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
self.thumb_listbox = tk.Listbox(left, bg="#1e1e1e", fg="#c9d1d9",
font=("Arial", 10), selectmode=tk.SINGLE,
activestyle="none")
sb = ttk.Scrollbar(left, command=self.thumb_listbox.yview)
self.thumb_listbox.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.thumb_listbox.pack(fill=tk.BOTH, expand=True)
self.thumb_listbox.bind("<<ListboxSelect>>", self._on_select)
# 右: プレビュー
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=4)
# 画像情報
self.info_var = tk.StringVar(value="")
tk.Label(right, textvariable=self.info_var, bg="#0d1117",
fg="#8b949e", font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
# キャンバス (スクロール)
canvas_f = tk.Frame(right, bg="#0d1117")
canvas_f.pack(fill=tk.BOTH, expand=True)
h_sb = ttk.Scrollbar(canvas_f, orient=tk.HORIZONTAL)
v_sb = ttk.Scrollbar(canvas_f, orient=tk.VERTICAL)
self.canvas = tk.Canvas(canvas_f, bg="#0d1117", highlightthickness=0,
xscrollcommand=h_sb.set,
yscrollcommand=v_sb.set)
h_sb.configure(command=self.canvas.xview)
v_sb.configure(command=self.canvas.yview)
v_sb.pack(side=tk.RIGHT, fill=tk.Y)
h_sb.pack(side=tk.BOTTOM, fill=tk.X)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas_img_id = None
# ズーム
zoom_f = tk.Frame(right, bg="#252526")
zoom_f.pack(fill=tk.X)
tk.Label(zoom_f, text="ズーム:", bg="#252526", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=6)
self.zoom_var = tk.DoubleVar(value=1.0)
zoom_scale = ttk.Scale(zoom_f, from_=0.1, to=3.0,
variable=self.zoom_var, orient=tk.HORIZONTAL,
length=200, command=lambda v: self._update_canvas())
zoom_scale.pack(side=tk.LEFT, padx=4)
self.zoom_label = tk.Label(zoom_f, text="100%", bg="#252526", fg="#ccc",
font=("Arial", 9))
self.zoom_label.pack(side=tk.LEFT, padx=4)
# 編集ボタン
edit_f = tk.Frame(right, bg="#252526")
edit_f.pack(fill=tk.X, pady=2)
for text, cmd in [("↻ 90°回転", self._rotate),
("↔ 左右反転", self._flip_h),
("↕ 上下反転", self._flip_v),
("⬛ グレー", self._grayscale)]:
tk.Button(edit_f, text=text, command=cmd,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=8, pady=2,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
# ステータスバー
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 _capture_fullscreen(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
self.status_var.set("キャプチャ中...")
threading.Thread(target=self._do_capture, daemon=True).start()
def _capture_delayed(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
delay = self.delay_var.get()
self.status_var.set(f"{delay}秒後にキャプチャします...")
threading.Thread(target=self._do_capture_delayed,
args=(delay,), daemon=True).start()
def _do_capture(self):
time.sleep(0.2) # ウィンドウが隠れるのを待つ
try:
img = ImageGrab.grab()
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _do_capture_delayed(self, delay):
for i in range(delay, 0, -1):
self.root.after(0, self.status_var.set, f"キャプチャまで {i} 秒...")
time.sleep(1)
self.root.after(0, self.root.withdraw) # ウィンドウを隠す
time.sleep(0.3)
try:
img = ImageGrab.grab()
self.root.after(0, self.root.deiconify)
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.root.deiconify)
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _add_screenshot(self, img):
timestamp = datetime.now().strftime("%H:%M:%S")
w, h = img.size
entry = {"img": img, "time": timestamp, "name": f"capture_{timestamp}"}
self._screenshots.insert(0, entry)
label = f"[{timestamp}] {w}×{h}"
self.thumb_listbox.insert(0, label)
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"キャプチャ完了: {w}×{h} px")
def _open_image(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
path = filedialog.askopenfilename(
filetypes=[("画像ファイル", "*.png *.jpg *.jpeg *.bmp *.gif *.webp"),
("すべて", "*.*")])
if path:
try:
img = Image.open(path)
img.load()
name = os.path.basename(path)
timestamp = datetime.now().strftime("%H:%M:%S")
entry = {"img": img.copy(), "time": timestamp, "name": name}
self._screenshots.insert(0, entry)
w, h = img.size
self.thumb_listbox.insert(0, f"[{timestamp}] {name} {w}×{h}")
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"開きました: {name}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _on_select(self, event):
sel = self.thumb_listbox.curselection()
if sel and sel[0] < len(self._screenshots):
self._current_img = self._screenshots[sel[0]]["img"]
self._update_canvas()
def _update_canvas(self):
if not PIL_AVAILABLE or self._current_img is None:
return
zoom = self.zoom_var.get()
self.zoom_label.config(text=f"{int(zoom*100)}%")
img = self._current_img
w, h = img.size
new_w = max(1, int(w * zoom))
new_h = max(1, int(h * zoom))
resized = img.resize((new_w, new_h), Image.LANCZOS)
self._tk_img = ImageTk.PhotoImage(resized)
self.canvas.delete("all")
self.canvas.create_image(0, 0, anchor="nw", image=self._tk_img)
self.canvas.configure(scrollregion=(0, 0, new_w, new_h))
self.info_var.set(f"サイズ: {w}×{h} px | 表示: {new_w}×{new_h} px")
def _save_image(self):
if self._current_img is None:
messagebox.showwarning("警告", "保存する画像がありません")
return
path = filedialog.asksaveasfilename(
defaultextension=".png",
filetypes=[("PNG", "*.png"), ("JPEG", "*.jpg"), ("BMP", "*.bmp")])
if path:
try:
self._current_img.save(path)
self.status_var.set(f"保存しました: {path}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _delete_selected(self):
sel = self.thumb_listbox.curselection()
if sel:
idx = sel[0]
self.thumb_listbox.delete(idx)
if idx < len(self._screenshots):
self._screenshots.pop(idx)
self._current_img = None
self.canvas.delete("all")
self.info_var.set("")
# 次の項目を選択
if self._screenshots:
new_idx = min(idx, len(self._screenshots) - 1)
self.thumb_listbox.selection_set(new_idx)
self._current_img = self._screenshots[new_idx]["img"]
self._update_canvas()
def _rotate(self):
if self._current_img:
self._current_img = self._current_img.rotate(-90, expand=True)
self._update_canvas()
def _flip_h(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_LEFT_RIGHT)
self._update_canvas()
def _flip_v(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_TOP_BOTTOM)
self._update_canvas()
def _grayscale(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.convert("L").convert("RGB")
self._update_canvas()
if __name__ == "__main__":
root = tk.Tk()
app = App31(root)
root.mainloop()
Entryウィジェットとイベントバインド
ttk.Entryで入力フィールドを作成します。bind('
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import threading
import time
from datetime import datetime
try:
from PIL import Image, ImageTk, ImageGrab
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
try:
import pyscreenshot as ImageGrabExt
PYSCREENSHOT_AVAILABLE = True
except ImportError:
PYSCREENSHOT_AVAILABLE = False
class App31:
"""スクリーンショットツール"""
def __init__(self, root):
self.root = root
self.root.title("スクリーンショットツール")
self.root.geometry("820x620")
self.root.configure(bg="#1e1e1e")
self._screenshots = []
self._current_img = None
self._tk_img = None
self._build_ui()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#252526", pady=8)
header.pack(fill=tk.X)
tk.Label(header, text="📸 スクリーンショットツール",
font=("Noto Sans JP", 13, "bold"),
bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PIL_AVAILABLE:
tk.Label(self.root,
text="⚠ Pillow が未インストールです (pip install Pillow)。",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# ツールバー
toolbar = tk.Frame(self.root, bg="#2d2d30", pady=6)
toolbar.pack(fill=tk.X)
btn_s = {"bg": "#3c3c3c", "fg": "white", "relief": tk.FLAT,
"font": ("Arial", 10), "padx": 12, "pady=4",
"activebackground": "#505050", "bd": 0}
tk.Button(toolbar, text="📸 全画面",
command=self._capture_fullscreen,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="⏱ 遅延撮影 (3秒)",
command=self._capture_delayed,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="🖼 ファイルを開く",
command=self._open_image,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
# 遅延秒数
tk.Label(toolbar, text="遅延:", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 2))
self.delay_var = tk.IntVar(value=3)
ttk.Spinbox(toolbar, from_=1, to=30, textvariable=self.delay_var,
width=4).pack(side=tk.LEFT)
tk.Label(toolbar, text="秒", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=2)
tk.Button(toolbar, text="💾 保存",
command=self._save_image,
bg="#0288d1", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#0277bd", bd=0).pack(side=tk.RIGHT, padx=8)
tk.Button(toolbar, text="🗑 削除",
command=self._delete_selected,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#b71c1c", bd=0).pack(side=tk.RIGHT, padx=4)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: サムネイルリスト
left = tk.Frame(paned, bg="#252526")
paned.add(left, weight=1)
tk.Label(left, text="キャプチャ一覧", bg="#252526", fg="#858585",
font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
self.thumb_listbox = tk.Listbox(left, bg="#1e1e1e", fg="#c9d1d9",
font=("Arial", 10), selectmode=tk.SINGLE,
activestyle="none")
sb = ttk.Scrollbar(left, command=self.thumb_listbox.yview)
self.thumb_listbox.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.thumb_listbox.pack(fill=tk.BOTH, expand=True)
self.thumb_listbox.bind("<<ListboxSelect>>", self._on_select)
# 右: プレビュー
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=4)
# 画像情報
self.info_var = tk.StringVar(value="")
tk.Label(right, textvariable=self.info_var, bg="#0d1117",
fg="#8b949e", font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
# キャンバス (スクロール)
canvas_f = tk.Frame(right, bg="#0d1117")
canvas_f.pack(fill=tk.BOTH, expand=True)
h_sb = ttk.Scrollbar(canvas_f, orient=tk.HORIZONTAL)
v_sb = ttk.Scrollbar(canvas_f, orient=tk.VERTICAL)
self.canvas = tk.Canvas(canvas_f, bg="#0d1117", highlightthickness=0,
xscrollcommand=h_sb.set,
yscrollcommand=v_sb.set)
h_sb.configure(command=self.canvas.xview)
v_sb.configure(command=self.canvas.yview)
v_sb.pack(side=tk.RIGHT, fill=tk.Y)
h_sb.pack(side=tk.BOTTOM, fill=tk.X)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas_img_id = None
# ズーム
zoom_f = tk.Frame(right, bg="#252526")
zoom_f.pack(fill=tk.X)
tk.Label(zoom_f, text="ズーム:", bg="#252526", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=6)
self.zoom_var = tk.DoubleVar(value=1.0)
zoom_scale = ttk.Scale(zoom_f, from_=0.1, to=3.0,
variable=self.zoom_var, orient=tk.HORIZONTAL,
length=200, command=lambda v: self._update_canvas())
zoom_scale.pack(side=tk.LEFT, padx=4)
self.zoom_label = tk.Label(zoom_f, text="100%", bg="#252526", fg="#ccc",
font=("Arial", 9))
self.zoom_label.pack(side=tk.LEFT, padx=4)
# 編集ボタン
edit_f = tk.Frame(right, bg="#252526")
edit_f.pack(fill=tk.X, pady=2)
for text, cmd in [("↻ 90°回転", self._rotate),
("↔ 左右反転", self._flip_h),
("↕ 上下反転", self._flip_v),
("⬛ グレー", self._grayscale)]:
tk.Button(edit_f, text=text, command=cmd,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=8, pady=2,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
# ステータスバー
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 _capture_fullscreen(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
self.status_var.set("キャプチャ中...")
threading.Thread(target=self._do_capture, daemon=True).start()
def _capture_delayed(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
delay = self.delay_var.get()
self.status_var.set(f"{delay}秒後にキャプチャします...")
threading.Thread(target=self._do_capture_delayed,
args=(delay,), daemon=True).start()
def _do_capture(self):
time.sleep(0.2) # ウィンドウが隠れるのを待つ
try:
img = ImageGrab.grab()
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _do_capture_delayed(self, delay):
for i in range(delay, 0, -1):
self.root.after(0, self.status_var.set, f"キャプチャまで {i} 秒...")
time.sleep(1)
self.root.after(0, self.root.withdraw) # ウィンドウを隠す
time.sleep(0.3)
try:
img = ImageGrab.grab()
self.root.after(0, self.root.deiconify)
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.root.deiconify)
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _add_screenshot(self, img):
timestamp = datetime.now().strftime("%H:%M:%S")
w, h = img.size
entry = {"img": img, "time": timestamp, "name": f"capture_{timestamp}"}
self._screenshots.insert(0, entry)
label = f"[{timestamp}] {w}×{h}"
self.thumb_listbox.insert(0, label)
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"キャプチャ完了: {w}×{h} px")
def _open_image(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
path = filedialog.askopenfilename(
filetypes=[("画像ファイル", "*.png *.jpg *.jpeg *.bmp *.gif *.webp"),
("すべて", "*.*")])
if path:
try:
img = Image.open(path)
img.load()
name = os.path.basename(path)
timestamp = datetime.now().strftime("%H:%M:%S")
entry = {"img": img.copy(), "time": timestamp, "name": name}
self._screenshots.insert(0, entry)
w, h = img.size
self.thumb_listbox.insert(0, f"[{timestamp}] {name} {w}×{h}")
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"開きました: {name}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _on_select(self, event):
sel = self.thumb_listbox.curselection()
if sel and sel[0] < len(self._screenshots):
self._current_img = self._screenshots[sel[0]]["img"]
self._update_canvas()
def _update_canvas(self):
if not PIL_AVAILABLE or self._current_img is None:
return
zoom = self.zoom_var.get()
self.zoom_label.config(text=f"{int(zoom*100)}%")
img = self._current_img
w, h = img.size
new_w = max(1, int(w * zoom))
new_h = max(1, int(h * zoom))
resized = img.resize((new_w, new_h), Image.LANCZOS)
self._tk_img = ImageTk.PhotoImage(resized)
self.canvas.delete("all")
self.canvas.create_image(0, 0, anchor="nw", image=self._tk_img)
self.canvas.configure(scrollregion=(0, 0, new_w, new_h))
self.info_var.set(f"サイズ: {w}×{h} px | 表示: {new_w}×{new_h} px")
def _save_image(self):
if self._current_img is None:
messagebox.showwarning("警告", "保存する画像がありません")
return
path = filedialog.asksaveasfilename(
defaultextension=".png",
filetypes=[("PNG", "*.png"), ("JPEG", "*.jpg"), ("BMP", "*.bmp")])
if path:
try:
self._current_img.save(path)
self.status_var.set(f"保存しました: {path}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _delete_selected(self):
sel = self.thumb_listbox.curselection()
if sel:
idx = sel[0]
self.thumb_listbox.delete(idx)
if idx < len(self._screenshots):
self._screenshots.pop(idx)
self._current_img = None
self.canvas.delete("all")
self.info_var.set("")
# 次の項目を選択
if self._screenshots:
new_idx = min(idx, len(self._screenshots) - 1)
self.thumb_listbox.selection_set(new_idx)
self._current_img = self._screenshots[new_idx]["img"]
self._update_canvas()
def _rotate(self):
if self._current_img:
self._current_img = self._current_img.rotate(-90, expand=True)
self._update_canvas()
def _flip_h(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_LEFT_RIGHT)
self._update_canvas()
def _flip_v(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_TOP_BOTTOM)
self._update_canvas()
def _grayscale(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.convert("L").convert("RGB")
self._update_canvas()
if __name__ == "__main__":
root = tk.Tk()
app = App31(root)
root.mainloop()
Textウィジェットでの結果表示
結果表示にはtk.Textウィジェットを使います。state=tk.DISABLEDでユーザーが直接編集できないようにし、表示前にNORMALに切り替えてからinsert()で内容を更新します。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import threading
import time
from datetime import datetime
try:
from PIL import Image, ImageTk, ImageGrab
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
try:
import pyscreenshot as ImageGrabExt
PYSCREENSHOT_AVAILABLE = True
except ImportError:
PYSCREENSHOT_AVAILABLE = False
class App31:
"""スクリーンショットツール"""
def __init__(self, root):
self.root = root
self.root.title("スクリーンショットツール")
self.root.geometry("820x620")
self.root.configure(bg="#1e1e1e")
self._screenshots = []
self._current_img = None
self._tk_img = None
self._build_ui()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#252526", pady=8)
header.pack(fill=tk.X)
tk.Label(header, text="📸 スクリーンショットツール",
font=("Noto Sans JP", 13, "bold"),
bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PIL_AVAILABLE:
tk.Label(self.root,
text="⚠ Pillow が未インストールです (pip install Pillow)。",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# ツールバー
toolbar = tk.Frame(self.root, bg="#2d2d30", pady=6)
toolbar.pack(fill=tk.X)
btn_s = {"bg": "#3c3c3c", "fg": "white", "relief": tk.FLAT,
"font": ("Arial", 10), "padx": 12, "pady=4",
"activebackground": "#505050", "bd": 0}
tk.Button(toolbar, text="📸 全画面",
command=self._capture_fullscreen,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="⏱ 遅延撮影 (3秒)",
command=self._capture_delayed,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="🖼 ファイルを開く",
command=self._open_image,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
# 遅延秒数
tk.Label(toolbar, text="遅延:", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 2))
self.delay_var = tk.IntVar(value=3)
ttk.Spinbox(toolbar, from_=1, to=30, textvariable=self.delay_var,
width=4).pack(side=tk.LEFT)
tk.Label(toolbar, text="秒", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=2)
tk.Button(toolbar, text="💾 保存",
command=self._save_image,
bg="#0288d1", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#0277bd", bd=0).pack(side=tk.RIGHT, padx=8)
tk.Button(toolbar, text="🗑 削除",
command=self._delete_selected,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#b71c1c", bd=0).pack(side=tk.RIGHT, padx=4)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: サムネイルリスト
left = tk.Frame(paned, bg="#252526")
paned.add(left, weight=1)
tk.Label(left, text="キャプチャ一覧", bg="#252526", fg="#858585",
font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
self.thumb_listbox = tk.Listbox(left, bg="#1e1e1e", fg="#c9d1d9",
font=("Arial", 10), selectmode=tk.SINGLE,
activestyle="none")
sb = ttk.Scrollbar(left, command=self.thumb_listbox.yview)
self.thumb_listbox.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.thumb_listbox.pack(fill=tk.BOTH, expand=True)
self.thumb_listbox.bind("<<ListboxSelect>>", self._on_select)
# 右: プレビュー
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=4)
# 画像情報
self.info_var = tk.StringVar(value="")
tk.Label(right, textvariable=self.info_var, bg="#0d1117",
fg="#8b949e", font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
# キャンバス (スクロール)
canvas_f = tk.Frame(right, bg="#0d1117")
canvas_f.pack(fill=tk.BOTH, expand=True)
h_sb = ttk.Scrollbar(canvas_f, orient=tk.HORIZONTAL)
v_sb = ttk.Scrollbar(canvas_f, orient=tk.VERTICAL)
self.canvas = tk.Canvas(canvas_f, bg="#0d1117", highlightthickness=0,
xscrollcommand=h_sb.set,
yscrollcommand=v_sb.set)
h_sb.configure(command=self.canvas.xview)
v_sb.configure(command=self.canvas.yview)
v_sb.pack(side=tk.RIGHT, fill=tk.Y)
h_sb.pack(side=tk.BOTTOM, fill=tk.X)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas_img_id = None
# ズーム
zoom_f = tk.Frame(right, bg="#252526")
zoom_f.pack(fill=tk.X)
tk.Label(zoom_f, text="ズーム:", bg="#252526", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=6)
self.zoom_var = tk.DoubleVar(value=1.0)
zoom_scale = ttk.Scale(zoom_f, from_=0.1, to=3.0,
variable=self.zoom_var, orient=tk.HORIZONTAL,
length=200, command=lambda v: self._update_canvas())
zoom_scale.pack(side=tk.LEFT, padx=4)
self.zoom_label = tk.Label(zoom_f, text="100%", bg="#252526", fg="#ccc",
font=("Arial", 9))
self.zoom_label.pack(side=tk.LEFT, padx=4)
# 編集ボタン
edit_f = tk.Frame(right, bg="#252526")
edit_f.pack(fill=tk.X, pady=2)
for text, cmd in [("↻ 90°回転", self._rotate),
("↔ 左右反転", self._flip_h),
("↕ 上下反転", self._flip_v),
("⬛ グレー", self._grayscale)]:
tk.Button(edit_f, text=text, command=cmd,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=8, pady=2,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
# ステータスバー
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 _capture_fullscreen(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
self.status_var.set("キャプチャ中...")
threading.Thread(target=self._do_capture, daemon=True).start()
def _capture_delayed(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
delay = self.delay_var.get()
self.status_var.set(f"{delay}秒後にキャプチャします...")
threading.Thread(target=self._do_capture_delayed,
args=(delay,), daemon=True).start()
def _do_capture(self):
time.sleep(0.2) # ウィンドウが隠れるのを待つ
try:
img = ImageGrab.grab()
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _do_capture_delayed(self, delay):
for i in range(delay, 0, -1):
self.root.after(0, self.status_var.set, f"キャプチャまで {i} 秒...")
time.sleep(1)
self.root.after(0, self.root.withdraw) # ウィンドウを隠す
time.sleep(0.3)
try:
img = ImageGrab.grab()
self.root.after(0, self.root.deiconify)
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.root.deiconify)
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _add_screenshot(self, img):
timestamp = datetime.now().strftime("%H:%M:%S")
w, h = img.size
entry = {"img": img, "time": timestamp, "name": f"capture_{timestamp}"}
self._screenshots.insert(0, entry)
label = f"[{timestamp}] {w}×{h}"
self.thumb_listbox.insert(0, label)
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"キャプチャ完了: {w}×{h} px")
def _open_image(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
path = filedialog.askopenfilename(
filetypes=[("画像ファイル", "*.png *.jpg *.jpeg *.bmp *.gif *.webp"),
("すべて", "*.*")])
if path:
try:
img = Image.open(path)
img.load()
name = os.path.basename(path)
timestamp = datetime.now().strftime("%H:%M:%S")
entry = {"img": img.copy(), "time": timestamp, "name": name}
self._screenshots.insert(0, entry)
w, h = img.size
self.thumb_listbox.insert(0, f"[{timestamp}] {name} {w}×{h}")
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"開きました: {name}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _on_select(self, event):
sel = self.thumb_listbox.curselection()
if sel and sel[0] < len(self._screenshots):
self._current_img = self._screenshots[sel[0]]["img"]
self._update_canvas()
def _update_canvas(self):
if not PIL_AVAILABLE or self._current_img is None:
return
zoom = self.zoom_var.get()
self.zoom_label.config(text=f"{int(zoom*100)}%")
img = self._current_img
w, h = img.size
new_w = max(1, int(w * zoom))
new_h = max(1, int(h * zoom))
resized = img.resize((new_w, new_h), Image.LANCZOS)
self._tk_img = ImageTk.PhotoImage(resized)
self.canvas.delete("all")
self.canvas.create_image(0, 0, anchor="nw", image=self._tk_img)
self.canvas.configure(scrollregion=(0, 0, new_w, new_h))
self.info_var.set(f"サイズ: {w}×{h} px | 表示: {new_w}×{new_h} px")
def _save_image(self):
if self._current_img is None:
messagebox.showwarning("警告", "保存する画像がありません")
return
path = filedialog.asksaveasfilename(
defaultextension=".png",
filetypes=[("PNG", "*.png"), ("JPEG", "*.jpg"), ("BMP", "*.bmp")])
if path:
try:
self._current_img.save(path)
self.status_var.set(f"保存しました: {path}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _delete_selected(self):
sel = self.thumb_listbox.curselection()
if sel:
idx = sel[0]
self.thumb_listbox.delete(idx)
if idx < len(self._screenshots):
self._screenshots.pop(idx)
self._current_img = None
self.canvas.delete("all")
self.info_var.set("")
# 次の項目を選択
if self._screenshots:
new_idx = min(idx, len(self._screenshots) - 1)
self.thumb_listbox.selection_set(new_idx)
self._current_img = self._screenshots[new_idx]["img"]
self._update_canvas()
def _rotate(self):
if self._current_img:
self._current_img = self._current_img.rotate(-90, expand=True)
self._update_canvas()
def _flip_h(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_LEFT_RIGHT)
self._update_canvas()
def _flip_v(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_TOP_BOTTOM)
self._update_canvas()
def _grayscale(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.convert("L").convert("RGB")
self._update_canvas()
if __name__ == "__main__":
root = tk.Tk()
app = App31(root)
root.mainloop()
例外処理とmessagebox
try-except で ValueError と Exception を捕捉し、messagebox.showerror() でユーザーにわかりやすいエラーメッセージを表示します。入力バリデーションは必ず実装しましょう。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
import threading
import time
from datetime import datetime
try:
from PIL import Image, ImageTk, ImageGrab
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
try:
import pyscreenshot as ImageGrabExt
PYSCREENSHOT_AVAILABLE = True
except ImportError:
PYSCREENSHOT_AVAILABLE = False
class App31:
"""スクリーンショットツール"""
def __init__(self, root):
self.root = root
self.root.title("スクリーンショットツール")
self.root.geometry("820x620")
self.root.configure(bg="#1e1e1e")
self._screenshots = []
self._current_img = None
self._tk_img = None
self._build_ui()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#252526", pady=8)
header.pack(fill=tk.X)
tk.Label(header, text="📸 スクリーンショットツール",
font=("Noto Sans JP", 13, "bold"),
bg="#252526", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PIL_AVAILABLE:
tk.Label(self.root,
text="⚠ Pillow が未インストールです (pip install Pillow)。",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# ツールバー
toolbar = tk.Frame(self.root, bg="#2d2d30", pady=6)
toolbar.pack(fill=tk.X)
btn_s = {"bg": "#3c3c3c", "fg": "white", "relief": tk.FLAT,
"font": ("Arial", 10), "padx": 12, "pady=4",
"activebackground": "#505050", "bd": 0}
tk.Button(toolbar, text="📸 全画面",
command=self._capture_fullscreen,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="⏱ 遅延撮影 (3秒)",
command=self._capture_delayed,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
tk.Button(toolbar, text="🖼 ファイルを開く",
command=self._open_image,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=4)
# 遅延秒数
tk.Label(toolbar, text="遅延:", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=(12, 2))
self.delay_var = tk.IntVar(value=3)
ttk.Spinbox(toolbar, from_=1, to=30, textvariable=self.delay_var,
width=4).pack(side=tk.LEFT)
tk.Label(toolbar, text="秒", bg="#2d2d30", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=2)
tk.Button(toolbar, text="💾 保存",
command=self._save_image,
bg="#0288d1", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#0277bd", bd=0).pack(side=tk.RIGHT, padx=8)
tk.Button(toolbar, text="🗑 削除",
command=self._delete_selected,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 10), padx=12, pady=4,
activebackground="#b71c1c", bd=0).pack(side=tk.RIGHT, padx=4)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: サムネイルリスト
left = tk.Frame(paned, bg="#252526")
paned.add(left, weight=1)
tk.Label(left, text="キャプチャ一覧", bg="#252526", fg="#858585",
font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
self.thumb_listbox = tk.Listbox(left, bg="#1e1e1e", fg="#c9d1d9",
font=("Arial", 10), selectmode=tk.SINGLE,
activestyle="none")
sb = ttk.Scrollbar(left, command=self.thumb_listbox.yview)
self.thumb_listbox.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.thumb_listbox.pack(fill=tk.BOTH, expand=True)
self.thumb_listbox.bind("<<ListboxSelect>>", self._on_select)
# 右: プレビュー
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=4)
# 画像情報
self.info_var = tk.StringVar(value="")
tk.Label(right, textvariable=self.info_var, bg="#0d1117",
fg="#8b949e", font=("Arial", 9)).pack(anchor="w", padx=6, pady=2)
# キャンバス (スクロール)
canvas_f = tk.Frame(right, bg="#0d1117")
canvas_f.pack(fill=tk.BOTH, expand=True)
h_sb = ttk.Scrollbar(canvas_f, orient=tk.HORIZONTAL)
v_sb = ttk.Scrollbar(canvas_f, orient=tk.VERTICAL)
self.canvas = tk.Canvas(canvas_f, bg="#0d1117", highlightthickness=0,
xscrollcommand=h_sb.set,
yscrollcommand=v_sb.set)
h_sb.configure(command=self.canvas.xview)
v_sb.configure(command=self.canvas.yview)
v_sb.pack(side=tk.RIGHT, fill=tk.Y)
h_sb.pack(side=tk.BOTTOM, fill=tk.X)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas_img_id = None
# ズーム
zoom_f = tk.Frame(right, bg="#252526")
zoom_f.pack(fill=tk.X)
tk.Label(zoom_f, text="ズーム:", bg="#252526", fg="#ccc",
font=("Arial", 9)).pack(side=tk.LEFT, padx=6)
self.zoom_var = tk.DoubleVar(value=1.0)
zoom_scale = ttk.Scale(zoom_f, from_=0.1, to=3.0,
variable=self.zoom_var, orient=tk.HORIZONTAL,
length=200, command=lambda v: self._update_canvas())
zoom_scale.pack(side=tk.LEFT, padx=4)
self.zoom_label = tk.Label(zoom_f, text="100%", bg="#252526", fg="#ccc",
font=("Arial", 9))
self.zoom_label.pack(side=tk.LEFT, padx=4)
# 編集ボタン
edit_f = tk.Frame(right, bg="#252526")
edit_f.pack(fill=tk.X, pady=2)
for text, cmd in [("↻ 90°回転", self._rotate),
("↔ 左右反転", self._flip_h),
("↕ 上下反転", self._flip_v),
("⬛ グレー", self._grayscale)]:
tk.Button(edit_f, text=text, command=cmd,
bg="#3c3c3c", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=8, pady=2,
activebackground="#505050", bd=0).pack(side=tk.LEFT, padx=2)
# ステータスバー
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 _capture_fullscreen(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
self.status_var.set("キャプチャ中...")
threading.Thread(target=self._do_capture, daemon=True).start()
def _capture_delayed(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
delay = self.delay_var.get()
self.status_var.set(f"{delay}秒後にキャプチャします...")
threading.Thread(target=self._do_capture_delayed,
args=(delay,), daemon=True).start()
def _do_capture(self):
time.sleep(0.2) # ウィンドウが隠れるのを待つ
try:
img = ImageGrab.grab()
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _do_capture_delayed(self, delay):
for i in range(delay, 0, -1):
self.root.after(0, self.status_var.set, f"キャプチャまで {i} 秒...")
time.sleep(1)
self.root.after(0, self.root.withdraw) # ウィンドウを隠す
time.sleep(0.3)
try:
img = ImageGrab.grab()
self.root.after(0, self.root.deiconify)
self.root.after(0, self._add_screenshot, img)
except Exception as e:
self.root.after(0, self.root.deiconify)
self.root.after(0, self.status_var.set, f"エラー: {e}")
def _add_screenshot(self, img):
timestamp = datetime.now().strftime("%H:%M:%S")
w, h = img.size
entry = {"img": img, "time": timestamp, "name": f"capture_{timestamp}"}
self._screenshots.insert(0, entry)
label = f"[{timestamp}] {w}×{h}"
self.thumb_listbox.insert(0, label)
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"キャプチャ完了: {w}×{h} px")
def _open_image(self):
if not PIL_AVAILABLE:
messagebox.showerror("エラー", "Pillow が必要です:\npip install Pillow")
return
path = filedialog.askopenfilename(
filetypes=[("画像ファイル", "*.png *.jpg *.jpeg *.bmp *.gif *.webp"),
("すべて", "*.*")])
if path:
try:
img = Image.open(path)
img.load()
name = os.path.basename(path)
timestamp = datetime.now().strftime("%H:%M:%S")
entry = {"img": img.copy(), "time": timestamp, "name": name}
self._screenshots.insert(0, entry)
w, h = img.size
self.thumb_listbox.insert(0, f"[{timestamp}] {name} {w}×{h}")
self.thumb_listbox.selection_clear(0, tk.END)
self.thumb_listbox.selection_set(0)
self._current_img = img
self._update_canvas()
self.status_var.set(f"開きました: {name}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _on_select(self, event):
sel = self.thumb_listbox.curselection()
if sel and sel[0] < len(self._screenshots):
self._current_img = self._screenshots[sel[0]]["img"]
self._update_canvas()
def _update_canvas(self):
if not PIL_AVAILABLE or self._current_img is None:
return
zoom = self.zoom_var.get()
self.zoom_label.config(text=f"{int(zoom*100)}%")
img = self._current_img
w, h = img.size
new_w = max(1, int(w * zoom))
new_h = max(1, int(h * zoom))
resized = img.resize((new_w, new_h), Image.LANCZOS)
self._tk_img = ImageTk.PhotoImage(resized)
self.canvas.delete("all")
self.canvas.create_image(0, 0, anchor="nw", image=self._tk_img)
self.canvas.configure(scrollregion=(0, 0, new_w, new_h))
self.info_var.set(f"サイズ: {w}×{h} px | 表示: {new_w}×{new_h} px")
def _save_image(self):
if self._current_img is None:
messagebox.showwarning("警告", "保存する画像がありません")
return
path = filedialog.asksaveasfilename(
defaultextension=".png",
filetypes=[("PNG", "*.png"), ("JPEG", "*.jpg"), ("BMP", "*.bmp")])
if path:
try:
self._current_img.save(path)
self.status_var.set(f"保存しました: {path}")
except Exception as e:
messagebox.showerror("エラー", str(e))
def _delete_selected(self):
sel = self.thumb_listbox.curselection()
if sel:
idx = sel[0]
self.thumb_listbox.delete(idx)
if idx < len(self._screenshots):
self._screenshots.pop(idx)
self._current_img = None
self.canvas.delete("all")
self.info_var.set("")
# 次の項目を選択
if self._screenshots:
new_idx = min(idx, len(self._screenshots) - 1)
self.thumb_listbox.selection_set(new_idx)
self._current_img = self._screenshots[new_idx]["img"]
self._update_canvas()
def _rotate(self):
if self._current_img:
self._current_img = self._current_img.rotate(-90, expand=True)
self._update_canvas()
def _flip_h(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_LEFT_RIGHT)
self._update_canvas()
def _flip_v(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.transpose(Image.FLIP_TOP_BOTTOM)
self._update_canvas()
def _grayscale(self):
if self._current_img and PIL_AVAILABLE:
self._current_img = self._current_img.convert("L").convert("RGB")
self._update_canvas()
if __name__ == "__main__":
root = tk.Tk()
app = App31(root)
root.mainloop()
6. ステップバイステップガイド
このアプリをゼロから自分で作る手順を解説します。コードをコピーするだけでなく、実際に手順を追って自分で書いてみましょう。
-
1ファイルを作成する
新しいファイルを作成して app31.py と保存します。
-
2クラスの骨格を作る
App31クラスを定義し、__init__とmainloop()の最小構成を作ります。
-
3タイトルバーを作る
Frameを使ってカラーバー付きのタイトルエリアを作ります。
-
4入力フォームを実装する
LabelFrameとEntryウィジェットで入力エリアを作ります。
-
5処理ロジックを実装する
_calculate()メソッドに計算・処理ロジックを実装します。
-
6結果表示を実装する
TextウィジェットかLabelに結果を表示する_show_result()を実装します。
-
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つ追加してみましょう。どんな機能があると便利か考えてから実装してください。
-
課題2:UIの改善
色・フォント・レイアウトを変更して、より使いやすいUIにカスタマイズしてみましょう。
-
課題3:保存機能の追加
入力値や計算結果をファイルに保存する機能を追加しましょう。jsonやcsvモジュールを使います。