Files

194 lines
6.7 KiB
Python

"""截图预览 Tab 视图相关:目录扫描、列表更新、图片加载与缩放、异步预览。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内一组互相调用的闭包,
共享 ``images_dir`` / ``image_var`` / ``image_combo`` / ``preview_body`` /
``image_label`` / ``preview_status`` / ``_img_ref`` 等。
抽出后通过 ``PreviewView`` 容器把 widgets/状态聚一起,各动作函数接收容器作为参数。
"""
from __future__ import annotations
import os
import threading
import tkinter as tk
from dataclasses import dataclass, field
from tkinter import ttk
from typing import Any, Callable, Dict, List
from PIL import Image, ImageTk # type: ignore[import]
@dataclass
class PreviewView:
"""截图预览 Tab 的 widgets + 状态容器。"""
images_dir: str
image_var: tk.StringVar
image_combo: ttk.Combobox
preview_body: tk.Misc
image_label: ttk.Label
preview_status: tk.StringVar
on_line: Callable[[str], None]
root: tk.Misc
img_ref: Dict[str, Any] = field(default_factory=lambda: {"photo": None})
def scan_image_files(view: PreviewView) -> List[str]:
"""扫描pic文件夹及其子文件夹中的所有图片文件"""
image_files: List[str] = []
if os.path.exists(view.images_dir):
for root_dir, _dirs, files in os.walk(view.images_dir):
for file in files:
if file.lower().endswith(
(".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif")
):
# 获取相对路径
rel_path = os.path.relpath(
os.path.join(root_dir, file), str(view.images_dir)
)
# 统一使用正斜杠(Windows和Unix都支持)
rel_path = rel_path.replace("\\", "/")
image_files.append(rel_path)
# 按文件名排序
image_files.sort(key=lambda x: x.lower())
return image_files
def update_image_list(view: PreviewView, refresh_after: bool = True) -> None:
"""更新图片列表"""
new_list = scan_image_files(view)
view.image_combo["values"] = new_list
current_value = view.image_var.get()
# 如果当前值不在新列表中,或列表为空,选择第一个
if new_list:
if not current_value or current_value not in new_list:
view.image_var.set(new_list[0])
else:
view.image_var.set("")
view.on_line(f"[预览] 扫描到 {len(new_list)} 个图片文件")
# 如果当前有选择的图片,刷新预览
if refresh_after and view.image_var.get():
try:
refresh_preview(view)
except Exception:
pass
def _load_and_fit_image(view: PreviewView, img_path: str) -> None:
if not os.path.exists(img_path):
view.preview_status.set(f"未找到:{os.path.basename(img_path)}")
view.image_label.configure(image="")
view.img_ref["photo"] = None
return
try:
img = Image.open(img_path)
img.load() # Force load to catch truncated files early
img = img.convert("RGB")
except (OSError, IOError, SyntaxError) as e:
# Handle truncated image files
view.preview_status.set(f"图片加载失败:{str(e)[:50]}")
view.image_label.configure(image="")
view.img_ref["photo"] = None
return
except Exception as e:
view.preview_status.set(f"图片加载错误:{str(e)[:50]}")
view.image_label.configure(image="")
view.img_ref["photo"] = None
return
# 获取预览区域的实际尺寸(如果窗口还未初始化,使用默认值)
try:
view.preview_body.update_idletasks() # 强制更新布局
w = view.preview_body.winfo_width()
h = view.preview_body.winfo_height()
# 如果尺寸无效(窗口未初始化),使用默认值
if w <= 1 or h <= 1:
w, h = 900, 520
except Exception:
w, h = 900, 520
max_w = max(300, w - 20)
max_h = max(200, h - 20)
try:
resample = Image.Resampling.LANCZOS
except AttributeError:
# Fallback for older Pillow versions: LANCZOS constant value is 1
resample = 1 # type: ignore[assignment]
img.thumbnail((max_w, max_h), resample)
photo: ImageTk.PhotoImage = ImageTk.PhotoImage(img)
view.img_ref["photo"] = photo # type: ignore[assignment]
view.image_label.configure(image=photo)
view.preview_status.set(f"{os.path.basename(img_path)} {img.width}x{img.height}")
def refresh_preview(view: PreviewView) -> None:
name = view.image_var.get().strip()
if not name:
view.preview_status.set("请选择图片")
view.image_label.configure(image="")
view.img_ref["photo"] = None
return
# 处理相对路径(将正斜杠转换为系统路径分隔符)
name_normalized = name.replace("/", os.sep)
path = os.path.join(view.images_dir, name_normalized)
_load_and_fit_image(view, path)
def open_pic_folder(view: PreviewView) -> None:
try:
os.makedirs(view.images_dir, exist_ok=True)
os.startfile(view.images_dir) # type: ignore[attr-defined]
except Exception as e:
view.on_line(f"[预览] 打开图片目录失败:{e}")
def async_refresh_preview(view: PreviewView) -> None:
"""后台加载图片预览,避免阻塞主线程导致 GUI 卡顿。"""
name = view.image_var.get().strip()
if not name:
return
name_normalized = name.replace("/", os.sep)
path = os.path.join(view.images_dir, name_normalized)
if not os.path.exists(path):
return
def _worker():
try:
img = Image.open(path)
img.load()
img = img.convert("RGB")
except Exception:
return
def _apply():
try:
view.preview_body.update_idletasks()
w = view.preview_body.winfo_width()
h = view.preview_body.winfo_height()
if w <= 1 or h <= 1:
w, h = 900, 520
max_w = max(300, w - 20)
max_h = max(200, h - 20)
try:
resample = Image.Resampling.LANCZOS
except AttributeError:
resample = 1
img.thumbnail((max_w, max_h), resample)
photo = ImageTk.PhotoImage(img)
view.img_ref["photo"] = photo
view.image_label.configure(image=photo)
view.preview_status.set(
f"{os.path.basename(path)} {img.width}x{img.height}"
)
except Exception:
pass
try:
view.root.after(0, _apply)
except Exception:
pass
threading.Thread(target=_worker, daemon=True).start()