refactor(gui): 抽预览 Tab 全部 8 个动作到 components/preview_view (3891 → 3775)
This commit is contained in:
1 parent
59ebe8c1e7
commit
92d524297b
2 files changed
+223
-146
No files matched your search
@@ -0,0 +1,193 @@
|
||||
"""截图预览 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()
|
||||
+30
-146
@@ -66,6 +66,15 @@ from gui.components.win_record_view import (
|
||||
load_false_positives as _load_false_positives_impl,
|
||||
save_false_positives as _save_false_positives_impl,
|
||||
)
|
||||
from gui.components.preview_view import (
|
||||
PreviewView as _PreviewView,
|
||||
scan_image_files as _scan_image_files_impl,
|
||||
update_image_list as _update_image_list_impl,
|
||||
refresh_preview as _refresh_preview_impl,
|
||||
_load_and_fit_image as _load_and_fit_image_impl,
|
||||
open_pic_folder as _open_pic_folder_impl,
|
||||
async_refresh_preview as _async_refresh_preview_impl,
|
||||
)
|
||||
|
||||
# 导入日志颜色配置模块
|
||||
try:
|
||||
@@ -3225,24 +3234,7 @@ def main():
|
||||
images_dir = path_config.get_pic_dir()
|
||||
|
||||
def scan_image_files():
|
||||
"""扫描pic文件夹及其子文件夹中的所有图片文件"""
|
||||
image_files = []
|
||||
if os.path.exists(images_dir):
|
||||
for root, dirs, files in os.walk(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, file), str(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
|
||||
return _scan_image_files_impl(_preview_view)
|
||||
|
||||
image_var = tk.StringVar(value="")
|
||||
|
||||
@@ -3254,39 +3246,11 @@ def main():
|
||||
image_combo.pack(side=LEFT, padx=(0, 10))
|
||||
|
||||
def update_image_list(refresh_after=True):
|
||||
"""更新图片列表"""
|
||||
new_list = scan_image_files()
|
||||
image_combo["values"] = new_list
|
||||
current_value = image_var.get()
|
||||
# 如果当前值不在新列表中,或列表为空,选择第一个
|
||||
if new_list:
|
||||
if not current_value or current_value not in new_list:
|
||||
image_var.set(new_list[0])
|
||||
else:
|
||||
image_var.set("")
|
||||
on_line(f"[预览] 扫描到 {len(new_list)} 个图片文件")
|
||||
# 如果当前有选择的图片,刷新预览(如果refresh_after为True且refresh_preview已定义)
|
||||
if refresh_after and image_var.get():
|
||||
try:
|
||||
refresh_preview()
|
||||
except NameError:
|
||||
# refresh_preview还没定义,忽略
|
||||
pass
|
||||
_update_image_list_impl(_preview_view, refresh_after=refresh_after)
|
||||
|
||||
# 先定义refresh_preview函数(即使它引用了后面的变量,函数定义本身是延迟执行的)
|
||||
def refresh_preview():
|
||||
name = image_var.get().strip()
|
||||
if not name:
|
||||
preview_status.set("请选择图片")
|
||||
image_label.configure(image="")
|
||||
_img_ref["photo"] = None
|
||||
return
|
||||
# 处理相对路径(将正斜杠转换为系统路径分隔符)
|
||||
name_normalized = name.replace("/", os.sep)
|
||||
path = os.path.join(images_dir, name_normalized)
|
||||
_load_and_fit_image(path)
|
||||
|
||||
update_image_list(refresh_after=False) # 初始化时扫描一次,但不刷新预览
|
||||
_refresh_preview_impl(_preview_view)
|
||||
|
||||
preview_status = tk.StringVar(value="")
|
||||
ttk.Label(preview_top, textvariable=preview_status).pack(side=RIGHT)
|
||||
@@ -3298,52 +3262,22 @@ def main():
|
||||
image_label.pack(fill=BOTH, expand=True)
|
||||
_img_ref: dict[str, Any] = {"photo": None} # 防止 PhotoImage 被回收
|
||||
|
||||
_preview_view = _PreviewView(
|
||||
images_dir=str(images_dir),
|
||||
image_var=image_var,
|
||||
image_combo=image_combo,
|
||||
preview_body=preview_body,
|
||||
image_label=image_label,
|
||||
preview_status=preview_status,
|
||||
on_line=on_line,
|
||||
root=root,
|
||||
img_ref=_img_ref,
|
||||
)
|
||||
|
||||
update_image_list(refresh_after=False) # 初始化时扫描一次,但不刷新预览
|
||||
|
||||
def _load_and_fit_image(img_path: str) -> None:
|
||||
if not os.path.exists(img_path):
|
||||
preview_status.set(f"未找到:{os.path.basename(img_path)}")
|
||||
image_label.configure(image="")
|
||||
_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
|
||||
preview_status.set(f"图片加载失败:{str(e)[:50]}")
|
||||
image_label.configure(image="")
|
||||
_img_ref["photo"] = None
|
||||
return
|
||||
except Exception as e:
|
||||
preview_status.set(f"图片加载错误:{str(e)[:50]}")
|
||||
image_label.configure(image="")
|
||||
_img_ref["photo"] = None
|
||||
return
|
||||
|
||||
# 获取预览区域的实际尺寸(如果窗口还未初始化,使用默认值)
|
||||
try:
|
||||
preview_body.update_idletasks() # 强制更新布局
|
||||
w = preview_body.winfo_width()
|
||||
h = 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)
|
||||
_img_ref["photo"] = photo # type: ignore[assignment]
|
||||
image_label.configure(image=photo)
|
||||
preview_status.set(f"{os.path.basename(img_path)} {img.width}x{img.height}")
|
||||
_load_and_fit_image_impl(_preview_view, img_path)
|
||||
|
||||
ttk.Button(
|
||||
preview_top,
|
||||
@@ -3354,11 +3288,10 @@ def main():
|
||||
|
||||
# 绑定选择变化事件,自动刷新预览(在 refresh_preview 函数定义之后)
|
||||
def on_image_selected(*args):
|
||||
"""当用户选择图片时自动刷新预览"""
|
||||
try:
|
||||
refresh_preview()
|
||||
except Exception:
|
||||
pass # 忽略错误,避免影响其他功能
|
||||
pass
|
||||
|
||||
image_var.trace("w", on_image_selected) # 监听变量变化
|
||||
image_combo.bind(
|
||||
@@ -3366,11 +3299,7 @@ def main():
|
||||
) # 监听下拉选择
|
||||
|
||||
def open_pic_folder():
|
||||
try:
|
||||
os.makedirs(images_dir, exist_ok=True)
|
||||
os.startfile(images_dir) # type: ignore[attr-defined]
|
||||
except Exception as e:
|
||||
on_line(f"[预览] 打开图片目录失败:{e}")
|
||||
_open_pic_folder_impl(_preview_view)
|
||||
|
||||
ttk.Button(preview_top, text="打开pic目录", command=open_pic_folder).pack(
|
||||
side=LEFT, padx=(10, 0)
|
||||
@@ -3794,52 +3723,7 @@ def main():
|
||||
_async_refresh_preview()
|
||||
|
||||
def _async_refresh_preview() -> None:
|
||||
"""后台加载图片预览,避免阻塞主线程导致 GUI 卡顿。"""
|
||||
name = image_var.get().strip()
|
||||
if not name:
|
||||
return
|
||||
name_normalized = name.replace("/", os.sep)
|
||||
path = os.path.join(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:
|
||||
preview_body.update_idletasks()
|
||||
w = preview_body.winfo_width()
|
||||
h = 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)
|
||||
_img_ref["photo"] = photo
|
||||
image_label.configure(image=photo)
|
||||
preview_status.set(
|
||||
f"{os.path.basename(path)} {img.width}x{img.height}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
root.after(0, _apply)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
threading.Thread(target=_worker, daemon=True).start()
|
||||
_async_refresh_preview_impl(_preview_view)
|
||||
|
||||
root.after(3000, delayed_refresh_preview) # type: ignore[arg-type]
|
||||
root.after(500, refresh_stats) # type: ignore[arg-type]
|
||||
|
||||
Reference in new issue
Block a user