Files

1166 lines
41 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""平板化 UI 组件(tkinter + Pillow 抗锯齿圆角,不引入第三方 UI 库)。
设计基准:1440×900 横屏平板
· 触摸目标 ≥ 52px,主操作 64~72px
· 圆角 14(卡片)/ 999(胶囊按钮)
· 留白 16 / 20,字号 13 / 15 / 18 / 26 / 72
对外:
C 配色常量
rounded_photo(...) 抗锯齿圆角图片(带缓存,按尺寸/颜色复用)
TouchButton 大触摸按钮(按下回弹、圆角)
Segmented 分段导航(滑块跟手 + 吸附动画)
Switch 滑动开关
StepsBar 圆角步骤条
Pager 可左右滑动的页面容器(跟手 + 松手吸附)
TouchScroll 手指拖动滚动(带惯性)
bind_swipe_to(...) 让普通控件也参与翻页手势
"""
import tkinter as tk
import time as _time
try:
from PIL import Image, ImageDraw, ImageTk
_HAS_PIL = True
except Exception: # pragma: no cover
_HAS_PIL = False
# ------------------------------------------------------------------ 配色
class C:
bg = '#f4f6fa' # 页面底色
surface = '#ffffff' # 卡片
line = '#e6ebf2' # 分隔线
ink = '#1b2634' # 主文字
ink2 = '#5b6675' # 次文字
ink3 = '#98a2b3' # 弱文字
brand = '#1b5fa5' # 品牌蓝
brand_dark = '#134a83'
brand_soft = '#e8f1fb'
green = '#0f6e56'
green_soft = '#e3f2ec'
amber = '#b45309'
amber_soft = '#fdf0d9'
red = '#a32d2d'
red_soft = '#fbe9e9'
track = '#e9edf4'
def shade(hex_color, k):
"""把颜色整体调暗/调亮:k<1 变暗,k>1 变亮(保持色相)"""
hex_color = hex_color.lstrip('#')
if len(hex_color) == 3:
hex_color = ''.join(c * 2 for c in hex_color)
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
if k <= 1:
r, g, b = int(r * k), int(g * k), int(b * k)
else:
d = k - 1.0
r = int(r + (255 - r) * d)
g = int(g + (255 - g) * d)
b = int(b + (255 - b) * d)
return '#%02x%02x%02x' % (max(0, min(255, r)),
max(0, min(255, g)),
max(0, min(255, b)))
# ------------------------------------------------------------------ 圆角图片
_SS = 3 # 超采样倍数:3 倍绘制再缩小,边缘才不毛
_IMG_CACHE = {}
_PH_CACHE = {}
def _hex_rgb(h):
h = h.lstrip('#')
if len(h) == 3:
h = ''.join(c * 2 for c in h)
return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16))
def rounded_image(w, h, r, fill, on, outline=None, ow=1):
"""返回抗锯齿圆角矩形 PIL 图;on = 背景色(用于把透明角混成实体色)"""
w, h = max(1, int(w)), max(1, int(h))
r = max(0, int(r))
key = (w, h, r, fill, on, outline, ow)
im = _IMG_CACHE.get(key)
if im is not None:
return im
if _HAS_PIL:
W, H, R = w * _SS, h * _SS, min(r * _SS, min(w, h) * _SS // 2)
base = Image.new('RGB', (W, H), _hex_rgb(on))
d = ImageDraw.Draw(base)
box = [0, 0, W - 1, H - 1]
if outline and ow > 0:
d.rounded_rectangle(box, radius=R, fill=_hex_rgb(outline))
i = int(ow * _SS)
d.rounded_rectangle([i, i, W - 1 - i, H - 1 - i],
radius=max(0, R - i), fill=_hex_rgb(fill))
else:
d.rounded_rectangle(box, radius=R, fill=_hex_rgb(fill))
im = base.resize((w, h), Image.LANCZOS)
else: # 没有 Pillow 就退化成直角块
im = None
_IMG_CACHE[key] = im
return im
def rounded_photo(w, h, r, fill, on, outline=None, ow=1):
"""转成 Tk 可用的 PhotoImage(全局缓存,避免每次重绘都新建位图)"""
w, h = max(1, int(w)), max(1, int(h))
key = (w, h, r, fill, on, outline, ow)
ph = _PH_CACHE.get(key)
if ph is not None:
return ph
im = rounded_image(w, h, r, fill, on, outline, ow)
if im is None or not _HAS_PIL:
return None
try:
ph = ImageTk.PhotoImage(im)
except Exception:
return None
_PH_CACHE[key] = ph
return ph
def draw_round(cv, x1, y1, x2, y2, r, fill, outline='', width=1, tags=''):
"""Canvas 上画圆角块(无 Pillow 时的兜底 / 小装饰用)"""
r = max(0, min(r, (x2 - x1) // 2, (y2 - y1) // 2))
pts = [x1 + r, y1, x2 - r, y1, x2, y1, x2, y1 + r,
x2, y2 - r, x2, y2, x2 - r, y2, x1 + r, y2,
x1, y2, x1, y2 - r, x1, y1 + r, x1, y1]
return cv.create_polygon(pts, smooth=True, splinesteps=16, fill=fill,
outline=outline, width=width, tags=tags)
# ------------------------------------------------------------------ 触摸按钮
class TouchButton(tk.Canvas):
"""圆角大按钮:按下变深并轻微下沉,松手回弹再执行。
参数按「平板尺寸」给:height 默认 64,最小建议 52。
"""
def __init__(self, parent, text='', command=None, fill=C.brand,
fg='#ffffff', surface=None, height=64, radius=None,
font=None, sub='', sub_font=None, width=None,
enabled=True, outline=None, pad=18, anchor='center',
icon='', icon_font=None, **kw):
surface = surface or _surface_of(parent)
super().__init__(parent, bg=surface, highlightthickness=0, bd=0,
height=height, width=width or 10, takefocus=0, **kw)
self._text = text
self._icon = icon
self._sub = sub
self._command = command
self._fill = fill
self._fg = fg
self._surface = surface
self._radius = radius if radius is not None else min(18, height // 2)
self._font = font or ('Microsoft YaHei', 16, 'bold')
self._sub_font = sub_font or ('Microsoft YaHei', 11)
self._icon_font = icon_font or ('Microsoft YaHei', 20)
self._enabled = bool(enabled)
self._outline = outline
self._pad = pad
self._anchor = anchor
self._pressed = False
self._hover = False
self._last_size = (0, 0)
self.bind('<Configure>', self._on_configure)
self.bind('<ButtonPress-1>', self._on_press)
self.bind('<ButtonRelease-1>', self._on_release)
self.bind('<Enter>', self._on_enter)
self.bind('<Leave>', self._on_leave)
self.bind('<Destroy>', lambda e: None)
# -- 外部接口
def configure_btn(self, **kw):
for k, v in kw.items():
if k == 'text':
self._text = v
elif k == 'sub':
self._sub = v
elif k == 'fill':
self._fill = v
elif k == 'bg':
self._fill = v
elif k == 'fg':
self._fg = v
elif k == 'enabled':
self._enabled = bool(v)
elif k == 'state':
self._enabled = (v != 'disabled')
elif k == 'command':
self._command = v
elif k == 'icon':
self._icon = v
self._draw()
def configure(self, cnf=None, **kw):
"""兼容 tk 的 configure:业务属性走自绘,其余(宽度/位置)交给 Canvas"""
mine, rest = {}, {}
for k, v in kw.items():
if k in ('text', 'sub', 'fill', 'bg', 'fg', 'enabled',
'state', 'command', 'icon'):
mine[k] = v
else:
rest[k] = v
if mine:
self.configure_btn(**mine)
if rest or cnf:
tk.Canvas.configure(self, cnf, **rest)
config = configure
def set_text(self, text):
self._text = text
self._draw()
def set_enabled(self, on=True):
self._enabled = bool(on)
self._draw()
# -- 事件
def _on_configure(self, _e=None):
size = (self.winfo_width(), self.winfo_height())
if size != self._last_size:
self._last_size = size
self._draw()
def _on_enter(self, _e=None):
if self._enabled:
self._hover = True
self._draw()
def _on_leave(self, _e=None):
self._hover = False
self._draw()
def _on_press(self, _e=None):
if not self._enabled:
return
self._pressed = True
self._draw()
def _on_release(self, e=None):
if not self._enabled:
return
was = self._pressed
self._pressed = False
self._draw()
# 手指滑出按钮再松手 = 取消(平板上的常见预期)
if was and e is not None:
x, y = e.x, e.y
if 0 <= x <= self.winfo_width() and 0 <= y <= self.winfo_height():
if self._command:
self._command()
# -- 绘制
def _draw(self):
w, h = self.winfo_width(), self.winfo_height()
if w <= 1 or h <= 1:
return
self.delete('all')
if not self._enabled:
fill, fg = '#dde3ec', '#98a2b3'
elif self._pressed:
fill, fg = shade(self._fill, 0.86), self._fg
elif self._hover:
fill, fg = shade(self._fill, 1.06), self._fg
else:
fill, fg = self._fill, self._fg
r = self._radius
ph = rounded_photo(w, h, r, fill, self._surface,
outline=self._outline, ow=1)
if ph is not None:
self.create_image(0, 0, anchor='nw', image=ph)
self._ph = ph
else:
draw_round(self, 0, 0, w - 1, h - 1, r, fill,
outline=self._outline or fill)
dy = 1 if self._pressed else 0
cx = w // 2
has_sub = bool(self._sub)
if self._anchor == 'w':
cx = self._pad
if self._icon:
self.create_text(self._pad, h // 2 + dy, text=self._icon,
font=self._icon_font, fill=fg, anchor='w')
if has_sub:
ty = h // 2 - 9 + dy
else:
ty = h // 2 + dy
anchor = 'w' if self._anchor == 'w' else 'center'
x = (self._pad + (28 if self._icon else 0)) if anchor == 'w' else cx
self.create_text(x, ty, text=self._text, font=self._font, fill=fg,
anchor=anchor)
if has_sub:
self.create_text(x, ty + 20, text=self._sub, font=self._sub_font,
fill=_alpha_ink(fg), anchor=anchor)
def _alpha_ink(fg):
return '#dbe6f2' if fg == '#ffffff' else C.ink2
def _surface_of(w):
try:
return w.cget('bg')
except Exception:
try:
return w.master.cget('bg')
except Exception:
return C.bg
# ------------------------------------------------------------------ 卡片
class Card(tk.Frame):
"""白底圆角卡片:用 Canvas 画底,内容放 .body(普通 Frame)。"""
def __init__(self, parent, radius=18, pad=18, surface=None, fill=None,
border=None, **kw):
surface = surface or _surface_of(parent)
super().__init__(parent, bg=surface, highlightthickness=0, bd=0, **kw)
self._surface = surface
self._fill = fill or C.surface
self._radius = radius
self._border = border
self._canvas = tk.Canvas(self, bg=surface, highlightthickness=0, bd=0,
takefocus=0)
self._canvas.place(x=0, y=0, relwidth=1, relheight=1)
# 内容区用 pack + 内边距(place 的负宽高在部分 Tk 版本上算成 0,
# 表现就是卡片里的文字/按钮整块消失)
self.body = tk.Frame(self, bg=self._fill)
self.body.pack(fill='both', expand=True, padx=pad, pady=pad)
self.bind('<Configure>', self._redraw)
self._ph = None
def _redraw(self, _e=None):
w, h = self.winfo_width(), self.winfo_height()
if w <= 1 or h <= 1:
return
self._canvas.delete('all')
ph = rounded_photo(w, h, self._radius, self._fill, self._surface,
outline=self._border, ow=1)
if ph is not None:
self._canvas.create_image(0, 0, anchor='nw', image=ph)
self._ph = ph
else:
draw_round(self._canvas, 0, 0, w - 1, h - 1, self._radius,
self._fill)
def set_border(self, color):
self._border = color
self._redraw()
# ------------------------------------------------------------------ 分段导航
class Segmented(tk.Canvas):
"""胶囊分段控件:白色滑块跟着手指滑动,松手吸附到最近一段。"""
def __init__(self, parent, items, command=None, height=56, width=440,
surface=None, font=None, value=None, pad=5, anim_ms=220):
surface = surface or _surface_of(parent)
super().__init__(parent, bg=surface, highlightthickness=0, bd=0,
height=height, width=width, takefocus=0)
self._surface = surface
self._items = [(k, t) for k, t in items]
self._command = command
self._h = height
self._pad = pad
self._font = font or ('Microsoft YaHei', 15, 'bold')
self._idx = 0
self._thumb_x = None
self._anim_job = None
self._drag = None
# 增量重绘:画布项只建一次,拖动/动画只改坐标和颜色。
# 以前每帧 delete('all') + 重建,现场低端机上拖动明显发卡。
self._shape = None # (w, h, items) —— 决定要不要整建
self._id_sh = None # 滑块阴影图元
self._id_th = None # 滑块本体图元
self._id_txt = [] # 各段文字图元
self._paint_idx = None # 上次画文字时的选中段
self._motion_paint = None # 拖动重绘合并计时器
if value is not None:
for i, (k, _t) in enumerate(self._items):
if k == value:
self._idx = i
self.bind('<Configure>', self._on_configure)
self.bind('<ButtonPress-1>', self._on_press)
self.bind('<B1-Motion>', self._on_drag)
self.bind('<ButtonRelease-1>', self._on_release)
self.after(10, self._redraw)
# -- 接口
def index(self):
return self._idx
def key(self):
try:
return self._items[self._idx][0]
except Exception:
return None
def set_text(self, key, text):
for i, (k, _t) in enumerate(self._items):
if k == key:
self._items[i] = (k, text)
self._redraw()
def select(self, key_or_idx, animate=True, notify=False):
if isinstance(key_or_idx, int):
idx = key_or_idx
else:
idx = 0
for i, (k, _t) in enumerate(self._items):
if k == key_or_idx:
idx = i
idx = max(0, min(len(self._items) - 1, idx))
changed = (idx != self._idx)
self._idx = idx
if animate:
self._animate_to(self._seg_x(idx))
else:
self._thumb_x = self._seg_x(idx)
self._redraw()
if notify and self._command:
self._command(self._items[idx][0], idx)
return changed
# -- 几何
def _seg_w(self):
n = max(1, len(self._items))
return max(10, (self.winfo_width() - self._pad * 2) / float(n))
def _seg_x(self, idx):
return self._pad + idx * self._seg_w()
# -- 绘制
def _on_configure(self, _e=None):
self._thumb_x = self._seg_x(self._idx)
self._redraw(rebuild=True)
def _redraw(self, rebuild=False):
"""rebuild=True 才整建;平时只挪滑块/阴影、切文字颜色(增量)。"""
w, h = self.winfo_width(), self.winfo_height()
if w <= 2 or h <= 2:
return
shape = (w, h, tuple(self._items))
if rebuild or shape != self._shape:
self._build(w, h, shape)
return
seg_w = self._seg_w()
x = self._thumb_x + 3
if self._id_sh is not None:
self.coords(self._id_sh, x, 7)
if self._id_th is not None:
self.coords(self._id_th, x, 6)
if self._paint_idx != self._idx:
# 只在换段时才重刷文字(颜色 + 1px 下沉),拖动过程零文字开销
self._paint_idx = self._idx
for i, tid in enumerate(self._id_txt):
on = (i == self._idx)
self.coords(tid, self._pad + seg_w * (i + 0.5),
h // 2 + (1 if on else 0))
self.itemconfig(tid, fill=C.brand if on else C.ink2)
def _build(self, w, h, shape):
self.delete('all')
self._shape = shape
track_h = h - 2
ph = rounded_photo(w, track_h, track_h // 2, C.track, self._surface)
if ph is not None:
self.create_image(0, 1, anchor='nw', image=ph)
else:
draw_round(self, 0, 1, w - 1, track_h, track_h // 2, C.track)
seg_w = self._seg_w()
tw = seg_w - 6
th = h - 12
if self._thumb_x is None:
self._thumb_x = self._seg_x(self._idx)
x = self._thumb_x + 3
sh = rounded_photo(int(tw), th, th // 2, '#dfe5ee', C.track)
self._id_sh = None
if sh is not None:
self._id_sh = self.create_image(int(x), 7, anchor='nw', image=sh)
th_img = rounded_photo(int(tw), th, th // 2, '#ffffff', C.track)
self._id_th = None
if th_img is not None:
self._id_th = self.create_image(int(x), 6, anchor='nw',
image=th_img)
else:
draw_round(self, x, 6, x + tw, 6 + th, th // 2, '#ffffff')
self._id_txt = []
for i, (_k, t) in enumerate(self._items):
cx = self._pad + seg_w * (i + 0.5)
on = (i == self._idx)
self._id_txt.append(self.create_text(
cx, h // 2 + (1 if on else 0), text=t, font=self._font,
fill=C.brand if on else C.ink2))
self._paint_idx = self._idx
def _animate_to(self, target, ms=220):
if self._anim_job:
try:
self.after_cancel(self._anim_job)
except Exception:
pass
self._anim_job = None
start = self._thumb_x if self._thumb_x is not None else target
steps = max(1, int(ms / 16))
n = [0]
def tick():
n[0] += 1
k = n[0] / float(steps)
k = 1 - (1 - k) ** 3 # ease-out cubic
self._thumb_x = start + (target - start) * k
self._redraw()
if n[0] < steps:
self._anim_job = self.after(16, tick)
else:
self._thumb_x = target
self._anim_job = None
self._redraw()
tick()
# -- 手势
def _on_press(self, e):
self._drag = {'x0': e.x, 'start': self._thumb_x, 'moved': False}
if self._anim_job:
try:
self.after_cancel(self._anim_job)
except Exception:
pass
self._anim_job = None
def _on_drag(self, e):
if not self._drag:
return
dx = e.x - self._drag['x0']
if abs(dx) > 3:
self._drag['moved'] = True
seg_w = self._seg_w()
left = self._pad
right = self._pad + seg_w * (len(self._items) - 1)
x = max(left, min(right, self._drag['start'] + dx))
self._thumb_x = x
self._idx = int(round((x - self._pad) / seg_w))
self._idx = max(0, min(len(self._items) - 1, self._idx))
# 触摸屏的 motion 事件会一波波砸进来(120Hz+),直接每事件重绘
# 会把事件队列越压越多、滑块越拖越滞后。按 ~125fps 合并成
# 「有脏标记才画」,滑块始终贴着最新位置,弱机上也不发卡。
if self._motion_paint is None:
self._motion_paint = self.after(8, self._motion_paint_now)
def _motion_paint_now(self):
self._motion_paint = None
self._redraw()
def _on_release(self, e):
if not self._drag:
return
if not self._drag['moved']:
idx = int((e.x - self._pad) // self._seg_w())
else:
idx = self._idx
idx = max(0, min(len(self._items) - 1, idx))
self._drag = None
if self._motion_paint is not None:
# 拖动途中的挂起重绘交给动画去做,避免两次重绘打架
try:
self.after_cancel(self._motion_paint)
except Exception:
pass
self._motion_paint = None
changed = (idx != self._idx) or True
self._idx = idx
self._animate_to(self._seg_x(idx))
if self._command:
self._command(self._items[idx][0], idx)
# ------------------------------------------------------------------ 滑动开关
class Switch(tk.Canvas):
"""滑动开关:轨道变色 + 圆点滑过去。"""
def __init__(self, parent, value=False, command=None, surface=None,
width=64, height=36, on_color=None):
surface = surface or _surface_of(parent)
super().__init__(parent, bg=surface, highlightthickness=0, bd=0,
width=width, height=height, takefocus=0)
self._surface = surface
# 注意:不能用 self._w / self._h —— tkinter 的 _w 是窗口路径
self.sz_w = width
self.sz_h = height
self._on_color = on_color or C.brand
self._value = bool(value)
self._command = command
self._pos = 1.0 if value else 0.0
self._job = None
self.bind('<Button-1>', self._toggle)
self.after(10, self._redraw)
def get(self):
return self._value
def set(self, value, animate=True):
value = bool(value)
if value == self._value:
self._redraw()
return
self._value = value
if animate:
self._animate(1.0 if value else 0.0)
else:
self._pos = 1.0 if value else 0.0
self._redraw()
def _toggle(self, _e=None):
self._value = not self._value
self._animate(1.0 if self._value else 0.0)
if self._command:
self._command(self._value)
def _animate(self, target, ms=160):
if self._job:
try:
self.after_cancel(self._job)
except Exception:
pass
self._job = None
start = self._pos
steps = max(1, int(ms / 16))
n = [0]
def tick():
n[0] += 1
k = min(1.0, n[0] / float(steps))
k = 1 - (1 - k) ** 3
self._pos = start + (target - start) * k
self._redraw()
if n[0] < steps:
self._job = self.after(16, tick)
else:
self._pos = target
self._job = None
self._redraw()
tick()
def _redraw(self):
w, h = self.sz_w, self.sz_h
if w <= 2 or h <= 2:
return
self.delete('all')
# 轨道颜色:关=灰,开=品牌色,中间随位置插值
off = _hex_rgb('#cdd5e1')
on = _hex_rgb(self._on_color)
k = self._pos
col = '#%02x%02x%02x' % tuple(
int(off[i] + (on[i] - off[i]) * k) for i in range(3))
ph = rounded_photo(w, h, h // 2, col, self._surface)
if ph is not None:
self.create_image(0, 0, anchor='nw', image=ph)
self._ph = ph
else:
draw_round(self, 0, 0, w - 1, h - 1, h // 2, col)
d = h - 8
x = 4 + (w - d - 8) * k
kp = rounded_photo(d, d, d // 2, '#ffffff', col)
if kp is not None:
self.create_image(int(x), 4, anchor='nw', image=kp)
self._ph_knob = kp
else:
self.create_oval(x, 4, x + d, 4 + d, fill='#ffffff', outline='')
# ------------------------------------------------------------------ 步骤条
class StepsBar(tk.Canvas):
"""5 段圆角步骤条:已完成=绿、当前=琥珀、未到=灰。"""
def __init__(self, parent, steps, surface=None, height=44,
font=None, gap=6):
surface = surface or _surface_of(parent)
super().__init__(parent, bg=surface, highlightthickness=0, bd=0,
height=height, takefocus=0)
self._surface = surface
self._steps = list(steps)
self._h = height
self._gap = gap
self._font = font or ('Microsoft YaHei', 11)
self._idx = -1
self.bind('<Configure>', lambda e: self._redraw())
self.after(10, self._redraw)
def set_state(self, idx):
if idx == self._idx:
return
self._idx = idx
self._redraw()
def _redraw(self):
w, h = self.winfo_width(), self.winfo_height()
if w <= 2 or h <= 2:
return
self.delete('all')
n = max(1, len(self._steps))
gap = self._gap
sw = (w - gap * (n - 1)) / float(n)
for i, text in enumerate(self._steps):
if i < self._idx:
fill, fg = C.green_soft, C.green
elif i == self._idx:
fill, fg = '#fdeccd', '#8a5a11'
else:
fill, fg = '#f1f3f7', C.ink3
x = i * (sw + gap)
ph = rounded_photo(int(sw), h, h // 2, fill, self._surface)
if ph is not None:
self.create_image(int(x), 0, anchor='nw', image=ph)
if not hasattr(self, '_phs'):
self._phs = []
self._phs.append(ph)
self._phs = self._phs[-12:]
else:
draw_round(self, x, 0, x + sw, h - 1, h // 2, fill)
self.create_text(x + sw / 2, h // 2, text=text,
font=self._font, fill=fg)
# ------------------------------------------------------------------ 翻页容器
class Pager(tk.Frame):
"""横向页面容器:手指左右拖跟手移动,松手吸附到最近一页。
页面用 Canvas 内嵌窗口实现——滑动只是移动画布视口,不重建控件,
摄像头预览这种一直在刷新的页面也不会因为翻页而卡顿。
"""
def __init__(self, parent, bg=None, on_change=None):
bg = bg or _surface_of(parent)
super().__init__(parent, bg=bg)
self._bg = bg
self._cv = tk.Canvas(self, bg=bg, highlightthickness=0, bd=0,
takefocus=0)
self._cv.pack(fill='both', expand=True)
self._pages = []
self._items = []
self._idx = 0
self._on_change = on_change
self._anim = None
self._drag = None
self._cv.bind('<Configure>', self._on_configure)
# -- 接口
def add(self, page):
self._pages.append(page)
item = self._cv.create_window((0, 0), window=page, anchor='nw')
self._items.append(item)
self._sync_geom()
return page
def count(self):
return len(self._pages)
def index(self):
return self._idx
def show(self, idx, animate=True, notify=False):
if not self._pages:
return
idx = max(0, min(len(self._pages) - 1, idx))
changed = idx != self._idx
self._idx = idx
if animate:
self._animate_to(idx)
else:
self._set_frac(idx)
if notify and changed and self._on_change:
self._on_change(idx)
# -- 几何 / 滚动
def _on_configure(self, _e=None):
self._sync_geom()
def _sync_geom(self):
if not self._pages:
return
w = self._cv.winfo_width()
h = self._cv.winfo_height()
if w <= 2 or h <= 2:
return
for i, item in enumerate(self._items):
self._cv.coords(item, i * w, 0)
self._cv.itemconfigure(item, width=w, height=h)
n = len(self._pages)
self._cv.configure(scrollregion=(0, 0, w * n, h))
self._set_frac(self._idx)
def _set_frac(self, idx):
n = max(1, len(self._pages))
try:
self._cv.xview_moveto(idx / float(n))
except Exception:
pass
def _cur_frac(self):
try:
return self._cv.xview()[0]
except Exception:
return 0.0
def _animate_to(self, idx, ms=260):
if self._anim:
try:
self.after_cancel(self._anim)
except Exception:
pass
self._anim = None
n = max(1, len(self._pages))
start = self._cur_frac()
target = idx / float(n)
if abs(target - start) < 0.0005:
self._set_frac(idx)
return
steps = max(1, int(ms / 16))
k = [0]
def tick():
k[0] += 1
p = min(1.0, k[0] / float(steps))
p = 1 - (1 - p) ** 3
try:
self._cv.xview_moveto(start + (target - start) * p)
except Exception:
pass
if k[0] < steps:
self._anim = self.after(16, tick)
else:
self._anim = None
self._set_frac(idx)
tick()
# -- 手势(由 bind_swipe_to 绑到页面里的普通控件上)
def _press(self, e):
self._drag = {'x0': e.x_root, 'y0': e.y_root,
'frac': self._cur_frac(), 'axis': None, 'moved': False}
if self._anim:
try:
self.after_cancel(self._anim)
except Exception:
pass
self._anim = None
def _motion(self, e):
d = self._drag
if not d:
return
dx = e.x_root - d['x0']
dy = e.y_root - d['y0']
if d['axis'] is None:
if abs(dx) < 9 and abs(dy) < 9:
return
# 横向占优才翻页,否则交给页面自己的纵向滚动
d['axis'] = 'h' if abs(dx) > abs(dy) * 1.25 else 'v'
if d['axis'] == 'h':
d['moved'] = True
if d['axis'] != 'h':
return
w = max(1, self._cv.winfo_width())
n = max(1, len(self._pages))
frac = d['frac'] - dx / float(w * n)
frac = max(0.0, min((n - 1) / float(n), frac))
try:
self._cv.xview_moveto(frac)
except Exception:
pass
def _release(self, e):
d = self._drag
self._drag = None
if not d or d['axis'] != 'h':
return
n = max(1, len(self._pages))
frac = self._cur_frac() * n
base = int(round(frac))
dx = e.x_root - d['x0']
if abs(dx) > max(60, self._cv.winfo_width() * 0.16):
target = self._idx + (1 if dx < 0 else -1)
else:
target = base
target = max(0, min(n - 1, target))
self._idx = target
self._animate_to(target)
if self._on_change:
self._on_change(target)
def bind_swipe_to(widget, pager, skip=(), force=False):
"""把普通控件也接到翻页手势上(按钮/输入框/自绘画布除外)"""
if widget in skip:
return
if not force and isinstance(widget, (tk.Button, tk.Entry, tk.Text,
tk.Canvas)):
return
try:
if widget.cget('class') in ('TButton', 'TEntry', 'TSpinbox'):
return
except Exception:
pass
try:
widget.bind('<ButtonPress-1>', pager._press, add='+')
widget.bind('<B1-Motion>', pager._motion, add='+')
widget.bind('<ButtonRelease-1>', pager._release, add='+')
except Exception:
pass
def bind_swipe_recursive(widget, pager, depth=0):
"""整块页面(含子控件)都能滑动翻页:一次绑定,之后动态加的子控件不生效"""
if depth > 6:
return
bind_swipe_to(widget, pager)
for ch in widget.winfo_children():
bind_swipe_recursive(ch, pager, depth + 1)
# ------------------------------------------------------------------ 触摸滚动
class TouchScroll:
"""手指拖动滚动 + 惯性;纵向手势自己吃掉,横向让给翻页。"""
def __init__(self, canvas, min_content=0):
self.cv = canvas
self.moved = False
self._drag = None
self._anim = None
self._min = min_content
canvas.configure(yscrollincrement=1)
def attach(self, widget, allow_click=True):
try:
widget.bind('<ButtonPress-1>', self._press, add='+')
widget.bind('<B1-Motion>', self._motion, add='+')
widget.bind('<ButtonRelease-1>', self._release, add='+')
widget.bind('<MouseWheel>', self._wheel, add='+')
if allow_click:
# 拖动后松手不触发卡片点选:用标记让调用方自己判断
pass
except Exception:
pass
def attach_tree(self, widget, depth=0):
if depth > 6:
return
self.attach(widget)
for ch in widget.winfo_children():
self.attach_tree(ch, depth + 1)
# -- 尺寸
def _geom(self):
# 内容高度只在重建卡片/改列数/筛选时变,滚动期间不会变。原来每次
# 按下、每次滚轮都 bbox('all') 查一遍(上百个卡片项),弱机上就是
# 那几毫秒一卡一卡。缓存 0.5 秒,重建后最多半秒自愈。
now = _time.monotonic()
c = getattr(self, '_gc', None)
if c and now - c[2] < 0.5:
return c[0], c[1]
try:
bbox = self.cv.bbox('all') or (0, 0, 0, 0)
total = max(1, bbox[3] - bbox[1])
view = max(1, self.cv.winfo_height())
except Exception:
return 1, 1
self._gc = (total, view, now)
return total, view
def _press(self, e):
self._stop()
self.moved = False
# 拖动期间缓存内容高度/视口高度,别每个 motion 都去 bbox('all');
# 待办名单一长,这个查询本身就吃好几毫秒,拖起来发卡。
total, view = self._geom()
self._drag = {'y0': e.y_root, 'x0': e.x_root,
'frac': self.cv.yview()[0], 'axis': None,
't': e.time or 0, 'last_y': e.y_root,
'v': 0.0, 'total': total, 'view': view,
'target': None, 'painted_at': 0.0}
def _motion(self, e):
d = self._drag
if not d:
return
dy = e.y_root - d['y0']
dx = e.x_root - d['x0']
total, view = d['total'], d['view']
if total <= view + 2:
return
if d['axis'] is None:
if abs(dx) < 9 and abs(dy) < 9:
return
d['axis'] = 'v' if abs(dy) >= abs(dx) * 0.8 else 'h'
if d['axis'] != 'v':
return
if abs(dy) > 6:
self.moved = True # 拖动滚名单时不要顺手把卡片选中
frac = d['frac'] - dy / float(total)
frac = max(0.0, min(1.0 - view / float(total), frac))
# v1.0.49:触摸屏一秒能发 100~200 个 Motion,每个都滚一次就把界面
# 拖垮(每滚一次 Tk 要重画整块卡片区)。这里限帧,中间的
# 事件只记位置不重画;松手时再补最后一下。
# v1.0.56:16ms→24ms。现场 i5-4200U 上滚一帧本身就要 20~25ms,
# 按 60fps 限反而每帧都堆在队列里,松手后还要把积压的帧画完,
# 手感是「拖不动、一松手猛跳一下」。42fps 才是这台机器跟得上的节奏。
d['target'] = frac
now = _time.monotonic()
if now - d.get('painted_at', 0.0) >= 0.024:
d['painted_at'] = now
try:
self.cv.yview_moveto(frac)
except Exception:
pass
# 速度只用来算惯性:事件不带时间戳(time=0,部分触摸驱动/合成事件
# 就是这样)时 dt 会变成 1ms,速度虚高几十倍,松手直接甩到底。
# 真手指最快也就 3~5 px/ms,夹到 6 以内,异常值一律当 0。
now_t = int(getattr(e, 'time', 0) or 0)
if now_t and d['t'] and now_t > d['t']:
dt = now_t - d['t']
v = (e.y_root - d['last_y']) / float(dt) # px/ms
d['v'] = max(-6.0, min(6.0, v))
d['t'] = now_t
else:
d['v'] = 0.0
d['last_y'] = e.y_root
def _release(self, _e=None):
d = self._drag
self._drag = None
if not d or d.get('axis') != 'v':
return
# 补画最后一下(拖动时限了帧率,末位可能是没画出来的那帧)
if d.get('target') is not None:
try:
self.cv.yview_moveto(d['target'])
except Exception:
pass
v = d.get('v') or 0.0
if abs(v) < 0.35:
return
total, view = self._geom()
if total <= view + 2:
return
self._fling(v, total, view)
def _fling(self, v, total, view):
frac = self.cv.yview()[0]
step = 0.0
# 24ms 一帧(和拖动限帧一致):衰减按「同样减速度」换算,
# 16ms 时的 0.90 → 24ms 约 0.86,甩出去的距离才跟手一致
gap = 24
def tick():
nonlocal frac, v
v *= 0.86
frac = frac - v * gap / float(total)
frac = max(0.0, min(1.0 - view / float(total), frac))
try:
self.cv.yview_moveto(frac)
except Exception:
return
if abs(v) > 0.05:
self._anim = self.cv.after(gap, tick)
else:
self._anim = None
if abs(step) < 1:
tick()
def _wheel(self, e):
total, view = self._geom()
if total <= view + 2:
return
d = -1 if getattr(e, 'delta', 0) > 0 else 1
# v1.0.56:原来一格只走 3px(名单总高 5595px 时是 0.1%),滚一格几乎
# 看不出动,现场连滚十几下才走一屏,感受就是「滑不动」。改成一格
# 走四分之一屏,靠手感接近网页。
step = max(3, int(view * 0.25))
try:
self.cv.yview_scroll(d * step, 'units')
except Exception:
pass
return 'break'
def _stop(self):
if self._anim:
try:
self.cv.after_cancel(self._anim)
except Exception:
pass
self._anim = None
class TapGate:
"""按下→松手之间手指有没有挪过:挪过就是「拖动」,不算「点」。
为什么要单独一个:`TouchScroll.moved` 只在「内容比视口高、且纵向拖动」
时才置位,卡片区内容装得下、或者斜着划一下,它一直是 False ——
于是滑名单松手就点中了卡片(确认状态下直接打一张标签)。
这里只认几何位移,和滚动条、内容高度都无关:
· 位移超过 tol(默认 12px)→ 不算点,滚名单/滑下拉都不选中;
· 按下和松手不在同一条(key 不同,例如从这张卡滑到那张卡)→ 不算点;
· 按住超过 max_ms(默认 900ms)→ 不算点(长按多半是想拖)。
一个实例可以共给整片卡片区:同一时刻只可能有一根手指按着。
"""
def __init__(self, tol=12, max_ms=900):
self.tol = tol
self.max_ms = max_ms
self._key = None
self._x = 0.0
self._y = 0.0
self._t = 0
self._ok = False
def press(self, e, key=None):
try:
self._x = float(e.x_root)
self._y = float(e.y_root)
except Exception:
self._x = self._y = 0.0
self._t = int(getattr(e, 'time', 0) or 0)
self._key = key
self._ok = True
def motion(self, e):
if not self._ok:
return
try:
dx = abs(float(e.x_root) - self._x)
dy = abs(float(e.y_root) - self._y)
except Exception:
return
if dx > self.tol or dy > self.tol:
self._ok = False
def release(self, e=None, key=None):
"""松手:是「点」就返回 True。无论结果如何都会清掉本次状态。"""
ok = self._ok
self._ok = False
if not ok:
return False
if key is not None and self._key is not None and key != self._key:
return False # 从别处滑过来松手,不算点这条
t = int(getattr(e, 'time', 0) or 0)
if t and self._t and (t - self._t) > self.max_ms:
return False
return True
def bind_drag_scroll(canvas, widgets=()):
"""便捷函数:给 canvas 建一个 TouchScroll 并挂到给定控件上"""
ts = TouchScroll(canvas)
for w in widgets:
ts.attach(w)
return ts