from __future__ import annotations import os import tkinter as tk from pathlib import Path from tkinter import ttk from typing import Callable, Iterable, Sequence from . import theme BUTTON_ICONS = { "刷新设备": "⟳", "扫描 WiFi": "⌕", "扫描WiFi": "⌕", "WiFi ADB": "▣", "保存配置": "✓", "截图+OCR": "▧", "开始运行": "▶", "暂停/继续": "Ⅱ", "停止": "■", "强制停止": "!", "发送返回键": "↩", "刷新": "⟳", "刷新预览": "⟳", "刷新列表": "⟳", "刷新映射表": "⟳", "打开pic目录": "□", "打开目录": "□", "验证卡密": "✓", "上传诊断日志": "⇧", "上传日志": "⇧", "检查更新": "↻", "刷新状态": "⟳", "保存日志配置": "✓", "查看大图": "▢", "复制条目": "◇", "清除": "×", } NAV_ICONS = { "数据看板": "▦", "运行设置": "▶", "筛选设置": "◈", "高价值预约": "◇", "养号设置": "◌", "调试参数": "⌁", "授权": "✓", "日志配置": "☰", "关键词": "⌕", "运行日志": "☰", "截图预览": "▧", "统计信息": "▦", "预约队列": "≡", "高价值房间": "◇", "行为日志": "☷", "实时状态": "●", "OCR结果": "▤", "中奖记录": "□", "映射表": "⌘", "WiFi ADB": "▣", } def _with_icon(text: str, icon: str | None) -> str: if not icon: return text return text if text.startswith(icon) else f"{icon} {text}" def _parent_bg(parent) -> str: try: return str(parent["bg"]) except Exception: return theme.BG class IconButton(tk.Button): def __init__(self, *args, icon: str | None = None, **kwargs): self._icon = icon if "text" in kwargs: kwargs["text"] = _with_icon(str(kwargs["text"]), icon) super().__init__(*args, **kwargs) def configure(self, cnf=None, **kwargs): # type: ignore[override] if "text" in kwargs: kwargs["text"] = _with_icon(str(kwargs["text"]), self._icon) return super().configure(cnf, **kwargs) config = configure def rounded_rect(canvas: tk.Canvas, x1: int, y1: int, x2: int, y2: int, radius: int, **kwargs) -> int: points = [ x1 + radius, y1, x2 - radius, y1, x2, y1, x2, y1 + radius, x2, y2 - radius, x2, y2, x2 - radius, y2, x1 + radius, y2, x1, y2, x1, y2 - radius, x1, y1 + radius, x1, y1, ] return canvas.create_polygon(points, smooth=True, splinesteps=16, **kwargs) class RoundedSurface(tk.Frame): def __init__( self, parent, *, fill: str = theme.SURFACE, outline: str = theme.BORDER, radius: int = theme.RADIUS_MD, ) -> None: super().__init__(parent, bg=_parent_bg(parent), highlightthickness=0, bd=0) self._fill = fill self._outline = outline self._radius = radius self._canvas = tk.Canvas(self, bg=_parent_bg(parent), highlightthickness=0, bd=0) self._canvas.place(x=0, y=0, relwidth=1, relheight=1) self._canvas.tk.call("lower", self._canvas._w) self.bind("", self._draw_surface) def _draw_surface(self, _event=None) -> None: width = max(2, self.winfo_width()) height = max(2, self.winfo_height()) self._canvas.delete("all") if self._outline != self._fill: rounded_rect( self._canvas, 3, 4, width - 2, height - 1, self._radius, fill=theme.SHADOW, outline=theme.SHADOW, ) rounded_rect( self._canvas, 1, 1, width - 2, height - 2, self._radius, fill=self._fill, outline=self._outline, ) def rounded_surface( parent, *, fill: str = theme.SURFACE, outline: str = theme.BORDER, radius: int = theme.RADIUS_MD, ) -> RoundedSurface: return RoundedSurface(parent, fill=fill, outline=outline, radius=radius) class RoundedButton(tk.Canvas): def __init__( self, parent, text: str, command: Callable[[], None] | None, *, kind: str = "soft", icon: str | None = None, width: int | None = None, ) -> None: self._icon = icon self.text = _with_icon(text, icon) self.command = command self.kind = kind self._state = "normal" colors = { "primary": (theme.TEAL, "#ffffff", theme.TEAL_DARK, theme.TEAL), "danger": (theme.RED_SOFT, theme.RED, "#ffe5e2", "#f2ccd1"), "amber": (theme.AMBER_SOFT, "#8a5a00", "#ffe8b8", "#f0d6a0"), "soft": (theme.SURFACE, theme.TEXT, theme.SURFACE_HOVER, theme.BORDER), "ghost": (theme.SURFACE, theme.TEXT, theme.TEAL_SOFT, theme.SURFACE), } self.bg_color, self.fg_color, self.hover_color, self.outline_color = colors.get(kind, colors["soft"]) w = width or max(118, len(self.text) * 16 + 42) super().__init__(parent, width=w, height=46, bg=_parent_bg(parent), highlightthickness=0, bd=0, cursor="hand2") self._draw(self.bg_color) self.bind("", self._click) self.bind("", lambda _e: self._draw(self.hover_color)) self.bind("", lambda _e: self._draw(self.bg_color)) def _draw(self, fill: str) -> None: self.delete("all") outline = self.outline_color fg = self.fg_color if self._state != "disabled" else theme.SUBTLE rounded_rect(self, 1, 1, int(self["width"]) - 2, int(self["height"]) - 2, theme.RADIUS_SM, fill=fill, outline=outline) self.create_text(int(self["width"]) // 2, int(self["height"]) // 2, text=self.text, fill=fg, font=("Microsoft YaHei UI", 14, "bold") if self.kind == "primary" else theme.FONT_UI) def _click(self, _event) -> None: if self.command and self._state != "disabled": self.command() def configure(self, cnf=None, **kwargs): # type: ignore[override] if cnf: kwargs.update(cnf) if "text" in kwargs: self.text = _with_icon(str(kwargs.pop("text")), self._icon) if "state" in kwargs: self._state = str(kwargs.pop("state")) self.configure(cursor="arrow" if self._state == "disabled" else "hand2") result = super().configure(**kwargs) if kwargs else None self._draw(self.bg_color) return result config = configure class RoundedNavButton(tk.Canvas): def __init__(self, parent, text: str, command: Callable[[], None], *, active: bool = False) -> None: self.raw_text = text self.text = _with_icon(text, NAV_ICONS.get(text)) self.command = command self.active = active self.enabled = True super().__init__(parent, height=46, bg=theme.SURFACE, highlightthickness=0, bd=0, cursor="hand2") self.bind("", lambda _e: self._draw()) self.bind("", lambda _e: self._invoke()) self.bind("", lambda _e: self._draw(hover=True)) self.bind("", lambda _e: self._draw()) def _invoke(self) -> None: if self.enabled: self.command() def set_active(self, active: bool) -> None: self.active = active self._draw() def set_enabled(self, enabled: bool) -> None: self.enabled = bool(enabled) self.configure(cursor="hand2" if self.enabled else "arrow") self._draw() def _draw(self, hover: bool = False) -> None: self.delete("all") width = max(1, self.winfo_width()) if not self.enabled: bg = theme.SURFACE fg = theme.MUTED else: bg = theme.TEAL_SOFT if self.active else (theme.SURFACE_HOVER if hover else theme.SURFACE) fg = theme.TEAL_DARK if self.active else theme.TEXT rounded_rect(self, 1, 4, width - 2, 42, theme.RADIUS_SM, fill=bg, outline=bg) if self.active: rounded_rect(self, 4, 12, 10, 34, 4, fill=theme.TEAL, outline=theme.TEAL) self.create_text(22 if self.active else 15, 23, text=self.text, anchor="w", fill=fg, font=("Microsoft YaHei UI", 13, "bold") if self.active else theme.FONT_UI) class SlimScrollbar(tk.Canvas): def __init__( self, parent, *, command: Callable[[str, int | float, str | None], None] | None = None, orient: str = "vertical", ) -> None: self.orient = "horizontal" if str(orient).startswith("h") else "vertical" super().__init__( parent, width=14 if self.orient == "vertical" else 1, height=14 if self.orient == "horizontal" else 1, bg=theme.SURFACE, highlightthickness=0, bd=0, cursor="hand2", ) self.command = command self.first = 0.0 self.last = 1.0 self._drag_y: int | None = None self.bind("", lambda _e: self._draw()) self.bind("", self._jump) self.bind("", self._drag) self.bind("", lambda _e: setattr(self, "_drag_y", None)) def set(self, first: float | str, last: float | str) -> None: self.first = max(0.0, min(1.0, float(first))) self.last = max(self.first, min(1.0, float(last))) self._draw() def _track_length(self) -> int: size = self.winfo_width() if self.orient == "horizontal" else self.winfo_height() return max(1, int(size)) def _thumb_bounds(self) -> tuple[int, int, int]: length = self._track_length() track_start = 10 track_end = max(track_start + 1, length - 10) track_len = track_end - track_start min_thumb = 46 if self.orient == "horizontal" else 42 thumb_len = max(min_thumb, int(track_len * max(0.08, self.last - self.first))) travel = max(1, track_len - thumb_len) start = track_start + int(travel * self.first) return start, min(track_end, start + thumb_len), travel def _draw(self) -> None: self.delete("all") length = self._track_length() if self.orient == "horizontal": self.create_line(10, 7, length - 10, 7, fill=theme.BG_ALT, width=8, capstyle="round") else: self.create_line(7, 10, 7, length - 10, fill=theme.BG_ALT, width=8, capstyle="round") if self.last - self.first >= 0.995: if self.orient == "horizontal": self.create_line(10, 7, length - 10, 7, fill=theme.TEAL_SOFT, width=8, capstyle="round") self.create_line(10, 7, length - 10, 7, fill=theme.BORDER_DARK, width=3, capstyle="round") else: self.create_line(7, 10, 7, length - 10, fill=theme.TEAL_SOFT, width=8, capstyle="round") self.create_line(7, 10, 7, length - 10, fill=theme.BORDER_DARK, width=3, capstyle="round") return start, end, _travel = self._thumb_bounds() if self.orient == "horizontal": self.create_line(start, 7, end, 7, fill=theme.TEAL, width=8, capstyle="round") self.create_line(start + 5, 7, end - 5, 7, fill=theme.TEAL_DARK, width=3, capstyle="round") else: self.create_line(7, start, 7, end, fill=theme.TEAL, width=8, capstyle="round") self.create_line(7, start + 5, 7, end - 5, fill=theme.TEAL_DARK, width=3, capstyle="round") def _moveto_from_position(self, pos: int) -> None: if not self.command: return start, end, travel = self._thumb_bounds() thumb_len = max(1, end - start) target = (pos - 10 - thumb_len / 2) / max(1, travel) self.command("moveto", max(0.0, min(1.0, target)), None) def _jump(self, event) -> None: self._drag_y = int(event.x if self.orient == "horizontal" else event.y) self._moveto_from_position(self._drag_y) def _drag(self, event) -> None: self._drag_y = int(event.x if self.orient == "horizontal" else event.y) self._moveto_from_position(self._drag_y) def clear(frame: tk.Misc) -> None: for child in frame.winfo_children(): child.destroy() def button(parent, text: str, command: Callable[[], None] | None = None, *, kind: str = "soft", width: int | None = None) -> tk.Canvas: return RoundedButton(parent, text, command, kind=kind, icon=BUTTON_ICONS.get(text), width=width) def nav_button(parent, text: str, command: Callable[[], None], *, active: bool = False) -> tk.Canvas: return RoundedNavButton(parent, text, command, active=active) def pill(parent, text: str, *, fg: str = theme.TEAL, bg: str = theme.TEAL_SOFT) -> tk.Label: return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 10, "bold"), padx=11, pady=4) def status_pill(parent, text: str, *, color: str = theme.GREEN, bg: str = theme.GREEN_SOFT) -> tk.Label: return tk.Label(parent, text=text, bg=bg, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=15, pady=6) def card(parent, title: str | None = None, *, padding: int = 14) -> tk.Frame: frame = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD) if title: head = tk.Frame(frame, bg=theme.SURFACE) head.pack(fill="x", padx=padding + 4, pady=(padding + 2, 8)) tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 11)) ttk.Label(head, text=title, style="H2.TLabel").pack(side="left") return frame def metric(parent, title: str, value: object, hint: str = "", color: str = theme.TEAL) -> tk.Frame: box = card(parent) top = tk.Frame(box, bg=theme.SURFACE) top.pack(fill="x", padx=14, pady=(10, 3)) tk.Label(top, text="●", fg=color, bg=theme.SURFACE, font=("Segoe UI", 11, "bold")).pack(side="left") ttk.Label(top, text=title, style="Small.TLabel").pack(side="left", padx=(6, 0)) ttk.Label(box, text=str(value), style="Value.TLabel").pack(anchor="w", padx=14) ttk.Label(box, text=hint, style="Small.TLabel").pack(anchor="w", padx=14, pady=(0, 10)) return box def stat_tile(parent, title: str, value: object, hint: str, *, color: str, soft: str, compact: bool = False) -> tk.Frame: box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD) if compact: box.configure(height=104) box.pack_propagate(False) inner = tk.Frame(box, bg=theme.SURFACE) inner.pack(fill="both", expand=True, padx=18, pady=14) head = tk.Frame(inner, bg=theme.SURFACE) head.pack(fill="x") tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left") tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 11, "bold")).pack(side="right") tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 24 if compact else 25, "bold")).pack(anchor="w", pady=(5, 0)) tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=12, pady=4).pack(anchor="w", pady=(7, 0)) return box def section(parent, title: str, subtitle: str = "") -> tk.Frame: row = tk.Frame(parent, bg=theme.BG) row.pack(fill="x", pady=(2, 12)) ttk.Label(row, text=title, style="Title.TLabel").pack(side="left") if subtitle: tk.Label(row, text=subtitle, bg=theme.TEAL_SOFT, fg=theme.TEAL_DARK, font=theme.FONT_SMALL, padx=14, pady=7).pack(side="left", padx=(14, 0)) return row def flow_grid(parent, columns: int = 4) -> tk.Frame: grid = tk.Frame(parent, bg=theme.BG) grid.pack(fill="x", pady=(0, 14)) for idx in range(columns): grid.grid_columnconfigure(idx, weight=1, uniform="metric") return grid def text_panel(parent, title: str, lines: Iterable[str], height: int = 10) -> tk.Frame: box = card(parent, title) text = tk.Text( box, height=height, wrap="none", bd=0, bg=theme.SURFACE_ALT, fg=theme.TEXT, insertbackground=theme.TEAL, font=theme.FONT_MONO, padx=14, pady=12, spacing1=3, spacing3=4, ) text.pack(fill="both", expand=True, padx=11, pady=(4, 11)) content = "\n".join(list(lines)[:260]) or "暂无数据" text.insert("1.0", content) text.configure(state="disabled") return box def log_panel(parent, title: str, lines: Iterable[str], height: int = 24) -> tuple[tk.Frame, tk.Text]: box = card(parent, title) wrap = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1) wrap.pack(fill="both", expand=True, padx=13, pady=(4, 13)) wrap.grid_rowconfigure(0, weight=1) wrap.grid_columnconfigure(0, weight=1) text = tk.Text( wrap, height=height, wrap="none", bd=0, bg=theme.SURFACE_ALT, fg=theme.TEXT, insertbackground=theme.TEAL, font=theme.FONT_MONO, padx=14, pady=12, spacing1=3, spacing3=4, ) yscroll = SlimScrollbar(wrap, orient="vertical", command=lambda *args: text.yview(*[a for a in args if a is not None])) xscroll = SlimScrollbar(wrap, orient="horizontal", command=lambda *args: text.xview(*[a for a in args if a is not None])) text.configure(yscrollcommand=yscroll.set, xscrollcommand=xscroll.set) text.grid(row=0, column=0, sticky="nsew") yscroll.grid(row=0, column=1, sticky="ns", padx=(4, 6), pady=8) xscroll.grid(row=1, column=0, sticky="ew", padx=8, pady=(4, 6)) content = "\n".join(list(lines)[-1000:]) or "暂无数据" text.insert("1.0", content) text.configure(state="disabled") def _wheel(event): text.yview_scroll(int(-1 * (event.delta / 120)), "units") return "break" def _shift_wheel(event): text.xview_scroll(int(-1 * (event.delta / 120)), "units") return "break" text.bind("", _wheel) text.bind("", _shift_wheel) return box, text def table_panel(parent, title: str, columns: Sequence[tuple[str, str, int]], rows: Sequence[dict], height: int = 8) -> tk.Frame: box = card(parent, title) table_wrap = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1, bd=0) table_wrap.pack(fill="both", expand=True, padx=16, pady=(4, 16)) table_wrap.grid_rowconfigure(0, weight=1) table_wrap.grid_columnconfigure(0, weight=1) tree = ttk.Treeview(table_wrap, columns=[c[0] for c in columns], show="headings", height=height, style="Dashboard.Treeview") tree.tag_configure("odd", background=theme.SURFACE) tree.tag_configure("even", background="#f7fbfc") tree.tag_configure("empty", background=theme.SURFACE_ALT, foreground=theme.MUTED) ybar = SlimScrollbar(table_wrap, orient="vertical", command=lambda *args: tree.yview(*[a for a in args if a is not None])) xbar = SlimScrollbar(table_wrap, orient="horizontal", command=lambda *args: tree.xview(*[a for a in args if a is not None])) tree.configure(yscrollcommand=ybar.set, xscrollcommand=xbar.set) total_width = sum(width for _key, _label, width in columns) compact_table = total_width <= 640 for idx, (key, label, width) in enumerate(columns): tree.heading(key, text=label) anchor = "center" if width <= 90 or key in {"idx", "pos", "value", "status"} else "w" stretch = compact_table or len(columns) <= 5 or idx == len(columns) - 1 min_width = min(width, 76) if width <= 90 else min(width, 120) tree.column(key, width=width, minwidth=min_width, anchor=anchor, stretch=stretch) for idx, row in enumerate(rows): tree.insert("", "end", values=[str(row.get(key, "-")) for key, _, _ in columns], tags=("even" if idx % 2 else "odd",)) if not rows: tree.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)], tags=("empty",)) tree.grid(row=0, column=0, sticky="nsew") ybar.grid(row=0, column=1, sticky="ns", padx=(4, 6), pady=8) xbar.grid(row=1, column=0, sticky="ew", padx=10, pady=(4, 7)) def _wheel(event): tree.yview_scroll(int(-1 * (event.delta / 120)), "units") return "break" def _shift_wheel(event): tree.xview_scroll(int(-1 * (event.delta / 120)), "units") return "break" tree.bind("", _wheel) tree.bind("", _shift_wheel) table_wrap.configure(width=max(1, min(total_width + 36, 980))) box.tree = tree # type: ignore[attr-defined] box.columns_spec = list(columns) # type: ignore[attr-defined] return box def mini_table(parent, title: str, rows: Sequence[tuple[str, str, str]], *, color: str = theme.TEAL) -> tk.Frame: box = card(parent, title) body = tk.Frame(box, bg=theme.SURFACE) body.pack(fill="both", expand=True, padx=11, pady=(4, 11)) if not rows: tk.Label(body, text="暂无数据", bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_READ, pady=20).pack(fill="x") return box for idx, (a, b, c) in enumerate(rows[:8]): row = tk.Frame(body, bg=theme.SURFACE if idx % 2 == 0 else theme.SURFACE_ALT) row.pack(fill="x", pady=1) tk.Label(row, text=a, bg=row["bg"], fg=theme.TEXT, font=theme.FONT_READ, anchor="w").pack(side="left", fill="x", expand=True, padx=9, pady=7) tk.Label(row, text=b, bg=row["bg"], fg=color, font=("Microsoft YaHei UI", 10, "bold"), width=10).pack(side="left", padx=5) tk.Label(row, text=c, bg=row["bg"], fg=theme.MUTED, font=theme.FONT_READ, width=12).pack(side="left", padx=5) return box def field_shell(parent, label: str) -> tk.Frame: row = rounded_surface(parent, fill=theme.SURFACE_ALT, outline=theme.BORDER, radius=theme.RADIUS_SM) tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_SMALL).pack(anchor="w", padx=11, pady=(8, 2)) return row def field(parent, label: str, variable: tk.Variable | None = None, *, value: object = "", wide: bool = False) -> tk.Frame: row = field_shell(parent, label) if variable is None: variable = tk.StringVar(value=str(value)) entry = tk.Entry( row, textvariable=variable, bg=theme.SURFACE_ALT, fg=theme.TEXT, insertbackground=theme.TEAL, relief="flat", bd=0, font=theme.FONT_UI, ) entry.pack(fill="x", padx=9, pady=(0, 8)) return row def select_field( parent, label: str, variable: tk.Variable | None = None, *, value: object = "", values: Sequence[object] = (), width: int | None = None, ) -> tk.Frame: row = field_shell(parent, label) if variable is None: variable = tk.StringVar(value=str(value)) combo = ttk.Combobox( row, textvariable=variable, values=[str(item) for item in values], state="readonly", width=width, ) combo.pack(fill="x", padx=9, pady=(0, 8)) return row def spin_field( parent, label: str, variable: tk.Variable | None = None, *, value: object = "", from_: float | int = 0, to: float | int = 99999, increment: float | int = 1, width: int | None = None, state: str = "normal", ) -> tk.Frame: return field(parent, label, variable, value=value) def switch_row(parent, label: str, variable: tk.Variable | None = None, value: bool = False) -> tk.Frame: row = rounded_surface(parent, fill=theme.SURFACE_ALT, outline=theme.BORDER, radius=theme.RADIUS_SM) var = variable if variable is not None else tk.BooleanVar(value=bool(value)) tk.Checkbutton( row, text=label, variable=var, bg=theme.SURFACE_ALT, fg=theme.TEXT, activebackground=theme.SURFACE_ALT, activeforeground=theme.TEXT, selectcolor=theme.SURFACE, relief="flat", bd=0, anchor="w", justify="left", font=theme.FONT_UI, ).pack(fill="x", padx=10, pady=8) return row def toolbar(parent, actions: Sequence[tuple[str, Callable[[], None] | None, str]] | Sequence[str]) -> tk.Frame: row = tk.Frame(parent, bg=theme.BG) row.pack(fill="x", pady=(0, 8)) for item in actions: if isinstance(item, str): text, command, kind = item, None, "soft" else: text, command, kind = item button(row, text, command, kind=kind).pack(side="left", padx=(0, 6)) return row def _preview_signature(image_path: Path | None) -> tuple[str, int, int] | None: try: if not image_path or not image_path.exists(): return None st = image_path.stat() return (str(image_path), int(getattr(st, "st_mtime_ns", int(st.st_mtime * 1_000_000_000))), int(st.st_size)) except Exception: return None def preview_panel( parent, image_path: Path | None, title: str = "截图预览", max_size: tuple[int, int] = (360, 560), *, auto_refresh_ms: int = 0, path_getter: Callable[[], Path | None] | None = None, ) -> tk.Frame: box = card(parent, title) body = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1) body.pack(fill="both", expand=True, padx=16, pady=(4, 16)) box._preview_signature = object() # type: ignore[attr-defined] def _render(path: Path | None, signature: tuple[str, int, int] | None) -> None: box._preview_signature = signature # type: ignore[attr-defined] for child in body.winfo_children(): child.destroy() if path and path.exists(): try: from PIL import Image, ImageTk img = Image.open(path).convert("RGB") img.thumbnail(max_size) photo = ImageTk.PhotoImage(img) label = tk.Label(body, image=photo, bg=theme.SURFACE_ALT) label.image = photo label.pack(expand=True, pady=12) ttk.Label(body, text=os.path.basename(str(path)), background=theme.SURFACE_ALT, foreground=theme.MUTED).pack(pady=(0, 8)) return except Exception: pass tk.Label(body, text="暂无截图\n点击“截图+OCR”后刷新", bg=theme.SURFACE_ALT, fg=theme.MUTED, font=("Microsoft YaHei UI", 13)).pack(expand=True) def _current_path() -> Path | None: if path_getter is not None: try: return path_getter() except Exception: return image_path return image_path def _refresh() -> None: try: if not box.winfo_exists(): return except Exception: return path = _current_path() signature = _preview_signature(path) if signature != getattr(box, "_preview_signature", None): _render(path, signature) if auto_refresh_ms > 0: try: box.after(auto_refresh_ms, _refresh) except Exception: pass _refresh() return box class ScrollFrame(ttk.Frame): def __init__(self, parent): super().__init__(parent, style="Dashboard.TFrame") self.canvas = tk.Canvas(self, bg=theme.BG, highlightthickness=0, bd=0) self.scroll = SlimScrollbar(self, orient="vertical", command=lambda *args: self.canvas.yview(*[a for a in args if a is not None])) self.inner = tk.Frame(self.canvas, bg=theme.BG) self.window_id = self.canvas.create_window((0, 0), window=self.inner, anchor="nw") self.canvas.configure(yscrollcommand=self.scroll.set) self.canvas.pack(side="left", fill="both", expand=True) self.scroll.pack(side="right", fill="y", padx=(6, 0), pady=6) self.inner.bind("", lambda _e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))) self.canvas.bind("", lambda e: self.canvas.itemconfigure(self.window_id, width=e.width)) self.canvas.bind_all("", self._wheel) def _wheel(self, event) -> None: try: widget = event.widget while widget is not None: if str(widget.winfo_class()) in {"Text", "Treeview", "Listbox", "TCombobox", "TSpinbox", "Entry"}: return if widget is self.canvas: break widget = widget.master self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units") except Exception: pass