优化:更新配置文件中的重置动作和点击等待时间;调整映射表生成逻辑,提升代码可读性

This commit is contained in:
Your Name committed 2026-01-20 12:16:19 +08:00
1 parent 3b4293365d
commit b9b21d472f
9 files changed
+1062 -528

No files matched your search

+5 -515
View File
@@ -26,6 +26,7 @@ from gui.gui_core import (
write_config,
)
from path_config import get_logs_dir
from gui.components.mapping_table import create_mapping_tab
# 导入日志颜色配置模块
try:
@@ -484,7 +485,7 @@ def main():
value=float(cfg.get("reservation_back_swipe_delay", 0) or 0)
)
reservation_back_verify_wait_seconds_var = tk.DoubleVar(
value=float(cfg.get("reservation_back_verify_wait_seconds", 3.0) or 3.0)
value=float(cfg.get("reservation_back_verify_wait_seconds", 5.0) or 5.0)
)
fudai_find_max_attempts_var = tk.IntVar(
value=int(cfg.get("fudai_find_max_attempts", 0) or 0)
@@ -2314,7 +2315,7 @@ def main():
reservation_back_swipe_delay_var.get() or 0
)
cfg2["reservation_back_verify_wait_seconds"] = float(
reservation_back_verify_wait_seconds_var.get() or 3.0
reservation_back_verify_wait_seconds_var.get() or 5.0
)
cfg2["fudai_find_max_attempts"] = int(fudai_find_max_attempts_var.get() or 0)
cfg2["fudai_icon_retry_delay_seconds"] = float(
@@ -2782,519 +2783,8 @@ def main():
notebook.add(realtime_tab, text="实时状态")
notebook.add(ocr_results_tab, text="OCR结果")
notebook.add(win_record_tab, text="中奖记录")
# 将运行时映射表加入右侧 Notebook
mapping_tab = ttk.Frame(notebook)
map_box = ttk.LabelFrame(mapping_tab, text="运行时映射表(包含福袋详情)")
map_box.pack(fill=BOTH, expand=True, padx=10, pady=(10, 10))
map_ctrl = ttk.Frame(map_box)
map_ctrl.pack(fill=X, padx=10, pady=(8, 6))
map_auto_refresh_var = tk.BooleanVar(value=True)
ttk.Checkbutton(
map_ctrl, text="自动刷新(5s)", variable=map_auto_refresh_var
).pack(side=LEFT)
ttk.Button(map_ctrl, text="刷新映射表", width=12).pack(side=LEFT, padx=(8, 6))
# 映射内容显示区(表格形式)
mapping_source_var = tk.StringVar(value="未加载")
ttk.Label(map_ctrl, textvariable=mapping_source_var).pack(side=LEFT, padx=(8, 0))
# mapping_tree_box 应该放在 map_box(LabelFrame)内部,
# 否则与控件区的布局会错位,导致列显示挤在一起和滚动行为异常。
mapping_tree_box = ttk.Frame(map_box)
mapping_tree_box.pack(fill=BOTH, expand=True, padx=10, pady=(6, 10))
mapping_tree = ttk.Treeview(
mapping_tree_box,
columns=(
"pos",
"title",
"title_raw",
"has_fudai",
"fudai_content",
"task_list",
"countdown",
"fudai_value",
"participants",
"copies",
"button_text",
"is_reserved",
),
show="headings",
height=12,
)
# 为表头指定对齐,便于阅读;长列允许 stretch 以便在窗口拉伸时扩展
mapping_tree.heading("pos", text="位置", anchor="center")
mapping_tree.heading("title", text="标题", anchor="w")
mapping_tree.heading("title_raw", text="原始标题", anchor="w")
mapping_tree.heading("has_fudai", text="有福袋", anchor="center")
mapping_tree.heading("fudai_content", text="福袋内容", anchor="w")
mapping_tree.heading("task_list", text="任务列表", anchor="w")
mapping_tree.heading("countdown", text="倒计时", anchor="center")
mapping_tree.heading("fudai_value", text="价值(元)", anchor="e")
mapping_tree.heading("participants", text="参与人数", anchor="e")
mapping_tree.heading("copies", text="份数", anchor="e")
mapping_tree.heading("button_text", text="按钮文本", anchor="w")
mapping_tree.heading("is_reserved", text="已预约", anchor="center")
# 优化列宽与伸缩行为:让标题/内容类列随窗口拉伸,数值列保持固定宽度
mapping_tree.column("pos", width=50, anchor="e", stretch=False)
mapping_tree.column("title", width=220, anchor="w", stretch=True)
mapping_tree.column("title_raw", width=220, anchor="w", stretch=True)
mapping_tree.column("has_fudai", width=60, anchor="center", stretch=False)
mapping_tree.column("fudai_content", width=300, anchor="w", stretch=True)
mapping_tree.column("task_list", width=240, anchor="w", stretch=True)
mapping_tree.column("countdown", width=90, anchor="center", stretch=False)
mapping_tree.column("fudai_value", width=90, anchor="e", stretch=False)
mapping_tree.column("participants", width=90, anchor="e", stretch=False)
mapping_tree.column("copies", width=70, anchor="e", stretch=False)
mapping_tree.column("button_text", width=180, anchor="w", stretch=True)
mapping_tree.column("is_reserved", width=70, anchor="center", stretch=False)
mapping_tree.tag_configure("odd", background="#fafafa")
mapping_tree.tag_configure("even", background="#ffffff")
# 自动调整列宽以适应内容(基于文本像素宽度测量)
try:
import tkinter.font as tkfont
def _adjust_mapping_tree_columns(
tree: ttk.Treeview, padding: int = 12, max_width: int = 1200
) -> None:
try:
font = tkfont.Font()
except Exception:
try:
# 回退:创建默认字体
font = tkfont.Font()
except Exception:
font = None
# 最小列宽(与之前的默认宽度保持一致,避免太窄)
min_widths = {
"pos": 50,
"title": 120,
"title_raw": 120,
"has_fudai": 60,
"fudai_content": 180,
"task_list": 160,
"countdown": 90,
"fudai_value": 90,
"participants": 90,
"copies": 70,
"button_text": 140,
"is_reserved": 70,
}
cols = tree["columns"]
for col in cols:
try:
# 获取表头文本
header = tree.heading(col).get("text", str(col))
except Exception:
try:
header = tree.heading(col, "text")
except Exception:
header = str(col)
try:
max_w = font.measure(str(header)) if font else len(str(header)) * 8
except Exception:
max_w = len(str(header)) * 8
# 遍历所有行,找到最大内容宽度
for iid in tree.get_children():
try:
cell = str(tree.set(iid, col) or "")
except Exception:
cell = ""
try:
w = font.measure(cell) if font else len(cell) * 8
except Exception:
w = len(cell) * 8
if w > max_w:
max_w = w
target = int(max(min_widths.get(col, 40), max_w + padding))
if target > max_width:
target = max_width
try:
tree.column(col, width=target)
except Exception:
pass
except Exception:
# tkinter.font 不可用时跳过自动调整
def _adjust_mapping_tree_columns(
tree: ttk.Treeview, padding: int = 12, max_width: int = 1200
) -> None:
return
map_scroll_y = ttk.Scrollbar(
mapping_tree_box, orient="vertical", command=mapping_tree.yview
)
map_scroll_x = ttk.Scrollbar(
mapping_tree_box, orient="horizontal", command=mapping_tree.xview
)
mapping_tree.configure(
yscrollcommand=map_scroll_y.set, xscrollcommand=map_scroll_x.set
)
# 使用 grid 布局使横向/纵向滚动条与 Treeview 精确对齐
mapping_tree_box.grid_rowconfigure(0, weight=1)
mapping_tree_box.grid_columnconfigure(0, weight=1)
mapping_tree.grid(row=0, column=0, sticky="nsew")
map_scroll_y.grid(row=0, column=1, sticky="ns")
map_scroll_x.grid(row=1, column=0, sticky="ew")
# 绑定窗口变化:自动调整列宽以适配内容(节流,避免频繁计算)
mapping_tree_autofit_job = {"id": None}
def _schedule_mapping_tree_autofit(_event: object | None = None) -> None:
try:
job_id = mapping_tree_autofit_job.get("id")
if job_id:
root.after_cancel(job_id)
except Exception:
pass
def _do_adjust() -> None:
try:
_adjust_mapping_tree_columns(mapping_tree)
except Exception:
pass
try:
mapping_tree_autofit_job["id"] = root.after(120, _do_adjust)
except Exception:
_do_adjust()
try:
mapping_tree_box.bind("<Configure>", _schedule_mapping_tree_autofit)
except Exception:
pass
# 加载映射表到表格(尝试多个可能的路径)
def _load_mapping_to_view():
# 清空表格
try:
mapping_tree.delete(*mapping_tree.get_children())
except Exception:
pass
# 加载预约状态(用于检查是否已预约)
reservations_data = {}
try:
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
reservations_paths = [
os.path.join(base_dir, "douyin", "core", "state", "reservations.json"),
os.path.join(base_dir, "douyin", "state", "reservations.json"),
os.path.join(
os.getcwd(), "douyin", "core", "state", "reservations.json"
),
]
for res_path in reservations_paths:
try:
if os.path.exists(res_path):
with open(res_path, "r", encoding="utf-8") as f:
res_raw = f.read()
res_parsed = json.loads(res_raw)
if isinstance(res_parsed, dict) and "queue" in res_parsed:
# 提取预约队列中的位置信息
for item in res_parsed["queue"]:
pos = item.get("pos_seen", 0)
if pos:
reservations_data[pos] = item
break
except Exception:
pass
except Exception:
pass
# 优先使用基于项目目录的固定路径,避免不同工作目录导致无法找到状态文件
try:
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
except Exception:
base_dir = os.getcwd()
possible_paths = [
os.path.join(base_dir, "douyin", "core", "state", "room_pos_map.json"),
os.path.join(base_dir, "douyin", "core", "state", "reservations.json"),
os.path.join(base_dir, "douyin", "state", "room_pos_map.json"),
os.path.join(os.getcwd(), "douyin", "core", "state", "room_pos_map.json"),
]
found = False
row_index = 0
for p in possible_paths:
try:
if os.path.exists(p):
with open(p, "r", encoding="utf-8") as f:
raw = f.read()
try:
parsed = json.loads(raw)
except Exception:
parsed = None
mapping_source_var.set(p)
if not parsed:
# 非JSON或解析错误:在表格中显示原始文本的一行提示
mapping_tree.insert(
"",
"end",
values=(
"-",
"(非JSON,查看原始文件)",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
),
tags=("even",),
)
else:
# 移除元信息
if isinstance(parsed, dict) and "_meta" in parsed:
parsed.pop("_meta", None)
# 按数字顺序插入
try:
keys = sorted(
parsed.keys(),
key=lambda x: int(x) if str(x).isdigit() else x,
)
except Exception:
keys = list(parsed.keys())
for k in keys:
try:
v = parsed.get(k, {})
if isinstance(v, dict):
# 新格式:字典
title = (v.get("title", "") or "").strip() or "-"
title_raw = (
v.get("title_raw", "") or ""
).strip() or "-"
has_fudai = "✓" if v.get("has_fudai", False) else ""
fudai_content = (
v.get("fudai_content", "") or ""
).strip() or "-"
# 提取福袋详细信息
fudai_detail = v.get("fudai_detail")
task_list = "-"
button_text = "-"
countdown_text = "-"
if isinstance(fudai_detail, dict):
task_list = (
str(
fudai_detail.get("task_list") or ""
).strip()
or "-"
)
button_text = (
str(
fudai_detail.get("button_text") or ""
).strip()
or "-"
)
fudai_time = (
str(
fudai_detail.get("time_text") or ""
).strip()
or "-"
)
fudai_value = (
f"{float(fudai_detail.get('prize_value_yuan') or 0):.2f}"
if fudai_detail.get("prize_value_yuan")
else "-"
)
participants = (
str(fudai_detail.get("participants") or 0)
if fudai_detail.get("participants")
else "-"
)
copies = (
str(fudai_detail.get("copies") or 0)
if fudai_detail.get("copies")
else "-"
)
mm = str(
fudai_detail.get("countdown_mm") or ""
).strip()
ss = str(
fudai_detail.get("countdown_ss") or ""
).strip()
if fudai_time and fudai_time != "-":
countdown_text = fudai_time
elif mm or ss:
if mm.isdigit() and len(mm) == 1:
mm = f"0{mm}"
if ss.isdigit() and len(ss) == 1:
ss = f"0{ss}"
if mm and ss:
countdown_text = f"{mm}:{ss}"
else:
countdown_text = mm or ss
elif (
fudai_detail
and isinstance(fudai_detail, (tuple, list))
and len(fudai_detail) >= 5
):
# fudai_detail结构: (content, time_text, participants, copies, prize_value_yuan, countdown_tuple)
fudai_time = fudai_detail[1] or "-" # time_text
fudai_value = (
f"{fudai_detail[4] or 0:.2f}"
if fudai_detail[4]
else "-"
) # prize_value_yuan
participants = (
str(fudai_detail[2] or 0)
if fudai_detail[2]
else "-"
) # participants
copies = (
str(fudai_detail[3] or 0)
if fudai_detail[3]
else "-"
) # copies
countdown_text = fudai_time or "-"
else:
fudai_time = "-"
fudai_value = "-"
participants = "-"
copies = "-"
countdown_text = "-"
# 检查是否已预约
is_reserved = (
"✓" if int(k) in reservations_data else ""
)
else:
# 兼容旧格式:元组
title = (v[0] or "").strip() or "-"
title_raw = (v[1] or "").strip() or "-"
has_fudai = ""
fudai_content = "-"
fudai_time = "-"
countdown_text = "-"
fudai_value = "-"
participants = "-"
copies = "-"
task_list = "-"
button_text = "-"
is_reserved = (
"✓" if int(k) in reservations_data else ""
)
except Exception:
(
title,
title_raw,
has_fudai,
fudai_content,
task_list,
countdown_text,
fudai_value,
participants,
copies,
button_text,
is_reserved,
) = (
"-",
"-",
"",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
)
row_tag = "even" if row_index % 2 == 0 else "odd"
mapping_tree.insert(
"",
"end",
values=(
k,
title,
title_raw,
has_fudai,
fudai_content,
task_list,
countdown_text,
fudai_value,
participants,
copies,
button_text,
is_reserved,
),
tags=(row_tag,),
)
row_index += 1
found = True
break
except Exception:
# 忽略单个路径读取错误,尝试下一个候选
pass
# 如果已找到并填充了映射表,尝试自动调整列宽以适配内容
if found:
try:
_schedule_mapping_tree_autofit()
except Exception:
try:
_adjust_mapping_tree_columns(mapping_tree)
except Exception:
pass
if not found:
mapping_source_var.set("未找到 room_pos_map.json")
mapping_tree.insert(
"",
"end",
values=(
"-",
"未找到映射表文件",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
),
tags=("even",),
)
# 绑定刷新按钮与自动刷新
btns = map_ctrl.winfo_children()
if btns and isinstance(btns[-1], ttk.Button):
btns[-1].config(command=_load_mapping_to_view)
def _maybe_auto_refresh():
if map_auto_refresh_var.get():
try:
_load_mapping_to_view()
except Exception:
pass
root.after(5000, _maybe_auto_refresh)
# 启动自动刷新轮询(无害,如果开关关闭不会频繁IO)
root.after(5000, _maybe_auto_refresh)
# 使用模块化组件创建映射表并加入 Notebook
mapping_tab = create_mapping_tab(root, notebook, cfg)
notebook.add(mapping_tab, text="映射表")
# 日志区