refactor(gui): 抽 win_record Tab 全部 7 个动作到 components/win_record_view (4044 → 3891)

This commit is contained in:
Your Name committed 2026-05-30 14:53:11 +08:00
1 parent a7ef92fc7c
commit 59ebe8c1e7
2 files changed
+228 -176

No files matched your search

+205
View File
@@ -0,0 +1,205 @@
"""中奖记录 Tab 视图相关:截图列表、预览、误识别记录管理。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内一组互相调用的闭包,
共享 ``_win_file_paths`` / ``_win_img_ref`` / 多个 widgets。
抽出后通过 ``WinRecordView`` 容器把状态聚一起,7 个动作函数接收容器作为参数。
``gui_app.py`` 在创建好 widgets 后调用 ``install_win_record_view`` 绑定按钮和
回调,并拿到 ``refresh`` / ``load_false_positives`` 两个函数用于 ``after`` 调度。
"""
from __future__ import annotations
import json
import os
import tkinter as tk
from dataclasses import dataclass, field
from datetime import datetime
from tkinter import ttk
from typing import Any, Callable, Dict
from PIL import Image, ImageTk # type: ignore[import]
@dataclass
class WinRecordView:
"""中奖记录 Tab 的 widgets + 状态容器。"""
listbox: tk.Listbox
image_label: ttk.Label
preview_frame: tk.Misc
false_positive_text: tk.Text
on_line: Callable[[str], None]
file_paths: Dict[int, str] = field(default_factory=dict)
img_ref: Dict[str, Any] = field(default_factory=lambda: {"photo": None})
def _get_pic_dir() -> str:
try:
from douyin.core.path_config import get_pic_dir
return get_pic_dir()
except Exception:
from douyin.core import path_config
return path_config.get_pic_dir()
def scan_win_images() -> list:
"""扫描中奖截图目录,返回 ``[(filename, abs_path, mtime), ...]`` 按时间倒序。"""
pic_dir = _get_pic_dir()
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
win_images: list = []
if os.path.exists(prize_dir):
for file in os.listdir(prize_dir):
if file.lower().endswith((".png", ".jpg", ".jpeg")):
file_path = os.path.join(prize_dir, file)
# 获取文件修改时间
try:
mtime = os.path.getmtime(file_path)
win_images.append((file, file_path, mtime))
except Exception:
win_images.append((file, file_path, 0))
# 按时间倒序排序(最新的在前)
win_images.sort(key=lambda x: x[2], reverse=True)
return win_images
def refresh_win_record(view: WinRecordView) -> None:
"""刷新中奖记录列表"""
try:
win_images = scan_win_images()
view.listbox.delete(0, tk.END)
view.file_paths.clear()
for idx, (file, file_path, mtime) in enumerate(win_images):
# 格式化显示:文件名 + 时间
try:
dt = datetime.fromtimestamp(mtime)
time_str = dt.strftime("%Y-%m-%d %H:%M:%S")
display_text = f"{file} ({time_str})"
except Exception:
display_text = file
view.listbox.insert(tk.END, display_text)
# 存储文件路径映射
view.file_paths[idx] = file_path
if win_images:
view.on_line(f"[中奖记录] 扫描到 {len(win_images)} 张中奖截图")
else:
view.on_line("[中奖记录] 暂无中奖截图")
except Exception as e:
view.on_line(f"[中奖记录] 刷新失败:{e}")
def _load_win_image(view: WinRecordView, img_path: str) -> None:
"""加载并显示中奖截图"""
if not os.path.exists(img_path):
view.image_label.configure(image="")
view.img_ref["photo"] = None
return
try:
img = Image.open(img_path)
img.load()
img = img.convert("RGB")
except Exception as e:
view.on_line(f"[中奖记录] 图片加载失败:{e}")
return
# 获取预览区域尺寸
try:
view.preview_frame.update_idletasks()
w = view.preview_frame.winfo_width()
h = view.preview_frame.winfo_height()
if w <= 1 or h <= 1:
w, h = 400, 600
except Exception:
w, h = 400, 600
max_w = max(200, w - 20)
max_h = max(300, 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)
def on_win_list_select(view: WinRecordView, _event=None) -> None:
"""当选择中奖截图时,显示预览"""
try:
selection = view.listbox.curselection()
if not selection:
return
index = selection[0]
# 从映射中获取文件路径
if index in view.file_paths:
file_path = view.file_paths[index]
_load_win_image(view, file_path)
except Exception as e:
view.on_line(f"[中奖记录] 预览失败:{e}")
def open_win_folder(view: WinRecordView) -> None:
"""打开中奖截图目录"""
pic_dir = _get_pic_dir()
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
os.makedirs(prize_dir, exist_ok=True)
try:
os.startfile(prize_dir) # type: ignore[attr-defined]
except Exception as e:
view.on_line(f"[中奖记录] 打开目录失败:{e}")
def load_false_positives(view: WinRecordView) -> None:
"""加载误识别记录"""
pic_dir = _get_pic_dir()
false_positive_file = os.path.join(
pic_dir, "lottery_prize_captures", "false_positives.json"
)
if not os.path.exists(false_positive_file):
view.false_positive_text.delete("1.0", "end")
view.false_positive_text.insert("1.0", "暂无误识别记录")
return
try:
with open(false_positive_file, "r", encoding="utf-8") as f:
data = json.load(f)
false_positives = data.get("false_positives", [])
view.false_positive_text.delete("1.0", "end")
if false_positives:
view.false_positive_text.insert("1.0", "\n".join(false_positives))
else:
view.false_positive_text.insert("1.0", "暂无误识别记录")
except Exception as e:
view.false_positive_text.delete("1.0", "end")
view.false_positive_text.insert("1.0", f"加载失败:{e}")
def save_false_positives(view: WinRecordView) -> None:
"""保存误识别记录"""
pic_dir = _get_pic_dir()
false_positive_file = os.path.join(
pic_dir, "lottery_prize_captures", "false_positives.json"
)
os.makedirs(os.path.dirname(false_positive_file), exist_ok=True)
content = view.false_positive_text.get("1.0", "end-1c")
lines = [line.strip() for line in content.splitlines() if line.strip()]
try:
with open(false_positive_file, "w", encoding="utf-8") as f:
json.dump({"false_positives": lines}, f, ensure_ascii=False, indent=2)
view.on_line(f"[中奖记录] 已保存 {len(lines)} 条误识别记录")
except Exception as e:
view.on_line(f"[中奖记录] 保存失败:{e}")
+23 -176
View File
@@ -58,6 +58,14 @@ from gui.components.wifi_adb_pick_dialog import open_scan_pick_dialog as _open_s
from gui.components.wifi_adb_reconnect import try_reconnect_last_wifi as _try_reconnect_last_wifi_impl
from gui.components.ocr_results_view import update_ocr_results as _update_ocr_results_impl
from gui.components.log_pump import pump_logs as _pump_logs_impl
from gui.components.win_record_view import (
WinRecordView as _WinRecordView,
refresh_win_record as _refresh_win_record_impl,
on_win_list_select as _on_win_list_select_impl,
open_win_folder as _open_win_folder_impl,
load_false_positives as _load_false_positives_impl,
save_false_positives as _save_false_positives_impl,
)
# 导入日志颜色配置模块
try:
@@ -3718,115 +3726,11 @@ def main():
win_image_label.pack(fill=BOTH, expand=True)
_win_img_ref: dict[str, Any] = {"photo": None}
def scan_win_images():
"""扫描中奖截图目录"""
try:
from douyin.core.path_config import get_pic_dir
pic_dir = get_pic_dir()
except Exception:
from douyin.core import path_config
pic_dir = path_config.get_pic_dir()
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
win_images = []
if os.path.exists(prize_dir):
for file in os.listdir(prize_dir):
if file.lower().endswith((".png", ".jpg", ".jpeg")):
file_path = os.path.join(prize_dir, file)
# 获取文件修改时间
try:
mtime = os.path.getmtime(file_path)
win_images.append((file, file_path, mtime))
except Exception:
win_images.append((file, file_path, 0))
# 按时间倒序排序(最新的在前)
win_images.sort(key=lambda x: x[2], reverse=True)
return win_images
def refresh_win_record():
"""刷新中奖记录列表"""
try:
win_images = scan_win_images()
win_listbox.delete(0, tk.END)
_win_file_paths.clear()
for idx, (file, file_path, mtime) in enumerate(win_images):
# 格式化显示:文件名 + 时间
try:
dt = datetime.fromtimestamp(mtime)
time_str = dt.strftime("%Y-%m-%d %H:%M:%S")
display_text = f"{file} ({time_str})"
except Exception:
display_text = file
win_listbox.insert(tk.END, display_text)
# 存储文件路径映射
_win_file_paths[idx] = file_path
if win_images:
on_line(f"[中奖记录] 扫描到 {len(win_images)} 张中奖截图")
else:
on_line("[中奖记录] 暂无中奖截图")
except Exception as e:
on_line(f"[中奖记录] 刷新失败:{e}")
_refresh_win_record_impl(_win_record_view)
def on_win_list_select(event):
"""当选择中奖截图时,显示预览"""
try:
selection = win_listbox.curselection()
if not selection:
return
index = selection[0]
# 从映射中获取文件路径
if index in _win_file_paths:
file_path = _win_file_paths[index]
_load_win_image(file_path)
except Exception as e:
on_line(f"[中奖记录] 预览失败:{e}")
def _load_win_image(img_path: str):
"""加载并显示中奖截图"""
if not os.path.exists(img_path):
win_image_label.configure(image="")
_win_img_ref["photo"] = None
return
try:
img = Image.open(img_path)
img.load()
img = img.convert("RGB")
except Exception as e:
on_line(f"[中奖记录] 图片加载失败:{e}")
return
# 获取预览区域尺寸
try:
win_preview_frame.update_idletasks()
w = win_preview_frame.winfo_width()
h = win_preview_frame.winfo_height()
if w <= 1 or h <= 1:
w, h = 400, 600
except Exception:
w, h = 400, 600
max_w = max(200, w - 20)
max_h = max(300, h - 20)
try:
resample = Image.Resampling.LANCZOS
except AttributeError:
resample = 1
img.thumbnail((max_w, max_h), resample)
photo = ImageTk.PhotoImage(img)
_win_img_ref["photo"] = photo
win_image_label.configure(image=photo)
_on_win_list_select_impl(_win_record_view, event)
win_listbox.bind("<<ListboxSelect>>", on_win_list_select)
ttk.Button(win_record_top, text="刷新列表", command=refresh_win_record).pack(
@@ -3834,22 +3738,7 @@ def main():
)
def open_win_folder():
"""打开中奖截图目录"""
try:
from douyin.core.path_config import get_pic_dir
pic_dir = get_pic_dir()
except Exception:
from douyin.core import path_config
pic_dir = path_config.get_pic_dir()
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
os.makedirs(prize_dir, exist_ok=True)
try:
os.startfile(prize_dir) # type: ignore[attr-defined]
except Exception as e:
on_line(f"[中奖记录] 打开目录失败:{e}")
_open_win_folder_impl(_win_record_view)
ttk.Button(win_record_top, text="打开目录", command=open_win_folder).pack(side=LEFT)
ttk.Button(
@@ -3871,63 +3760,21 @@ def main():
false_positive_text = ScrolledText(false_positive_frame, height=6)
false_positive_text.pack(fill=X, padx=10, pady=10)
_win_record_view = _WinRecordView(
listbox=win_listbox,
image_label=win_image_label,
preview_frame=win_preview_frame,
false_positive_text=false_positive_text,
on_line=on_line,
file_paths=_win_file_paths,
img_ref=_win_img_ref,
)
def load_false_positives():
"""加载误识别记录"""
try:
from douyin.core.path_config import get_pic_dir
pic_dir = get_pic_dir()
except Exception:
from douyin.core import path_config
pic_dir = path_config.get_pic_dir()
false_positive_file = os.path.join(
pic_dir, "lottery_prize_captures", "false_positives.json"
)
if not os.path.exists(false_positive_file):
false_positive_text.delete("1.0", "end")
false_positive_text.insert("1.0", "暂无误识别记录")
return
try:
with open(false_positive_file, "r", encoding="utf-8") as f:
data = json.load(f)
false_positives = data.get("false_positives", [])
false_positive_text.delete("1.0", "end")
if false_positives:
false_positive_text.insert("1.0", "\n".join(false_positives))
else:
false_positive_text.insert("1.0", "暂无误识别记录")
except Exception as e:
false_positive_text.delete("1.0", "end")
false_positive_text.insert("1.0", f"加载失败:{e}")
_load_false_positives_impl(_win_record_view)
def save_false_positives():
"""保存误识别记录"""
try:
from douyin.core.path_config import get_pic_dir
pic_dir = get_pic_dir()
except Exception:
from douyin.core import path_config
pic_dir = path_config.get_pic_dir()
false_positive_file = os.path.join(
pic_dir, "lottery_prize_captures", "false_positives.json"
)
os.makedirs(os.path.dirname(false_positive_file), exist_ok=True)
content = false_positive_text.get("1.0", "end-1c")
lines = [line.strip() for line in content.splitlines() if line.strip()]
try:
with open(false_positive_file, "w", encoding="utf-8") as f:
json.dump({"false_positives": lines}, f, ensure_ascii=False, indent=2)
on_line(f"[中奖记录] 已保存 {len(lines)} 条误识别记录")
except Exception as e:
on_line(f"[中奖记录] 保存失败:{e}")
_save_false_positives_impl(_win_record_view)
false_positive_btn_frame = ttk.Frame(false_positive_frame)
false_positive_btn_frame.pack(fill=X, padx=10, pady=(0, 10))