Files
hk4e-gm-clone/ui/widgets.py
T

269 lines
10 KiB
Python

"""自制控件:卡片、搜索下拉、数据表、提示条。"""
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from typing import Callable, Dict, List, Optional, Sequence, Tuple
from .theme import C, F_BODY, F_H2, F_MONO_S, F_SMALL, mk_button, mk_entry
class Card(tk.Frame):
"""带标题的卡片容器。"""
def __init__(self, parent, title: str = "", subtitle: str = "", pad: int = 14, **kw):
super().__init__(parent, bg=C["card"], highlightthickness=1,
highlightbackground=C["border"], **kw)
self.body_pad = pad
if title:
head = tk.Frame(self, bg=C["card"])
head.pack(fill="x", padx=pad, pady=(pad, 0))
tk.Label(head, text=title, bg=C["card"], fg=C["text"], font=F_H2,
anchor="w").pack(side="left")
self.subtitle = tk.Label(head, text=subtitle, bg=C["card"], fg=C["faint"],
font=F_SMALL, anchor="e")
self.subtitle.pack(side="right")
tk.Frame(self, bg=C["border"], height=1).pack(fill="x", padx=pad, pady=(8, 0))
self.body = tk.Frame(self, bg=C["card"])
self.body.pack(fill="both", expand=True, padx=pad, pady=pad)
class Row(tk.Frame):
def __init__(self, parent, **kw):
super().__init__(parent, bg=C["card"], **kw)
def label(parent, text: str, fg: Optional[str] = None, font=None, width: int = 0) -> tk.Label:
lbl = tk.Label(parent, text=text, bg=C["card"], fg=fg or C["dim"], font=font or F_SMALL, anchor="w")
if width:
lbl.configure(width=width)
return lbl
class SearchCombo(tk.Frame):
"""带搜索过滤 + 收藏的下拉框(原程序 SearchComboBox 的等价物)。"""
def __init__(self, parent, entries_provider: Callable[[str], List], on_pick: Optional[Callable] = None,
width: int = 42, favorites: Optional[List[str]] = None,
on_favorite: Optional[Callable[[str], None]] = None):
super().__init__(parent, bg=C["card"])
self.entries_provider = entries_provider
self.on_pick = on_pick
self.on_favorite = on_favorite
self.favorites = favorites if favorites is not None else []
self._results: List = []
self.var = tk.StringVar()
self.entry = mk_entry(self, self.var, width=width)
self.entry.pack(side="left", fill="x", expand=True)
self.entry.bind("<KeyRelease>", self._on_key)
self.entry.bind("<Return>", self._on_enter)
self.entry.bind("<Down>", lambda e: self._move(1))
self.entry.bind("<Up>", lambda e: self._move(-1))
self.entry.bind("<Right>", lambda e: self._favorite())
self.btn = mk_button(self, "▾", self._show_all, kind="flat", width=2)
self.btn.pack(side="left", padx=(4, 0))
self.popup: Optional[tk.Toplevel] = None
self.listbox: Optional[tk.Listbox] = None
self._first_label = ""
self._first_value = ""
# ------------------------------------------------------------------
def _open(self) -> None:
if self.popup is not None:
return
self.popup = tk.Toplevel(self)
self.popup.overrideredirect(True)
self.popup.configure(bg=C["border"])
self.listbox = tk.Listbox(self.popup, bg=C["card2"], fg=C["text"], selectbackground=C["accent"],
selectforeground="#fff", relief="flat", bd=0, font=F_BODY,
highlightthickness=0, activestyle="none")
self.listbox.pack(fill="both", expand=True, padx=1, pady=1)
self.listbox.bind("<<ListboxSelect>>", self._on_select)
self.listbox.bind("<Double-Button-1>", lambda e: self._commit())
self.popup.bind("<FocusOut>", lambda e: self._close())
self._place()
def _place(self) -> None:
if not self.popup:
return
self.update_idletasks()
x = self.entry.winfo_rootx()
y = self.entry.winfo_rooty() + self.entry.winfo_height() + 2
w = self.winfo_width()
h = min(320, 22 * max(1, len(self._results)) + 6)
self.popup.geometry(f"{max(w, 240)}x{h}+{x}+{y}")
self.popup.lift()
def _close(self) -> None:
if self.popup:
try:
self.popup.destroy()
except Exception:
pass
self.popup = None
self.listbox = None
def _refresh(self, keyword: str = "") -> None:
self._results = self.entries_provider(keyword)[:300]
if not self.listbox:
return
self.listbox.delete(0, "end")
for e in self._results:
fav = "★ " if e.id in self.favorites else " "
self.listbox.insert("end", f"{fav}{e.id} {e.name}")
if self._results:
self.listbox.selection_set(0)
self._place()
# ------------------------------------------------------------------
def _on_key(self, event) -> None:
if event.keysym in ("Down", "Up", "Return", "Right", "Left", "Escape"):
return
self._open()
self._refresh(self.var.get())
self._sync_first()
def _sync_first(self) -> None:
if not self.listbox or not self._results:
self._first_label = ""
return
self._first_label = self.listbox.get(0)
self._first_value = self._results[0].id
def _show_all(self) -> None:
self._open()
self._refresh("")
self._sync_first()
def _move(self, delta: int) -> None:
if not self.listbox:
self._open()
self._refresh(self.var.get())
if not self.listbox or not self._results:
return
cur = self.listbox.curselection()
idx = (cur[0] if cur else 0) + delta
idx = max(0, min(len(self._results) - 1, idx))
self.listbox.selection_clear(0, "end")
self.listbox.selection_set(idx)
self.listbox.see(idx)
def _on_select(self, event=None) -> None:
if not self.listbox:
return
cur = self.listbox.curselection()
if not cur:
return
idx = cur[0]
if idx < len(self._results):
e = self._results[idx]
self.var.set(f"{e.id} {e.name}")
def _on_enter(self, event) -> None:
self._commit()
def _commit(self) -> None:
if self.listbox and self._results:
cur = self.listbox.curselection()
idx = cur[0] if cur else 0
if idx < len(self._results):
e = self._results[idx]
self.var.set(f"{e.id} {e.name}")
self._close()
if self.on_pick:
self.on_pick(e)
return
self._close()
def _favorite(self) -> None:
eid = self.current_id()
if eid and self.on_favorite:
self.on_favorite(eid)
# ------------------------------------------------------------------
def current_id(self) -> str:
text = self.var.get().strip()
if not text:
return ""
head = text.split()[0]
return head if head.isdigit() else (self._first_value if text else "")
def set_id(self, eid: str) -> None:
self.var.set(str(eid))
def clear(self) -> None:
self.var.set("")
class Table(tk.Frame):
"""Treeview 封装:列定义 + 便捷填充。"""
def __init__(self, parent, columns: Sequence[Tuple[str, str, int]], height: int = 8,
on_select: Optional[Callable] = None, on_double: Optional[Callable] = None):
super().__init__(parent, bg=C["card"])
self.columns = list(columns)
keys = [c[0] for c in self.columns]
self.tree = ttk.Treeview(self, columns=keys, show="headings", height=height, selectmode="browse")
for key, title, width in self.columns:
self.tree.heading(key, text=title, anchor="w")
self.tree.column(key, width=width, anchor="w", stretch=True)
vs = tk.Scrollbar(self, orient="vertical", command=self.tree.yview,
bg=C["card2"], troughcolor=C["bg"], activebackground=C["border2"],
relief="flat", bd=0, width=10, highlightthickness=0)
self.tree.configure(yscrollcommand=vs.set)
self.tree.pack(side="left", fill="both", expand=True)
vs.pack(side="right", fill="y")
if on_select:
self.tree.bind("<<TreeviewSelect>>", lambda e: on_select(self.selected()))
if on_double:
self.tree.bind("<Double-Button-1>", lambda e: on_double(self.selected()))
self._rows: Dict[str, dict] = {}
def clear(self) -> None:
self.tree.delete(*self.tree.get_children())
self._rows.clear()
def add(self, values: Sequence[str], record: Optional[dict] = None) -> str:
iid = self.tree.insert("", "end", values=list(values))
self._rows[iid] = dict(record or {})
return iid
def selected(self) -> Optional[dict]:
cur = self.tree.selection()
if not cur:
return None
rec = dict(self._rows.get(cur[0], {}))
rec["_iid"] = cur[0]
return rec
def values(self) -> List[Sequence[str]]:
return [self.tree.item(i, "values") for i in self.tree.get_children()]
class Toast:
"""底部提示条。"""
def __init__(self, parent, root):
self.root = root
self.label = tk.Label(parent, text="", bg=C["card2"], fg=C["text"], font=F_SMALL,
padx=12, pady=6)
self._job = None
def show(self, text: str, kind: str = "info", ms: int = 2600) -> None:
color = {"info": C["text"], "ok": C["ok"], "warn": C["warn"], "error": C["danger"]}.get(kind, C["text"])
self.label.configure(text=text, fg=color)
self.label.place(relx=0.5, rely=1.0, anchor="s", y=-14)
self.label.lift()
if self._job:
try:
self.root.after_cancel(self._job)
except Exception:
pass
self._job = self.root.after(ms, self.label.place_forget)
def status_pill(parent, text: str, on: bool = False) -> tk.Label:
return tk.Label(parent, text=text, bg=C["accent_dim"] if on else C["card2"],
fg=C["accent"] if on else C["faint"], font=F_SMALL,
padx=10, pady=3)