Files
Ubuntu 5d4f2d1ba3 feat(1.0.76): 识别记录留档(本地 YOLO + 云端)
来自 秤端源码-v1.0.76:flow 生成 recognition_audit(本地候选/耗时 + 云端结果)并随 review_queue 送审;assist/local_cls 记录本地推理;审核后台可查;版本/安装包 1.0.76。保留 1.0.71-1.0.75 既有修复与文档;config.json/data/models 未入库。
2026-12-03 17:05:19 +08:00

7420 lines
332 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:左=流程指示+预览+重量,右=模式/操作/日志。
只订阅 FlowEngine 事件并渲染,不含业务逻辑。
"""
import os
import json
import queue
import sys
import threading
import datetime
import time
import tkinter as tk
from tkinter import font as tkfont
from tkinter import messagebox, ttk
import cv2
from PIL import Image, ImageTk
from core.flow import FlowEngine
from core.matching import engine as M
from core.storage import atomic
from core.evidence import retention
from ui.tablet import (C, Card, Segmented, StepsBar, Switch, TapGate,
TouchButton, TouchScroll, rounded_photo, shade,
_hex_rgb)
class _BoolVar:
"""把 Switch 包成 BooleanVar 的样子(.get()),旧代码不用改"""
def __init__(self, sw):
self._sw = sw
def get(self):
return bool(self._sw.get())
def set(self, v):
self._sw.set(v)
APP_VERSION = '1.0.76'
# 待办卡外框粗细:所有卡统一这一个值,选中/确认只换颜色。
# Tk 的 highlight 环画在控件外侧,粗细一变控件尺寸就变,grid 会把整屏
# 卡片重排 —— 现场“点一下界面就抖”就是这么来的。
CARD_HL = 4
# AI 选中 / 待确认待办卡的红色高亮(分拣台与入库台共用)
CARD_FOCUS_BORDER = '#dc2626'
CARD_FOCUS_BG = '#fbe9e9'
FONT_BIG = ('Microsoft YaHei', 14)
FONT_HUGE = ('Microsoft YaHei', 38, 'bold')
FONT_BTN = ('Microsoft YaHei', 13, 'bold')
FONT_MID = ('Microsoft YaHei', 12)
ST_STATE_CN = {'IDLE': '待机', 'WEIGHING': '称重中',
'CAPTURE': '抓拍中', 'RECOGNIZE': 'AI 识别中',
'MATCH': '匹配中', 'MANUAL': '人工确认',
'CONFIRM': '等确认',
'SUBMIT': '提交中', 'PRINT': '打印中',
'DONE': '完成', 'COUNT_CAPTURE': '免称重抓拍',
'COUNT_RECOGNIZE': '免称重识别',
'COUNT_CONFIRM': '免称重核对'}
STEP_NAMES = ['① 称重稳定', '② 抓拍', '③ AI识别', '④ 匹配', '⑤ 提交打印']
STEP_STATE = {'IDLE': -1, 'WEIGHING': 0, 'CAPTURE': 1, 'RECOGNIZE': 2,
'MATCH': 3, 'MANUAL': 3, 'CONFIRM': 3,
'SUBMIT': 4, 'PRINT': 4, 'DONE': 4,
# 免称重(拍照计数):跳过①称重,从②抓拍开始,后面一样
'COUNT_CAPTURE': 1, 'COUNT_RECOGNIZE': 2, 'COUNT_CONFIRM': 3}
_TIP_IFACE = {}
def _tip_iface():
"""Windows 触摸键盘的 ITipInvocation 接口(只定义一次)。
这是 Win10/11 上「把常驻的 TabTip 窗口真正显示出来」的官方方式;
直接 Popen TabTip.exe 在进程已常驻时毫无效果。
"""
if not _TIP_IFACE:
from ctypes import c_void_p
from comtypes import GUID, COMMETHOD, HRESULT, IUnknown
class ITipInvocation(IUnknown):
_iid_ = GUID('{37c994e7-432b-4834-a2f7-dce1f13b834b}')
_methods_ = [COMMETHOD([], HRESULT, 'Toggle',
(['in'], c_void_p, 'hwnd'))]
_TIP_IFACE['iface'] = ITipInvocation
_TIP_IFACE['clsid'] = GUID('{4CE576FA-83DC-4F88-951C-9D0782B4E376}')
return _TIP_IFACE['iface'], _TIP_IFACE['clsid']
def load_config(path='config.json'):
return atomic.read_json(path) or {}
def save_config(cfg, path='config.json'):
atomic.write_json(path, cfg)
def _paginate_by_height(items, ncols, budget, height_of):
"""按实际行高分页:每页累计高度不超过 budget。
与固定「一页几行」相比:一页里有高卡(带黄底徽标)时少吃一行,
都是矮卡时能多放一行,而且永远不会把最底行排出视口。
height_of(kind, obj) 返回这一项单独占的高度(含上下 gap);
卡片行的实际高度取本行最高那张。
"""
pages, cur = [], []
used = 0.0
col = 0 # 本行已经摆了几张卡
row_h = 0.0 # 本行最高卡
def close_row():
nonlocal used, col, row_h
if col:
used += row_h
col, row_h = 0, 0.0
def new_page():
nonlocal cur, used, col, row_h
close_row()
if cur:
pages.append(cur)
cur, used, col, row_h = [], 0.0, 0, 0.0
seq = list(items)
for idx, (kind, obj) in enumerate(seq):
h = float(height_of(kind, obj))
if kind == 'hdr':
close_row()
# 页尾孤标题:连后面那张卡都放不下时,标题也挪到下一页
nxt = 0.0
if idx + 1 < len(seq) and seq[idx + 1][0] == 'card':
nxt = float(height_of(*seq[idx + 1]))
if cur and (used + h > budget
or (nxt and used + h + nxt > budget)):
new_page()
cur.append((kind, obj))
used += h
continue
if col == 0:
if cur and used + h > budget:
# 页上只有分组标题时不能把卡挤到下一页 —— 那会摆出一个
# 只有页头、没有卡的空白页
if not (len(cur) == 1 and cur[0][0] == 'hdr'):
new_page()
row_h = h
else:
row_h = max(row_h, h)
cur.append((kind, obj))
col += 1
if col >= ncols:
used += row_h
col, row_h = 0, 0.0
close_row()
if cur:
pages.append(cur)
return pages or [[]]
def _paginate_items(items, ncols, cap_rows):
"""把 (kind, obj) 序列切成若干页:每页占用的网格行数 ≤ cap_rows。
kind='hdr' 的分组标题独占一行(上一组卡片没摆满一行时先把那行收掉,
标题从下一行开始);kind='card' 的卡片每行 ncols 张。
标题孤悬页尾(它后面一张卡都没放上)看着像空行,挤不下时挪到
下一页开头。页容量 cap_rows 由「视口高 ÷ 实测卡高」得来,见
App._layout_cards。
"""
pages, cur = [], []
rows, col = 0, 0
def flush():
nonlocal cur, rows, col
if cur:
pages.append(cur)
cur, rows, col = [], 0, 0
for kind, obj in items:
if kind == 'hdr':
extra = (1 if col > 0 else 0) + 1
if rows + extra > cap_rows and cur:
flush()
if col > 0:
rows += 1
col = 0
cur.append((kind, obj))
rows += 1
continue
if col == 0:
if rows + 1 > cap_rows and cur:
# 新起一行就超页:页尾若刚好是分组标题,标题挪去下一页
if cap_rows >= 2 and cur[-1][0] == 'hdr':
hdr = cur.pop()
flush()
cur.append(hdr)
rows = 1
else:
flush()
rows += 1
cur.append((kind, obj))
col += 1
if col >= ncols:
col = 0
flush()
return pages or [[]]
class App:
def __init__(self, root):
self.root = root
self.cfg = load_config()
root.title('入库分拣工作站')
root.configure(bg='#f2f4f7')
# 窗口尺寸:设计基准 1440×900。
# ui.mode='fullscreen' → 全屏并按屏幕等比缩放
# ui.mode='fixed' → 按 width/height 固定居中(不超过工作区)
# 只要屏幕装得下设计基准(现场 19 寸 1440×900 正好等于基准)就默认
# 铺满:固定 1440×900 的窗口摆在同样 1440×900 的屏幕上,y=0 会让
# 底部 40px 压在任务栏下面,状态卡最后一行和结果条直接看不见。
# 真要留任务栏就设 ui.fit_screen=false(或 ui.mode='window')。
ui_cfg = self.cfg.get('ui', {}) or {}
mode = str(ui_cfg.get('mode', 'fixed')).lower()
DESIGN_W, DESIGN_H = 1440, 900
sw0 = root.winfo_screenwidth() or DESIGN_W
sh0 = root.winfo_screenheight() or DESIGN_H
wa_w, wa_h = self._work_area() or (sw0, sh0)
fit = bool(ui_cfg.get('fit_screen', True)) and \
mode not in ('window', 'fixed_small')
fits = sw0 + 8 >= DESIGN_W and sh0 + 8 >= DESIGN_H
if mode != 'fullscreen' and fit and \
(fits or sw0 * sh0 >= DESIGN_W * DESIGN_H * 1.5):
mode = 'fullscreen'
self._auto_full = True
if mode == 'fullscreen':
root.attributes('-fullscreen', True)
root.bind('<Escape>', lambda e: root.attributes(
'-fullscreen', False))
# 宽高都参与缩放:只按高度算,4:3 / 窄屏会被撑出去
sw = root.winfo_screenwidth() or DESIGN_W
sh = root.winfo_screenheight() or DESIGN_H
self.S = max(0.75, min(2.0, min(sw / DESIGN_W, sh / DESIGN_H)))
else:
root.attributes('-fullscreen', False)
w = int(ui_cfg.get('width', DESIGN_W))
h = int(ui_cfg.get('height', DESIGN_H))
sw = root.winfo_screenwidth() or DESIGN_W
sh = root.winfo_screenheight() or DESIGN_H
# 不超出可用工作区:否则底部会被任务栏压住
w = max(1024, min(w, wa_w))
h = max(700, min(h, wa_h))
x = max(0, (sw - w) // 2)
y = max(0, (sh - h) // 2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root.resizable(False, False)
self.S = max(0.75, min(2.0, min(w / DESIGN_W, h / DESIGN_H)))
# 无边框样式:去掉系统标题栏/边框(config ui.borderless=false 回退)。
# 拖动、最小化、关闭走自绘顶栏(登录页顶部条 / 主界面顶栏)
if bool(ui_cfg.get('borderless', True)):
self._apply_frameless(root, w, h)
self._dev_tick = 0
self.q = queue.Queue()
# v1.0.52:日志落盘走后台线程(见 _log_writer),界面线程只管入队
self._logq = queue.Queue(maxsize=5000)
self._log_stop = False
threading.Thread(target=self._log_writer, daemon=True).start()
self.engine = FlowEngine(self.cfg, lambda ev, p: self.q.put((ev, p)))
self._tkimg = None
self._confirm_top = None
self._count_top = None # 免称重确认页
self._fit_font = None # _fit_text 的字体测宽缓存
self._btn_newitem = None # 「这是一件新货」按钮(重复收货防护用)
self._last_input_w = None # 屏幕键盘的写入目标
self._osk_win = None
# 登录态:先出登录页,登录成功才构建入库/分拣主界面
self.ready = False
self._logging_in = False
self._login_pwd = ''
self._ka_started = False
acc = self.cfg.get('account', {}) or {}
role = str(acc.get('role') or 'picker').strip().lower()
# 工位用本地词(picking/inspection),config 里存的是服务端 role_type
self._login_role = 'inspection' \
if role in ('inspector', 'inspection') else 'picking'
self._build_login()
self.root.after(120, self._poll)
self.root.after(90, self._poll_preview)
self.root.protocol('WM_DELETE_WINDOW', self._quit)
# v1.0.49:记「用户正在拖/滚」的时刻。拖动时暂停预览刷新与相机解码,
# 把 CPU/重绘让给名单滚动(现场一拖就顿的主因之一)。
self._motion_at = 0.0
for seq in ('<B1-Motion>', '<MouseWheel>', '<Button-4>', '<Button-5>'):
try:
self.root.bind(seq, self._note_motion, add='+')
except Exception:
pass
# 记录最后一个拿到焦点的输入框,屏幕键盘才知道往哪写
self.root.bind_all('<FocusIn>', self._on_focus_in, add='+')
# 所有输入框点一下就弹内置键盘(含对话框/确认页里的框):
# 用类绑定,后面动态创建的 Entry 也自动生效,不用逐个改
for cls in ('Entry', 'TEntry', 'Text'):
try:
self.root.bind_class(cls, '<Button-1>', self._kb_on_click,
add='+')
except Exception:
pass
# ------------------------------------------------------ 桌面可用区域
def _work_area(self):
"""桌面可用区域(去掉任务栏)→ (宽, 高);拿不到返回 None。
1440×900 的机器任务栏占 40px,按屏幕高度开窗就会把底部压在
任务栏下面,所以定尺寸必须先问系统要 rcWork。
"""
try:
import ctypes
from ctypes import wintypes
class RECT(ctypes.Structure):
_fields_ = [('left', wintypes.LONG), ('top', wintypes.LONG),
('right', wintypes.LONG), ('bottom', wintypes.LONG)]
r = RECT()
if ctypes.windll.user32.SystemParametersInfoW(
0x0030, 0, ctypes.byref(r), 0):
w = int(r.right - r.left)
h = int(r.bottom - r.top)
if w > 400 and h > 300:
return (w, h)
except Exception:
pass
return None
# ------------------------------------------------------ 无边框窗口
def _apply_frameless(self, root, want_w=0, want_h=0):
"""无边框样式:用 Tk 自己的 overrideredirect 关掉系统标题栏和边框。
为什么不用 Win32 去裁 WS_CAPTION:Tk 仍按"有装饰"算尺寸,一收到
尺寸变化又把非客户区补回去,窗口会一轮轮变大(1456→1472→1488…)。
overrideredirect 让 Tk 自己知道没有装饰,geometry 就是物理尺寸。
代价与补法:
· 任务栏图标会消失 → 补 WS_EX_APPWINDOW(_frameless_taskbar)
· Alt+F4 失效 → 顶栏有 ✕;最小化走 _minimize(ShowWindow)
· 窗口不能拖动 → 顶栏自绘拖动(_bind_drag)
"""
self._fl_size = (int(want_w), int(want_h))
try:
root.overrideredirect(True)
if want_w and want_h:
root.geometry('%dx%d' % (want_w, want_h))
except Exception:
pass
# overrideredirect 会重建窗口,句柄得之后再取,所以延迟补任务栏
for delay in (30, 200, 800):
try:
root.after(delay, self._frameless_taskbar)
except Exception:
pass
def _frameless_taskbar(self):
"""把任务栏图标补回来(overrideredirect 后默认没有,Alt+Tab 也找不到)"""
try:
import ctypes
u = ctypes.windll.user32
self.root.update_idletasks()
hwnd = u.GetParent(self.root.winfo_id())
if not hwnd:
return
GWL_EXSTYLE = -20
WS_EX_APPWINDOW = 0x00040000
WS_EX_TOOLWINDOW = 0x00000080
ex = u.GetWindowLongW(hwnd, GWL_EXSTYLE)
want = (ex | WS_EX_APPWINDOW) & ~WS_EX_TOOLWINDOW
if ex != want:
u.SetWindowLongW(hwnd, GWL_EXSTYLE, want)
except Exception:
pass
def _minimize(self):
"""最小化:overrideredirect 窗口 root.iconify 不生效,走 ShowWindow"""
try:
import ctypes
u = ctypes.windll.user32
hwnd = u.GetParent(self.root.winfo_id())
if hwnd:
u.ShowWindow(hwnd, 6) # SW_MINIMIZE
return
except Exception:
pass
try:
self.root.iconify()
except Exception:
pass
def _bind_drag(self, widget):
"""顶栏空白处按住拖动窗口(无边框后窗口移动全靠它)"""
widget.bind('<Button-1>', self._drag_start, add='+')
widget.bind('<B1-Motion>', self._drag_move, add='+')
def _drag_start(self, e):
self._drag_off = (e.x_root - self.root.winfo_x(),
e.y_root - self.root.winfo_y())
def _drag_move(self, e):
off = getattr(self, '_drag_off', None)
if off:
self.root.geometry('+%d+%d' % (e.x_root - off[0],
e.y_root - off[1]))
def _win_btn(self, parent, text, cmd, hover_bg):
"""自绘窗口控制按钮(— 最小化 / ✕ 关闭),贴角无边框样式"""
b = tk.Label(parent, text=text, font=self._font(13, 'bold'),
bg='#185fa5', fg='#b5d4f4', width=4, cursor='hand2')
b.bind('<Button-1>', lambda e: cmd())
b.bind('<Enter>', lambda e: b.config(bg=hover_bg, fg='white'))
b.bind('<Leave>', lambda e: b.config(bg='#185fa5', fg='#b5d4f4'))
return b
# ------------------------------------------------------------ 登录页
def _build_login(self):
"""平板登录页:左侧品牌面 + 右侧大号表单。
触摸尺寸:输入框 60 高、工位分段 52 高、登录按钮 68 高,
记住密码改成滑动开关(点一下整条都能切,不用瞄准小方框)。
"""
px, font = self._px, self._font
root = self.root
self.ready = False
self._logging_in = False
# 登录页回到产品名(退出登录/首次启动时把“分拣工作站”之类复位)
try:
root.title('入库分拣工作站 - 登录')
except Exception:
pass
for w in root.winfo_children():
w.destroy()
bg = tk.Frame(root, bg=C.bg)
bg.pack(fill='both', expand=True)
# ---- 左侧品牌面(渐变 + 文案)----
panel = tk.Canvas(bg, bg=C.brand, highlightthickness=0, bd=0,
width=px(600))
panel.pack(side='left', fill='y')
self._login_panel = panel
def paint_panel(_e=None):
w = panel.winfo_width()
h = panel.winfo_height()
if w <= 4 or h <= 4:
return
panel.delete('all')
top = _hex_rgb('#123f6b')
bot = _hex_rgb('#2570bd')
step = max(2, h // 160) # 160 条渐变带足够平滑,也不拖慢启动
y = 0
while y < h:
k = y / float(h)
col = '#%02x%02x%02x' % tuple(
int(top[i] + (bot[i] - top[i]) * k) for i in range(3))
panel.create_rectangle(0, y, w, y + step + 1, fill=col,
outline=col)
y += step
x = px(64)
panel.create_text(x, px(120), anchor='nw', text='入库分拣',
font=font(40, 'bold'), fill='white')
panel.create_text(x, px(186), anchor='nw', text='工作站',
font=font(40, 'bold'), fill='#bcd9f5')
panel.create_text(x, px(262), anchor='nw',
text='称重 · 拍照 · AI 识别 · 打印标签,一屏完成',
font=font(15), fill='#d6e7fa')
feats = [('①', '放货上秤,重量稳定自动抓拍'),
('②', 'AI 认出商品,比对当前待办名单'),
('③', '提交、打印标签,取走即完成'),
('④', '有疑问的自动转人工,绝不猜')]
fy = px(360)
for ic, txt in feats:
panel.create_text(x, fy, anchor='nw', text=ic,
font=font(16, 'bold'), fill='#8fc0ee')
panel.create_text(x + px(40), fy + px(1), anchor='nw',
text=txt, font=font(14), fill='#e6f0fb')
fy += px(46)
panel.create_text(x, h - px(56), anchor='nw',
text='v%s · 平板版' % APP_VERSION,
font=font(11), fill='#9dc2e8')
panel.bind('<Configure>', paint_panel)
self._bind_drag(panel)
# ---- 右侧表单 ----
right = tk.Frame(bg, bg=C.surface)
right.pack(side='left', fill='both', expand=True)
self._bind_drag(right)
# 无边框窗口控制(右上角)
TouchButton(right, text='✕', command=self._quit, fill='#f1f4f9',
fg=C.ink2, height=px(40), width=px(40), radius=px(20),
font=font(14, 'bold'), surface=C.surface).place(
relx=1.0, x=-px(22), y=px(18), anchor='ne', width=px(40),
height=px(40))
TouchButton(right, text='—', command=self._minimize, fill='#f1f4f9',
fg=C.ink2, height=px(40), width=px(40), radius=px(20),
font=font(14, 'bold'), surface=C.surface).place(
relx=1.0, x=-px(70), y=px(18), anchor='ne', width=px(40),
height=px(40))
form = tk.Frame(right, bg=C.surface, width=px(460))
form.place(relx=0.5, rely=0.5, anchor='center', width=px(460))
tk.Label(form, text='欢迎回来', font=font(30, 'bold'), bg=C.surface,
fg=C.ink).pack(anchor='w')
tk.Label(form, text='请使用工位账号登录后开始作业', font=font(13),
bg=C.surface, fg=C.ink2).pack(anchor='w', pady=(px(4), px(24)))
# ---- 工位(分段滑块)----
tk.Label(form, text='选择工位', font=font(12, 'bold'), bg=C.surface,
fg=C.ink2).pack(anchor='w')
self.seg_role = Segmented(
form, [('picking', '分拣 · 打标签'),
('inspection', '入库 · 不打标签')],
command=lambda k, i: self._pick_login_role(k), height=px(54),
surface=C.surface, font=font(14, 'bold'))
self.seg_role.pack(fill='x', pady=(px(8), px(20)))
self.btn_role_pick = None
self.btn_role_ins = None
# ---- 账号 / 密码 ----
tk.Label(form, text='账号', font=font(12, 'bold'), bg=C.surface,
fg=C.ink2).pack(anchor='w')
f1 = Card(form, radius=px(14), pad=px(1), height=px(60),
border='#dfe6ef')
f1.pack(fill='x', pady=(px(8), px(16)))
f1.pack_propagate(False)
self.ent_user = self._login_entry(f1.body, label='账号')
self.ent_user.pack(fill='both', expand=True, padx=px(16), pady=px(10))
tk.Label(form, text='密码', font=font(12, 'bold'), bg=C.surface,
fg=C.ink2).pack(anchor='w')
f2 = Card(form, radius=px(14), pad=px(1), height=px(60),
border='#dfe6ef')
f2.pack(fill='x', pady=(px(8), px(14)))
f2.pack_propagate(False)
self.ent_pwd = self._login_entry(f2.body, secret=True, label='密码')
self.ent_pwd.pack(fill='both', expand=True, padx=px(16), pady=px(10))
# ---- 记住密码(滑动开关)----
opt = tk.Frame(form, bg=C.surface)
opt.pack(fill='x', pady=(0, px(20)))
acc = self.cfg.get('account', {}) or {}
self.switch_remember = Switch(
opt, value=bool(acc.get('password')),
command=lambda v: self._remember_toggle(v), surface=C.surface,
width=px(60), height=px(34))
self.switch_remember.pack(side='left')
tk.Label(opt, text='记住密码', font=font(13), bg=C.surface,
fg=C.ink2).pack(side='left', padx=(px(10), 0))
self.var_remember = _BoolVar(self.switch_remember)
TouchButton(opt, text='屏幕键盘', command=self._show_osk,
fill='#eef2f7', fg=C.ink2, height=px(42), width=px(104),
radius=px(21), font=font(12), surface=C.surface).pack(
side='right')
# ---- 登录 ----
self.btn_login = TouchButton(
form, text='登 录', command=self._do_login, fill=C.brand,
fg='white', height=px(68), radius=px(18), font=font(20, 'bold'),
surface=C.surface)
self.btn_login.pack(fill='x')
self.lbl_login_msg = tk.Label(
form, text='', font=font(12), bg=C.surface, fg=C.red,
anchor='w', justify='left', wraplength=px(450))
self.lbl_login_msg.pack(fill='x', pady=(px(10), px(4)))
# ---- 页脚 ----
# 登录前就能换服务器:换机房/切备用机不用改 config.json 再重启。
# 分两行:地址单独一行(长短不影响按钮),按钮放第二行,防止
# 地址一长就把「修改」挤成半截字。
foot = tk.Frame(form, bg=C.surface)
foot.pack(fill='x', pady=(px(12), 0))
self.lbl_login_srv = tk.Label(foot, text='', font=font(10),
bg=C.surface, fg=C.ink3,
anchor='w', justify='left',
cursor='hand2')
self.lbl_login_srv.pack(fill='x')
self.lbl_login_srv.bind('<Button-1>', lambda e: self._edit_server())
frow = tk.Frame(foot, bg=C.surface)
frow.pack(fill='x', pady=(px(8), 0))
tk.Button(frow, text='修改服务器地址', font=font(10), bd=0,
bg='#eef2f7', fg=C.brand, activebackground='#e3e9f2',
activeforeground=C.brand, cursor='hand2',
padx=px(12), pady=px(4),
command=self._edit_server).pack(side='left')
tk.Button(frow, text='退出程序', font=font(10), bd=0, bg=C.surface,
fg=C.ink3, activebackground=C.surface,
cursor='hand2', command=self._quit).pack(side='right')
self._refresh_login_srv()
# 预填上次账号
if acc.get('username'):
self.ent_user.insert(0, str(acc['username']))
if acc.get('password') and self.switch_remember.get():
self.ent_pwd.insert(0, str(acc['password']))
self._pick_login_role(self._login_role)
if self.ent_user.get():
self.ent_pwd.focus_set()
else:
self.ent_user.focus_set()
self.ent_user.bind(
'<Return>', lambda e: (self.ent_pwd.focus_set(), 'break')[1])
self.ent_pwd.bind('<Return>', self._do_login)
def _remember_toggle(self, on):
"""滑动开关:关掉就把已保存的密码从配置里删掉"""
if not on:
try:
(self.cfg.get('account') or {})['password'] = ''
except Exception:
pass
# ------------------------------------------------- 登录页改服务器地址
def _refresh_login_srv(self):
"""登录页页脚显示当前服务器(改完地址立即刷新,不用重启)
地址太长就中间打点:页脚是一行文字,撑出去会把第二行的按钮
顶出可视区(现场就遇到过「修改」只剩半个字)。完整地址在
修改窗口和 config.json 里都能看到。
"""
lbl = getattr(self, 'lbl_login_srv', None)
if lbl is None:
return
srv = self.cfg.get('server', {}) or {}
if srv.get('mock'):
txt = '服务器:离线模拟(不连后端)'
else:
url = str(srv.get('base_url') or '未配置')
if len(url) > 46:
url = url[:20] + '…' + url[-22:]
txt = '服务器:%s' % url
try:
lbl.configure(text=txt)
except Exception:
pass
def _edit_server(self):
"""登录页直接改服务器地址。
现场换机房 / 切备用服务器不用退出程序、也不用手工编辑 config.json:
保存后写回配置,并立刻作用到引擎的 ApiClient —— base_url 在
__init__ 里就缓存了,只改 self.cfg 不会生效。
"""
if getattr(self, '_logging_in', False):
return # 正在登录,别中途换地址
px, font = self._px, self._font
srv = self.cfg.setdefault('server', {})
cur = '' if srv.get('mock') else str(srv.get('base_url') or '')
d = self._dlg('服务器地址', px(560), px(392))
body = tk.Frame(d, bg='#ffffff')
body.pack(fill='both', expand=True, padx=px(24), pady=px(16))
tk.Label(body, text='服务器地址', font=font(15, 'bold'),
bg='#ffffff', fg=C.ink).pack(anchor='w')
tk.Label(body, text=('换机房 / 切备用服务器时在这里改。保存后立即生效,'
'并写回程序目录的 config.json(server.base_url);'
'原来是离线模拟的会一并关掉。'),
font=font(11), bg='#ffffff', fg=C.ink2, justify='left',
wraplength=px(500)).pack(anchor='w', pady=(px(2), px(10)))
card = Card(body, radius=px(12), pad=px(1), height=px(58),
border='#dfe6ef')
card.pack(fill='x')
card.pack_propagate(False)
ent = tk.Entry(card.body, font=font(14), bd=0, relief='flat',
bg='#ffffff', fg=C.ink)
ent.pack(fill='both', expand=True, padx=px(14), pady=px(6))
if cur:
ent.insert(0, cur)
msg = tk.Label(body, text='', font=font(11), bg='#ffffff', fg=C.ink2,
anchor='w', justify='left', wraplength=px(500))
msg.pack(fill='x', pady=(px(8), 0))
def say(text, color=C.ink2):
try:
msg.configure(text=text, fg=color)
except Exception:
pass
# 历史地址(用过的主备机):点一下填进输入框
hist = [x for x in (srv.get('history') or [])
if isinstance(x, str) and x and x != cur][:3]
if hist:
row = tk.Frame(body, bg='#ffffff')
row.pack(fill='x', pady=(px(8), 0))
tk.Label(row, text='用过:', font=font(10), bg='#ffffff',
fg=C.ink3).pack(side='left')
for u in hist:
shown = u.replace('https://', '').replace('http://', '')
if len(shown) > 32:
shown = shown[:29] + '…'
TouchButton(row, text=shown, fill='#eef2f7', fg=C.ink2,
height=px(34), radius=px(17), font=font(10),
surface='#ffffff',
command=lambda x=u: (ent.delete(0, 'end'),
ent.insert(0, x))).pack(
side='left', padx=(px(6), 0))
def pick_url():
raw = ent.get().strip()
if not raw:
say('请填写服务器地址,例如 https://www.xdjchuanhui.com/api',
C.red)
return ''
low = raw.lower()
if not (low.startswith('http://') or low.startswith('https://')):
say('地址必须以 http:// 或 https:// 开头', C.red)
return ''
return raw.rstrip('/')
def do_test():
url = pick_url()
if not url:
return
say('正在测试 %s …' % url, C.ink2)
res = {}
def work():
try:
import requests
s = requests.Session()
s.trust_env = False # 与正式客户端一致:直连
r = s.get(url + '/mobile/picking/weigh-station/pending',
timeout=(3, 5), allow_redirects=False)
code = int(r.status_code)
if code in (200, 401, 403):
res['ok'] = True
res['msg'] = ('连接正常(HTTP %d;未登录返回 401 是正常的)'
% code)
elif code == 404:
res['msg'] = ('服务器有响应,但路径 404:地址多半少了'
' /api,或指到了别的站点')
else:
res['msg'] = '服务器有响应,但返回 HTTP %d' % code
except Exception as e: # noqa: BLE001
res['msg'] = ('连不上:%s'
% (getattr(e, 'message', None) or e))
threading.Thread(target=work, daemon=True).start()
def wait(n=0):
if res:
say(res.get('msg'), '#1a7f37' if res.get('ok') else C.red)
elif n < 40:
d.after(150, lambda: wait(n + 1))
else:
say('测试超时(网络不通或服务端没响应)', C.red)
d.after(150, wait)
def do_save():
url = pick_url()
if not url:
return
backup = {'base_url': srv.get('base_url'),
'mock': srv.get('mock'),
'history': srv.get('history')}
srv['base_url'] = url
srv['mock'] = False
keep = [x for x in (srv.get('history') or [])
if isinstance(x, str) and x and x != url]
# 把「刚离开的地址」也存进历史:切到备用机之后要能一键切回来
prev = cur.strip() if isinstance(cur, str) else ''
if prev and prev != url and prev not in keep:
keep.insert(0, prev)
srv['history'] = ([url] + keep)[:5]
try:
save_config(self.cfg)
except Exception as e: # noqa: BLE001
# 写盘失败就把内存里的改动回滚,别让界面和文件不一致
for k, v in backup.items():
if v is None:
srv.pop(k, None)
else:
srv[k] = v
say('写入 config.json 失败:%s' % e, C.red)
return
# base_url 是 ApiClient.__init__ 里缓存的,只改 cfg 不会生效
try:
self.engine.api.base_url = url
self.engine.api.mock = False
# 旧服务器的 token 不能带给新服务器
self.engine.api.token = ''
except Exception:
pass
self._refresh_login_srv()
try:
d.destroy()
except Exception:
pass
self.log('服务器地址已改为 %s(已写入 config.json)' % url)
self._login_msg('服务器已切换到 %s' % url, '#1a7f37')
btns = tk.Frame(body, bg='#ffffff')
btns.pack(side='bottom', fill='x', pady=(px(12), 0))
TouchButton(btns, text='取消', command=d.destroy, fill='#eef2f7',
fg=C.ink2, height=px(56), width=px(120), radius=px(14),
font=font(14), surface='#ffffff').pack(side='right')
TouchButton(btns, text='保存并应用', command=do_save, fill=C.brand,
fg='white', height=px(56), width=px(170), radius=px(14),
font=font(14, 'bold'), surface='#ffffff').pack(
side='right', padx=(0, px(10)))
TouchButton(btns, text='测试连接', command=do_test, fill='#eef2f7',
fg=C.ink2, height=px(56), width=px(120), radius=px(14),
font=font(14), surface='#ffffff').pack(side='left')
ent.bind('<Return>', lambda e: (do_save(), 'break')[1])
ent.focus_set()
def _login_entry(self, parent, secret=False, label=''):
e = tk.Entry(parent, font=self._font(17), bd=0, relief='flat',
bg='#ffffff', fg=C.ink,
show='●' if secret else '',
highlightthickness=0,
insertbackground=C.brand)
e._kb_mode = 'abc' # 账号/密码:默认英文+数字
e._field_label = label
return e
def _pick_login_role(self, role):
"""工位选择:分段滑块 + 兼容旧的按钮状态"""
self._login_role = role if role in ('picking', 'inspection') \
else 'picking'
seg = getattr(self, 'seg_role', None)
if seg is not None:
seg.select(self._login_role, animate=False)
for btn, key in ((getattr(self, 'btn_role_pick', None), 'picking'),
(getattr(self, 'btn_role_ins', None), 'inspection')):
if btn is None:
continue
on = self._login_role == key
try:
btn.configure(bg='#185fa5' if on else '#eef2f7',
fg='white' if on else '#41505f',
activebackground='#185fa5' if on else '#e3e9f2',
activeforeground='white' if on else '#41505f')
except Exception:
pass
def _login_msg(self, text, color='#a32d2d'):
try:
self.lbl_login_msg.configure(text=text, fg=color)
except Exception:
pass
def _show_osk(self, mode=None, widget=None, handwriting=False):
"""呼出内置键盘(同一套键盘,ABC / 手写两个视图随时切)。
Windows 触摸键盘在部分工控机上进程常驻却永不显示
(ITipInvocation.Toggle 与 ShowWindow 都唤不起来),osk.exe 从普通
权限进程启动又直接 WinError 740,系统这条路不可靠。内置键盘点了
必定出现,按键和手写照写进目标输入框。
mode/widget 由调用方指定(如搜索框的「手写」按钮);
都不给就跟着"最后点过的输入框"和它自己的默认视图(_kb_mode)走。
"""
if handwriting and mode is None:
mode = 'hand'
try:
if getattr(self, '_osk_win', None) is None \
or not self._osk_win.alive():
from ui.osk import SoftKeyboard
self._osk_win = SoftKeyboard(self.root, self, self.S)
tgt = widget if widget is not None else self._current_input()
self._osk_win.show(tgt, mode)
return True
except Exception as e: # noqa: BLE001
self.log('内置键盘打不开:%s' % e)
return False
# ---- 所有输入框:点一下就用内置键盘弹,初始视图按框的性质定 ----
def _kb_on_click(self, e):
"""Entry/Text 被点:弹键盘(账号密码=ABC,搜索框=手写)。"""
w = e.widget
try:
if not w.winfo_exists():
return
except Exception:
return
self._last_input_w = w
try:
self.root.after(30, lambda w=w: self._open_kb_for(w))
except Exception:
pass
def _open_kb_for(self, w):
try:
if w is None or not w.winfo_exists():
return
except Exception:
return
self._last_input_w = w
# 带了 _kb_sys 标记的输入框(人工确认页的搜索框):
# 优先用 Windows 系统触摸键盘(TabTip,登录密码那种)且默认切到手写;
# 系统键盘打不开(工控机触摸键盘服务不可用)就退回内置手写键盘。
if getattr(w, '_kb_sys', False):
try:
if self._sys_osk(handwriting=True):
return
except Exception:
pass
self._show_osk('hand', w)
return
self._show_osk(widget=w)
# ---- 输入框焦点跟踪:键盘要知道往哪个框里打字 ----
def _is_input(self, w):
if w is None:
return False
try:
return w.winfo_class() in ('Entry', 'TEntry', 'Text')
except Exception:
return False
def _on_focus_in(self, e):
if self._is_input(e.widget):
self._last_input_w = e.widget
def _current_input(self):
if self._is_input(self._last_input_w):
return self._last_input_w
return None
def _sys_osk_fallback(self, widget=None):
"""系统触摸键盘(默认手写),打不开就退回内置手写键盘。"""
try:
if self._sys_osk(handwriting=True):
return
except Exception:
pass
self._show_osk('hand', widget)
def _sys_osk(self, handwriting=False):
"""系统触摸键盘(中文输入 / 手写):真判断窗口是否出现再算成功。"""
import ctypes
import time
u = ctypes.windll.user32
tip = r'C:\Program Files\Common Files\microsoft shared\ink\TabTip.exe'
h = u.FindWindowW('IPTip_Main_Window', None)
if h and u.IsWindowVisible(h): # 已经在屏幕上,置前即可
u.SetForegroundWindow(h)
if handwriting:
import threading
threading.Thread(target=self._tip_handwriting,
daemon=True).start()
return True
if handwriting and os.path.exists(tip):
try:
import subprocess
subprocess.Popen([tip])
except Exception:
pass
# Win10 官方调出方式:ITipInvocation::Toggle(进程常驻时 Popen 无效)
shown = self._tip_toggle(wait=1.4 if handwriting else 1.0)
if shown and handwriting:
import threading
threading.Thread(target=self._tip_handwriting,
daemon=True).start()
if not shown:
shown = self._launch_and_check(
r'C:\Windows\System32\osk.exe', 'OSKMainClass')
if not shown:
try:
self.log('系统软键盘打不开(本机触摸键盘服务不可用)')
except Exception:
pass
return shown
def _tip_toggle(self, wait=1.2):
"""调 ITipInvocation::Toggle 显示触摸键盘,并等它真的出现在屏幕上。"""
import ctypes
import time
u = ctypes.windll.user32
try:
import comtypes.client
iface, clsid = _tip_iface()
tip = comtypes.client.CreateObject(clsid, interface=iface)
tip.Toggle(None)
except Exception:
return False
end = time.time() + wait
while time.time() < end:
h = u.FindWindowW('IPTip_Main_Window', None)
if h and u.IsWindowVisible(h):
u.SetForegroundWindow(h)
return True
time.sleep(0.15)
return False
def _launch_and_check(self, exe, cls, wait=1.5):
"""启动外部程序并确认窗口真的出现(只看 Popen 会误判成功)。"""
import ctypes
import subprocess
import time
u = ctypes.windll.user32
try:
subprocess.Popen([exe])
except Exception:
try:
if ctypes.windll.shell32.ShellExecuteW(
None, 'open', exe, None, None, 1) <= 32:
return False
except Exception:
return False
end = time.time() + wait
while time.time() < end:
h = u.FindWindowW(cls, None) if cls else None
if h and u.IsWindowVisible(h):
return True
time.sleep(0.15)
return False
def _launch_exe(self, exe):
"""三级回退启动系统程序:直接起 → ShellExecute → explorer 代理"""
import subprocess
try:
subprocess.Popen([exe])
return True
except Exception:
pass
try:
import ctypes
ret = ctypes.windll.shell32.ShellExecuteW(
None, 'open', exe, None, None, 1)
if ret > 32: # >32 表示成功
return True
except Exception:
pass
try:
subprocess.Popen(['explorer.exe', exe])
return True
except Exception:
return False
def _tip_handwriting(self, tries=8):
"""把触摸键盘切到「手写」视图(Windows 输入法自带手写)。
用 UI 自动化找键盘上的「手写 / Handwriting」按钮并点它;
键盘没弹出来(无触摸设备)或找不到按钮时安静返回 False,
用户仍可在键盘上自己点手写图标。
"""
try:
import time
import comtypes.client
comtypes.client.GetModule('UIAutomationCore.dll')
from comtypes.gen import UIAutomationClient as UIA
auto = comtypes.client.CreateObject(
UIA.CUIAutomation, interface=UIA.IUIAutomation)
cond = auto.CreatePropertyCondition(
UIA.UIA_ClassNamePropertyId, 'IPTip_Main_Window')
win = None
for _ in range(max(1, tries)): # 键盘弹出要 1~2 秒
win = auto.GetRootElement().FindFirst(
UIA.TreeScope_Children, cond)
if win:
break
time.sleep(0.3)
if not win:
return False
def walk(el, depth=0):
if depth > 5:
return False
try:
kids = el.FindAll(UIA.TreeScope_Children,
auto.CreateTrueCondition())
except Exception:
return False
for i in range(kids.Length):
ch = kids.GetElement(i)
try:
nm = ch.CurrentName or ''
aid = ch.CurrentAutomationId or ''
except Exception:
continue
key = (nm + ' ' + aid).lower()
if ('手写' in key or 'handwrit' in key
or 'handwriting' in key):
try:
pat = ch.GetCurrentPattern(
UIA.UIA_InvokePatternId)
pat.QueryInterface(
UIA.IUIAutomationInvokePattern).Invoke()
return True
except Exception:
pass
if walk(ch, depth + 1):
return True
return False
return bool(walk(win))
except Exception:
return False
def _do_login(self, _e=None):
if getattr(self, '_logging_in', False):
return 'break'
u = self.ent_user.get().strip()
p = self.ent_pwd.get()
if not u:
self._login_msg('请输入账号')
self.ent_user.focus_set()
return 'break'
if not p:
self._login_msg('请输入密码')
self.ent_pwd.focus_set()
return 'break'
self._logging_in = True
self._login_pwd = p
self._login_user = u
self.btn_login.configure(state='disabled', text='正在登录…',
bg='#7f9dbd')
self._login_msg('正在连接服务器,请稍候…', '#5f6b7a')
def work():
try:
self.engine.login(u, p, self._login_role)
except Exception as e:
msg = getattr(e, 'message', None) or str(e) or '未知错误'
self.q.put(('login_err', str(msg)))
threading.Thread(target=work, daemon=True).start()
return 'break'
def _on_login_ok(self, p):
"""登录成功:记住账号 → 切主界面 → 启动秤/摄像头/主循环"""
self._logging_in = False
acc = self.cfg.setdefault('account', {})
acc['username'] = self._login_user
acc['role'] = p.get('role') or (
'inspector' if (p.get('station') or self._login_role)
== 'inspection' else 'picker')
acc['password'] = self._login_pwd \
if self.var_remember.get() else ''
try:
save_config(self.cfg)
except Exception:
pass
for w in self.root.winfo_children():
w.destroy()
self._build()
self.ready = True
self._tick_clock()
self._refresh_today()
self._refresh_devices()
self.engine.start()
try:
self._log_machine() # v1.0.52:记一行机器底子,卡了先看它
except Exception:
pass
if not self._ka_started:
self._ka_started = True
threading.Thread(target=self._keepalive, daemon=True).start()
# v1.0.72(性能):登录不再在 UI 线程等网络。引擎在后台登录时已经
# 拉过一次名单(engine.rows),先直接上屏;随后异步刷新一次。
# 以前这里调同步的 refresh_pending:入库站要发 2 个请求(pending +
# pending-grouped),读超时 10 秒,网络一抖就是几秒白屏(日志里
# 实测最大 3.1 秒)。业务逻辑一点没改:刷完还是同一套 _on_pending。
try:
_rows = getattr(self.engine, 'rows', None) or []
if _rows:
self._on_pending({
'rows': _rows,
'config': getattr(self.engine, 'server_config', {}) or {},
'account': getattr(self.engine, 'account_name', '')})
except Exception:
pass
self.engine.refresh_pending_async()
# 开机自动认设备(后台跑,认出什么就用什么;现场换备机/换口都能自愈)
# 延迟 1.5 秒:先让秤把第一帧吐出来,秤正常就不会被探测打扰
if bool(self._get('devices.auto_detect', True)):
self.root.after(1500, self._autodetect_devices)
def _on_login_err(self, msg):
self._logging_in = False
try:
self.btn_login.configure(state='normal', text='登 录',
bg='#185fa5')
except Exception:
pass
self._login_msg('登录失败:%s' % msg)
def _logout(self):
"""退出登录:回到登录页(重建引擎,避免沿用旧 token)。
分级放行,只有「提交中」必须等:
SUBMIT 正在提交 → 等回包。切断会出现「服务端已收货、本地
不知道」,下次登录就是未决提交,还可能重复收一次。
CAPTURE/RECOGNIZE/MANUAL 还没提交 → 问一句,作废本件即可退出。
WEIGHING 只是货在秤上,没发过任何请求 → 直接放行。
IDLE / DONE 直接放行。
另外:还有标签没打完要提示(队列一停,那几张就得补打)。
"""
st = self.engine.state
if st == 'SUBMIT':
messagebox.showwarning(
'正在提交,请等它出结果',
'这一件正在提交给服务器(通常几秒,最多 10 秒)。\n\n'
'为什么不能现在退:提交是「请求已经发出去了、结果要等回包」的'
'操作。现在把连接切断,服务器很可能已经记了这笔,本地却不知道'
'——下次登录会显示「未决提交」并锁住新提交,还得人工核实,'
'弄不好同一件货重复入一次。\n\n'
'等这一件出结果(界面会自动走到「完成」或提示失败)再退。',
parent=self.root)
return
leaving = ''
if st in ('CAPTURE', 'RECOGNIZE', 'MANUAL',
'COUNT_CAPTURE', 'COUNT_RECOGNIZE', 'COUNT_CONFIRM'):
step = {'CAPTURE': '抓拍', 'RECOGNIZE': 'AI 识别',
'MANUAL': '人工确认',
'COUNT_CAPTURE': '免称重抓拍',
'COUNT_RECOGNIZE': '免称重识别',
'COUNT_CONFIRM': '免称重确认'}.get(st, st)
leaving = ('\n\n提醒:这一件还在「%s」,还没有提交给服务器。\n'
'退出后本件作废(不留记录),要重新放货称一次。' % step)
left = 0
try:
left = self.engine.pending_labels()
except Exception:
left = 0
if left:
leaving += ('\n\n还有 %d 张标签没打出来,退出后不会自动补打。' % left)
if not messagebox.askyesno(
'退出登录',
'确定退出当前账号,回到登录页?' + leaving,
parent=self.root, default='no', icon='question'):
return
if st in ('CAPTURE', 'RECOGNIZE', 'MANUAL'):
try:
self.engine.abort_cycle('退出登录:本件作废(%s 未完成)'
% {'CAPTURE': '抓拍',
'RECOGNIZE': 'AI 识别',
'MANUAL': '人工确认'}.get(st, st))
except Exception:
pass
if st in ('COUNT_CAPTURE', 'COUNT_RECOGNIZE', 'COUNT_CONFIRM'):
try:
self.engine.cancel_count('退出登录:免称重已放弃')
except Exception:
pass
# 弹窗期间进度可能往前走(识别完成 → 已经开始提交):再确认一次
if self.engine.state == 'SUBMIT':
messagebox.showwarning(
'刚好开始提交了',
'这一件刚刚进入提交,请等它出结果(几秒)再退出登录。',
parent=self.root)
return
# 关掉可能还开着的人工确认页 / 屏幕键盘 / 未决提交弹窗
try:
if self._confirm_top is not None \
and self._confirm_top.winfo_exists():
self._confirm_top.destroy()
except Exception:
pass
self._confirm_top = None
try:
if self._count_top is not None and self._count_top.winfo_exists():
self._count_top.destroy()
except Exception:
pass
self._count_top = None
try:
if self._osk_win is not None:
self._osk_win.hide()
except Exception:
pass
self.ready = False
try:
self.engine.stop()
except Exception:
pass
while True: # 丢掉旧引擎残留事件
try:
self.q.get_nowait()
except queue.Empty:
break
self._last_preview_seq = None
self._tkimg = None
self.engine = FlowEngine(self.cfg, lambda ev, p: self.q.put((ev, p)))
self._build_login()
def _quit(self):
try:
self.engine.stop()
except Exception:
pass
try:
self.flush_log() # 日志队列写干净再关窗(最多等 1 秒)
except Exception:
pass
self.root.destroy()
# ------------------------------------------------------------ 布局
# 设计基准 1440×900:所有尺寸按 S 等比缩放,触摸屏直接按设计稿出图
def _px(self, n):
return max(1, int(round(n * self.S)))
def _font(self, size, weight='normal'):
return ('Microsoft YaHei', max(9, int(round(size * self.S))), weight)
def _name_font(self, size):
"""卡名用的加粗字体(带缓存):_layout_cards 要拿它量字宽。"""
cache = getattr(self, '_name_fonts', None)
if cache is None:
cache = self._name_fonts = {}
f = cache.get(size)
if f is None:
try:
f = tkfont.Font(font=self._font(size, 'bold'))
except Exception:
f = None
cache[size] = f
return f if f is not None else self._font(size, 'bold')
def _fit_text(self, txt, max_px, size=10):
"""按像素宽度把一行字截断(超出补 …)。
v1.0.51:状态卡压到 116 后只留得下一行「最近:…」。换行会把卡撑破、
最后一截被 pack 压掉,所以这里按实际字宽(中文比英文宽一倍)截,
而不是按字数猜。
"""
txt = str(txt or '')
try:
f = self._fit_font
if f is None or f[0] != size:
from tkinter import font as tkfont
f = (size, tkfont.Font(font=self._font(size)))
self._fit_font = f
ft = f[1]
if ft.measure(txt) <= max_px:
return txt
while txt and ft.measure(txt + '…') > max_px:
txt = txt[:-1]
return txt + '…'
except Exception:
return txt
# ------------------------------------------------------------ 平板骨架
def _build(self):
"""24 寸平板作业台:沿用原有布局(左作业 / 右待办),做大做软。
平板要点:触摸目标 ≥ 52px、圆角卡片、留白 16/20;
按钮按下回弹、开关滑块、名单手指拖动带惯性。
屏大(1920×1080 及以上)时整屏铺开,所有尺寸按 ui 缩放系数等比放大。
"""
px, font = self._px, self._font
root = self.root
root.configure(bg=C.bg)
# ---- 顶栏 ----
header = tk.Frame(root, bg=C.surface, height=px(60))
header.pack(fill='x')
header.pack_propagate(False)
tk.Frame(header, bg=C.line, height=1).pack(side='bottom', fill='x')
self._bind_drag(header)
logo = tk.Canvas(header, width=px(38), height=px(38), bg=C.surface,
highlightthickness=0, bd=0)
logo.pack(side='left', padx=(px(22), px(10)))
self._logo_img = rounded_photo(px(38), px(38), px(12), C.brand,
C.surface)
if self._logo_img is not None:
logo.create_image(0, 0, anchor='nw', image=self._logo_img)
logo.create_text(px(19), px(20), text='入', fill='white',
font=font(17, 'bold'))
self._logo_cv = logo
self._logo_text = logo.find_all()[-1] if logo.find_all() else None
self._bind_drag(logo)
lbl_brand = tk.Label(
header, text=self._station_title(self.engine.station),
font=font(17, 'bold'), bg=C.surface, fg=C.ink)
lbl_brand.pack(side='left')
self.lbl_brand = lbl_brand
self._bind_drag(lbl_brand)
# 工位标识:登录时定好,作业界面不提供第二个切换按钮
self.lbl_station = tk.Label(header, text='', font=font(12, 'bold'),
bg=C.brand_soft, fg=C.brand,
padx=px(12), pady=px(5))
self.lbl_station.pack(side='left', padx=(px(14), 0))
self._bind_drag(self.lbl_station)
self._paint_station()
# 右侧:关闭 / 最小化 / 退出登录 / 设置 / 账号 / 时钟 / 待办数
TouchButton(header, text='✕', command=self._quit, fill='#f1f4f9',
fg=C.ink2, height=px(44), width=px(44), radius=px(22),
font=font(15, 'bold'), surface=C.surface).pack(
side='right', padx=(0, px(18)))
TouchButton(header, text='—', command=self._minimize, fill='#f1f4f9',
fg=C.ink2, height=px(44), width=px(44), radius=px(22),
font=font(15, 'bold'), surface=C.surface).pack(
side='right', padx=(px(6), px(6)))
TouchButton(header, text='退出登录', command=self._logout,
fill='#f1f4f9', fg=C.ink2, height=px(44), width=px(104),
radius=px(22), font=font(12, 'bold'),
surface=C.surface).pack(side='right', padx=(0, px(10)))
TouchButton(header, text='设置', command=self._settings,
fill=C.brand_soft, fg=C.brand, height=px(44),
width=px(88), radius=px(22), font=font(12, 'bold'),
surface=C.surface).pack(side='right', padx=(0, px(10)))
self.lbl_account = tk.Label(
header, text=('账号:%s' % getattr(self, '_login_user', ''))
if getattr(self, '_login_user', '') else '未登录',
font=font(12), bg=C.surface, fg=C.ink2)
self.lbl_account.pack(side='right', padx=px(10))
self._bind_drag(self.lbl_account)
self.lbl_clock = tk.Label(header, text='', font=font(12),
bg=C.surface, fg=C.ink2)
self.lbl_clock.pack(side='right', padx=px(6))
self._bind_drag(self.lbl_clock)
# 右侧待办标题已显示总行数,顶栏不再重复展示「待办 N 行」
self.lbl_pending = tk.Label(header, text='待办 0 行', font=font(12),
bg=C.surface, fg=C.ink3)
main = tk.Frame(root, bg=C.bg)
main.pack(fill='both', expand=True, padx=px(20), pady=(px(6), px(14)))
# 先 pack 固定宽度的左列,右列再吃剩余(顺序反了左列会被压成 0 宽)
left = tk.Frame(main, bg=C.bg, width=px(560))
left.pack(side='left', fill='y')
left.pack_propagate(False)
right = tk.Frame(main, bg=C.bg)
right.pack(side='left', fill='both', expand=True, padx=(px(16), 0))
# ================= 左列:作业 =================
# 从下往上排固定高度的块,剩下的空间全给摄像头
# ① 状态卡
# v1.0.51:状态卡从 150 压到 116,腾出的高度全给摄像头预览
# (现场反馈「预览太矮,货放在秤上只能看见中间一条」)。
sc = Card(left, radius=px(18), pad=px(10), height=px(116))
sc.pack(side='bottom', fill='x', pady=(px(6), 0))
sc.pack_propagate(False)
r1 = tk.Frame(sc.body, bg=C.surface)
r1.pack(fill='x')
self._state_dot = tk.Canvas(r1, width=px(12), height=px(12),
bg=C.surface, highlightthickness=0, bd=0)
self._state_dot.pack(side='left', padx=(0, px(10)))
self._dot = self._state_dot.create_oval(px(1), px(1), px(11), px(11),
fill=C.green, outline='')
self.lbl_state = tk.Label(r1, text='待机中:请放货',
font=font(18, 'bold'), bg=C.surface,
fg=C.ink, anchor='w')
self.lbl_state.pack(side='left')
self.lbl_print = tk.Label(r1, text='', font=font(11),
bg=C.surface, fg=C.ink3, anchor='e')
self.lbl_print.pack(side='right')
self.lbl_hint = tk.Label(sc.body, text='放货 → 自动识别 → 取走',
font=font(11), bg=C.surface, fg=C.ink2,
anchor='w')
self.lbl_hint.pack(fill='x', pady=(px(1), 0))
# v1.0.51:只留一行(宽度按像素截断,见 _fit_text),不换行撑破卡
self.lbl_last = tk.Label(sc.body, text='', font=font(10), bg=C.surface,
fg=C.ink3, anchor='w', justify='left')
self.lbl_last.pack(fill='x')
# v1.0.42:状态卡不再显示「秤 COM3 · 相机 0 号 · 打印 GE130 ·
# 服务端 …」这行设备信息(操作员用不上,只留排障价值)——
# 内容改由 _refresh_devices() 写进日志,界面不显示。
# ② 主操作(大按钮)
# v1.0.53:删掉「不称重分拣 / 免称重收货」按钮(现场要求)。
# 件装货(1 袋 / 1 桶)照样能收:点名单里那一行会进免称重核对页,
# 数量人工确认;画面自动识别(_auto_scan)也还留着,不受影响。
acts = tk.Frame(left, bg=C.bg)
acts.pack(side='bottom', fill='x', pady=(px(6), 0))
# v1.0.62:「重拍」并进「手动抓拍识别」——有待确认件时这颗按钮
# 就是重拍(作废这一件重新抓拍),平时就是手动抓拍。行里只剩
# 抓拍/确认/放弃三颗,手指好点。
self.btn_cancel = TouchButton(
acts, text='放弃', command=self._focus_cancel,
fill=C.red_soft, fg=C.red, height=px(44), radius=px(12),
font=font(13), width=px(76), surface=C.bg, enabled=False)
self.btn_cancel.pack(side='right', padx=(px(8), 0), pady=px(7))
self.btn_capture = TouchButton(
acts, text='手动抓拍识别', command=self._capture_or_retry,
fill=C.brand, fg='white', height=px(58), radius=px(16),
font=font(16, 'bold'), surface=C.bg)
self.btn_capture.pack(side='left', fill='x', expand=True)
# v1.0.60:原来这里并排过「无称入库」按钮(v1.0.53 已删),现在
# 这个位置换成「确认」—— 秤上认出来的那件,就近点它。
# 没有待确认件时置灰,不会误触发。
self.btn_confirm = TouchButton(
acts, text='确认', command=self._big_confirm,
fill=C.green, fg='white', height=px(58), radius=px(16),
font=font(16, 'bold'), surface=C.bg, enabled=False)
self.btn_confirm.pack(side='left', fill='x', expand=True,
padx=(px(10), 0))
# 重复收货防护的「推翻按钮」:有疑问时才出现
self._newitem_row = tk.Frame(left, bg=C.bg)
self._newitem_row.pack(side='bottom', fill='x', pady=(px(6), 0))
self._btn_newitem = TouchButton(
self._newitem_row, text='这是一件新货(不是刚才那件)',
command=self._accept_new_item, fill=C.amber, fg='white',
height=px(52), radius=px(16), font=font(14, 'bold'),
surface=C.bg)
# ③ 重量卡
wc = Card(left, radius=px(18), pad=px(12))
wc.pack(side='bottom', fill='x')
hd = tk.Frame(wc.body, bg=C.surface)
hd.pack(fill='x')
tk.Label(hd, text='当前重量', font=font(12, 'bold'), bg=C.surface,
fg=C.ink2).pack(side='left')
self.lbl_w_tare = tk.Label(hd, text='未去皮', font=font(12),
bg=C.surface, fg=C.ink3)
self.lbl_w_tare.pack(side='right')
wrow = tk.Frame(wc.body, bg=C.surface)
wrow.pack(fill='x')
# v1.0.51:字号 56→46 —— 少 10 号字换预览多出 20px,46 号在 1.5 米外
# 仍然一眼能读,不用凑近看。
self.lbl_weight = tk.Label(wrow, text='0.0', anchor='w',
font=font(46, 'bold'), bg=C.surface,
fg=C.brand)
self.lbl_weight.pack(side='left')
tk.Label(wrow, text='kg', font=font(17, 'bold'), bg=C.surface,
fg=C.ink3).pack(side='left', padx=(px(6), 0),
pady=(px(12), 0))
self.lbl_jin = tk.Label(wrow, text='0.0 斤', font=font(17),
bg=C.surface, fg=C.green)
self.lbl_jin.pack(side='left', padx=(px(12), 0), pady=(px(16), 0))
bt = tk.Frame(wc.body, bg=C.surface)
bt.pack(fill='x', pady=(px(2), 0))
self.btn_tare = TouchButton(bt, text='去皮', command=lambda:
self._scale_action('tare'),
fill=C.brand_soft, fg=C.brand,
height=px(46), radius=px(14),
font=font(16, 'bold'), surface=C.surface)
self.btn_tare.pack(side='left', fill='x', expand=True)
self.btn_zero = TouchButton(bt, text='置零', command=lambda:
self._scale_action('zero'),
fill='#eef1f6', fg=C.ink,
height=px(46), radius=px(14),
font=font(16, 'bold'), surface=C.surface)
self.btn_zero.pack(side='left', fill='x', expand=True,
padx=(px(12), 0))
# 秤状态小字:正常称重时不占高度,仅在未连接/超载/过期等异常时显露
self.lbl_scale = tk.Label(wc.body, text='', font=font(11),
bg=C.surface, fg=C.red, anchor='w')
self._scale_err_vis = False
self.lbl_w_live = self.lbl_weight
# ④ 步骤条(贴重量卡上方)
self.step_bar = StepsBar(left, STEP_NAMES, surface=C.bg,
height=px(30), font=font(11), gap=px(6))
self.step_bar.pack(side='bottom', fill='x', pady=(px(6), 0))
self.step_lbls = [] # 旧字段:步骤状态现在由 step_bar 画
# ⑤ 摄像头大窗(吃掉剩余高度)
cam = Card(left, radius=px(18), pad=px(10))
cam.pack(side='top', fill='both', expand=True)
self.cam_card = cam
ch = tk.Frame(cam.body, bg=C.surface)
ch.pack(fill='x')
tk.Label(ch, text='实时画面', font=font(12, 'bold'), bg=C.surface,
fg=C.ink).pack(side='left')
self.btn_zin = TouchButton(ch, text='+', command=lambda:
self._zoom_step(+0.5), fill='#2b3440',
fg='white', height=px(30), width=px(30),
radius=px(15), font=font(14, 'bold'),
surface=C.surface)
self.btn_zin.pack(side='right')
self.lbl_zoom = tk.Label(ch, text='1.0×', font=font(12, 'bold'),
bg=C.surface, fg=C.ink2, width=5)
self.lbl_zoom.pack(side='right')
self.btn_zout = TouchButton(ch, text='−', command=lambda:
self._zoom_step(-0.5), fill='#2b3440',
fg='white', height=px(30), width=px(30),
radius=px(15), font=font(14, 'bold'),
surface=C.surface)
self.btn_zout.pack(side='right')
box = tk.Frame(cam.body, bg='#10141a')
box.pack(fill='both', expand=True, pady=(px(4), 0))
self.preview_lbl = tk.Label(box, bg='#10141a', bd=0)
self.preview_lbl.pack(fill='both', expand=True)
self.preview_lbl.bind('<MouseWheel>', self._zoom_wheel)
box.bind('<MouseWheel>', self._zoom_wheel)
# ================= 右列:待办名单 =================
# 取消「待办名单 + 合计」标题行(多单位时易截断且占高度),保留隐藏引用兼容旧回调
self.lbl_todo_title = tk.Label(right, text='', font=font(17, 'bold'),
bg=C.bg, fg=C.ink)
self.lbl_todo_sum = tk.Label(right, text='', font=font(13, 'bold'),
bg=C.bg, fg=C.green)
# 卡片详情/提示行:平时无选中或筛选时自动隐藏,避免占白位
self.lbl_todo_detail = tk.Label(right, text='',
font=font(11), bg=C.bg, fg=C.ink2,
anchor='w', justify='left')
self._todo_detail_vis = False
# ---- 展示维度:不分组 / 按客户(下拉选一家)/ 按分类(下拉选一类) ----
# 待办一动就是几十行,分组后「这一趟给谁拣」一眼能看出来。
# 客户/分类的取值不再铺一排 chips:名字长短不一,两三个就把一行挤满,
# 长名字还会互相压字。改成右侧一个下拉,点开再选,标题永远只占一行。
self._close_group_dd()
self._group_pop = None
self._dd_bind = None
self._group_mode = str((self.cfg.get('ui') or {})
.get('todo_group') or 'none')
# v1.0.34 去掉「按商品」:品名本来就印在每张卡上,再按品名分组没意义
if self._group_mode not in ('none', 'customer', 'category'):
self._group_mode = 'none'
self._group_pick = None
gbar = tk.Frame(right, bg=C.bg)
gbar.pack(fill='x', pady=(0, px(6)))
self._group_bar = gbar
seg = tk.Frame(gbar, bg=C.bg)
seg.pack(side='top', fill='x')
self._group_btns = {}
who_txt = '按客户' if self.engine.station == 'picking' else '按供应商'
for key, txt in (('none', '不分组'), ('customer', who_txt),
('category', '按分类')):
b = TouchButton(seg, text=txt,
command=lambda k=key: self._set_group_mode(k),
fill='#eaeff6', fg=C.ink2, height=px(38),
width=px(82), radius=px(19), font=font(12),
surface=C.bg)
b.pack(side='left', padx=(0, px(6)))
self._group_btns[key] = b
# 下拉按钮:只在按客户/按分类时出现,「全部 N 行」= 不筛
self._group_dd = TouchButton(seg, text='全部 ▾',
command=self._toggle_group_dd,
fill=C.surface, fg=C.ink, height=px(38),
width=px(210), radius=px(19),
font=font(12), surface=C.bg,
outline=C.line)
# 硬刷新按钮与列数切换放到分组条右侧,给卡片留出更多空间
TouchButton(seg, text='刷新待办', command=self._refresh_pending_now,
fill=C.green, fg='white', height=px(38), width=px(102),
radius=px(19), font=font(12, 'bold'),
surface=C.bg).pack(side='right')
self.btn_cols = TouchButton(seg, text=self._cols_text(),
command=self._cycle_cols, fill='#eaeff6',
fg=C.ink2, height=px(38), width=px(92),
radius=px(19), font=font(12),
surface=C.bg)
self.btn_cols.pack(side='right', padx=(0, px(8)))
self._paint_group_bar()
# 搜索框
sb_card = Card(right, radius=px(24), pad=px(5), height=px(52))
sb_card.pack(fill='x', pady=(0, px(8)))
sb_card.pack_propagate(False)
sbox = sb_card.body
self.var_search = tk.StringVar()
self._search_ph_on = False
self._search_job = None
self._empty_lbl = None
self.ent_search = tk.Entry(
sbox, textvariable=self.var_search, font=font(15), bd=0,
relief='flat', bg=C.surface, fg=C.ink, insertwidth=2,
insertbackground=C.brand)
self.ent_search.pack(side='left', fill='x', expand=True,
padx=(px(12), px(4)), pady=px(6))
self.ent_search._kb_mode = 'hand'
self.ent_search._field_label = '搜索'
for txt, cmd, bgc, fg, bw in (
('×', self._clear_search, C.surface, C.ink3, 44),
('键盘', lambda: (self._search_focus_in(),
self._show_osk('abc', self.ent_search)),
'#eef2f7', C.ink2, 62),
('语音', self._voice_input, '#eef2f7', C.ink2, 62),
('手写', self._handwriting, '#eef2f7', C.ink2, 62)):
TouchButton(sbox, text=txt, command=cmd, fill=bgc, fg=fg,
height=px(38), width=px(bw), radius=px(19),
font=font(12), surface=C.surface).pack(
side='right', padx=(px(4), 0))
self.ent_search.bind('<FocusIn>', self._search_focus_in)
self.ent_search.bind('<FocusOut>', self._search_focus_out)
self.ent_search.bind('<Escape>',
lambda e: (self._clear_search(), 'break')[1])
self.var_search.trace_add('write', self._on_search_changed)
self._search_placeholder()
self._all_rows = []
body = tk.Frame(right, bg=C.bg)
body.pack(fill='both', expand=True)
# v1.0.58:待办名单不再拖动滚动(现场触摸屏拖起来卡、还容易误选
# 误打印),改成分页:一屏放不下的用「上一页/下一页」翻。翻页条
# 先 pack 在底部,canvas 才能拿到刨去它之后的高度算「一页几行」。
pager = tk.Frame(body, bg=C.bg)
pager.pack(side='bottom', fill='x', pady=(px(6), 0))
self.btn_pg_prev = TouchButton(
pager, text='‹ 上一页',
command=lambda: self._page_turn(-1),
fill='#eef2f7', fg=C.ink2, height=px(44), width=px(140),
radius=px(22), font=font(13, 'bold'), surface=C.bg)
self.btn_pg_prev.pack(side='left')
self.lbl_page = tk.Label(pager, text='', font=font(12),
bg=C.bg, fg=C.ink2)
self.lbl_page.pack(side='left', fill='x', expand=True)
self.btn_pg_next = TouchButton(
pager, text='下一页 ›',
command=lambda: self._page_turn(1),
fill='#eef2f7', fg=C.ink2, height=px(44), width=px(140),
radius=px(22), font=font(13, 'bold'), surface=C.bg)
self.btn_pg_next.pack(side='right')
self.todo_canvas = tk.Canvas(body, bg=C.bg, highlightthickness=0,
bd=0, takefocus=0)
self.todo_canvas.pack(side='left', fill='both', expand=True)
self.todo_canvas.configure(yscrollincrement=1)
self.todo_grid = tk.Frame(self.todo_canvas, bg=C.bg)
self._todo_win = self.todo_canvas.create_window(
(0, 0), window=self.todo_grid, anchor='nw')
self.todo_canvas.bind('<Configure>', self._todo_on_resize)
self.todo_canvas.bind('<MouseWheel>', self._page_wheel)
self._bind_swipe(self.todo_canvas)
# v1.0.58:不再有拖动滚动,翻页状态如下
self._todo_scroll = None
self._page = 0 # 当前页(0 起)
self._page_count = 1 # 总页数,_layout_cards 算
self._page_of = {} # id(卡片/标题) → 页码
self._row_h_est = 0 # 卡高实测缓存(名字 1~2 行差 20px)
# 点击判定(v1.0.57):按下→松手没挪过才算点。分页后拖动不再滚动,
# 但「按下→划走→松手」仍不算点,确认状态下不会误改判/误打印。
self._tap = TapGate()
self._swipe = None # 左右滑动翻页的起点(v1.0.68)
self._sel_rid = None
self.todo_cards = {}
self.todo_rows = {}
# v1.0.47:当前渲染的行 id 顺序 + 分批建卡代数(增量更新/取消旧批次用)
self._shown_ids = []
self._build_gen = 0
# 底部结果条:紧凑单行(模式已在顶栏标明,不重复占一行)
ft = Card(right, radius=px(14), pad=px(8), height=px(48))
ft.pack(fill='x', pady=(px(6), 0))
ft.pack_propagate(False)
self.ft_bar = ft
f1 = tk.Frame(ft.body, bg=C.surface)
f1.pack(fill='both', expand=True)
tk.Label(f1, text='本次结果', font=font(11), bg=C.surface,
fg=C.ink3).pack(side='left', padx=(0, px(8)))
self.lbl_result = tk.Label(f1, text='—', font=font(13, 'bold'),
bg=C.surface, fg=C.green, anchor='w',
justify='left')
self.lbl_result.pack(side='left', fill='x', expand=True)
self.lbl_today = tk.Label(f1, text='今日已完成 0 件', font=font(11),
bg=C.surface, fg=C.ink2, anchor='e')
self.lbl_today.pack(side='right')
# 「最近提交」:提交完不能改,但得让人随时翻出「刚才是怎么记的账」,
# 对着照片和操作号去后台更正,而不是凭记忆吵。
TouchButton(f1, text='最近提交', command=self._show_recent_records,
fill='#eef2f7', fg=C.ink2, height=px(32), width=px(90),
radius=px(16), font=font(11),
surface=C.surface).pack(side='right', padx=(0, px(10)))
self.lbl_mode = tk.Label(ft.body, text='', font=font(10),
bg=C.surface, fg=C.ink3, anchor='w')
# 识别确认:认出商品后跳到那张卡,人点左列「确认」才提交。
# 用 pack(before=ft) 插在结果条上面,不用另开窗口 —— 现场最烦弹窗。
self._build_focus_bar(right)
@staticmethod
def _station_title(station):
"""当前工位的软件名(顶栏 + 窗口标题)
两个工位共用同一个程序,但顶栏写“入库分拣工作站”对分拣台来说很
容易让人以为这是入库的机子。按工位分开叫,库管/调度一眼就知道
这台是干什么的。
"""
return '分拣工作站' if str(station) == 'picking' else '入库工作站'
def _paint_station(self):
"""工位只显示当前那一个(登录时定的),不做切换按钮。"""
picking = self.engine.station == 'picking'
name = self._station_title(self.engine.station)
try:
self.lbl_brand.configure(text=name)
except Exception:
pass
try:
self.root.title(name)
except Exception:
pass
try:
if getattr(self, '_logo_text', None) is not None:
self._logo_cv.itemconfigure(
self._logo_text, text='拣' if picking else '入')
except Exception:
pass
try:
self.lbl_station.configure(
text='分拣工位 · 打标签' if picking else '入库工位 · 不打标签',
bg='#fdf0d9' if picking else '#e6f0fb',
fg='#854f0b' if picking else '#185fa5')
except Exception:
pass
try:
self.lbl_mode.configure(
text='分拣模式:确认后自动打印标签' if picking
else '入库模式:只记录,不打印标签',
fg='#854f0b' if picking else '#5f5e5a')
except Exception:
pass
def _set_station(self, s):
if self.engine.state not in ('IDLE',):
self.log('请先完成当前流程再切换工位')
return
self.engine.set_station(s)
self._paint_station()
self._refresh_today()
# 记住这次工位:下次登录页默认选它(config 里存服务端 role_type)
try:
self.cfg.setdefault('account', {})['role'] = (
'inspector' if s == 'inspection' else 'picker')
save_config(self.cfg)
except Exception:
pass
self.log('切换到【%s】' % ('分拣' if s == 'picking' else '入库'))
def _scale_action(self, which):
"""去皮 / 置零:待机、称重中、以及「完成」态都允许。
完成态也放开是因为现场真会卡住:复核失败没提交、货还压在秤上,
以前这里直接拒绝「流程已进行到 DONE」,操作员唯一的自救手段
(置零重新开始)也被堵死,只能重启程序。
"""
name = '去皮' if which == 'tare' else '置零'
# 现场顺序:空筐上秤 → 界面进入 WEIGHING → 按「去皮」→ 净重归零回待机,
# 所以 WEIGHING 必须允许;抓拍之后(含人工确认/提交/打印)不许改重量,
# 但 DONE 是「已完成、等取货」,置零/去皮是明确的重新开始意图。
if self.engine.state not in ('IDLE', 'WEIGHING', 'DONE'):
self.log('流程已进行到「%s」,暂不能%s(完成或取货后再操作)'
% (self.engine.state, name))
return
was_done = self.engine.state == 'DONE'
def work():
fn = (self.engine.scale.tare if which == 'tare'
else self.engine.scale.zero)
try:
ok, msg = fn()
except Exception as e: # noqa: BLE001
ok, msg = False, str(e)
self.q.put(('log', ('%s %s' % ('✔' if ok else '✘', msg))))
if ok and was_done:
self.q.put(('force_idle', '(%s后回到待机)' % name))
# 串口写在后台做:真秤应答慢时不卡界面
threading.Thread(target=work, daemon=True).start()
# ------------------------------------------------------------ 事件轮询
def _prof(self, tag, t0, force=False):
"""慢帧自检(v1.0.49):单个回调超过 80ms 记一条日志(同标签 20 秒
一条)。现场再反馈「卡」时,日志里能直接看出是哪个回调在拖,
不用再靠猜。v1.0.52 起 _poll 对每个事件处理器单独计时(ev:xxx)。"""
now = time.monotonic()
ms = (now - t0) * 1000.0
if ms < 80.0 and not force:
return
seen = getattr(self, '_prof_seen', None)
if seen is None:
seen = self._prof_seen = {}
if now - seen.get(tag, 0.0) < 20.0:
return
seen[tag] = now
self.log('[dev] UI 慢帧:%s 用时 %.0f ms' % (tag, ms))
def _poll(self):
_t0 = time.monotonic()
cb = getattr(self, '_detect_pending', None)
if cb is not None: # 自动识别收尾(worker 线程只放不放)
self._detect_pending = None
try:
cb()
except Exception:
pass
n = 0
try:
while True:
ev, payload = self.q.get_nowait()
n += 1
# 登录页期间只认登录结果,其余事件(旧引擎的称重/待办)丢掉
if not self.ready and ev not in ('login_ok', 'login_err',
'log'):
continue
handler = getattr(self, '_on_' + ev, None)
if handler:
# v1.0.52:每个处理器单独计时。上一版只知道「_poll 慢
# 500ms」,不知道慢在哪;这样日志会直接写 ev:weight /
# ev:manual … 哪一类事件拖的。
_h0 = time.monotonic()
try:
handler(payload)
except Exception as e: # 别让一个坏事件打死整个轮询
try:
self.log('❌ 界面事件 %s 出错:%s' % (ev, e))
except Exception:
pass
finally:
self._prof('ev:' + ev, _h0)
except queue.Empty:
pass
if n >= 12: # 一次轮询堆了十几条:界面确实被拖住过
self._prof('_poll-busy', _t0 - 0.5, force=True)
if self.ready:
self._tick_clock()
self._sync_camera_size()
self._dev_tick += 1
if self._dev_tick % 16 == 0: # 约 2 秒刷新一次设备状态
_d0 = time.monotonic()
self._refresh_devices()
self._prof('_refresh_devices', _d0)
if self._dev_tick % 240 == 0: # 约 30 秒报一次本进程 CPU
self._report_cpu()
self._prof('_poll', _t0)
self.root.after(120, self._poll)
# ------------------------------------------------- 弱机自检(v1.0.52)
def _cpu_pct(self):
"""本进程平均 CPU(单核 = 100%)。不引 psutil,直接问 Windows。"""
try:
import ctypes
from ctypes import wintypes
class FT(ctypes.Structure):
_fields_ = [('lo', wintypes.DWORD), ('hi', wintypes.DWORD)]
k32 = ctypes.WinDLL('kernel32', use_last_error=True)
k32.GetCurrentProcess.restype = wintypes.HANDLE
# 必须声明 argtypes:不声明时 ctypes 不会把 byref 的指针转好,
# 调用直接失败(返回 0),看起来就像「拿不到 CPU」。
k32.GetProcessTimes.argtypes = [
wintypes.HANDLE, ctypes.POINTER(FT), ctypes.POINTER(FT),
ctypes.POINTER(FT), ctypes.POINTER(FT)]
k32.GetProcessTimes.restype = wintypes.BOOL
h = k32.GetCurrentProcess()
def _q(ft):
return (ft.hi << 32) | ft.lo
out = []
for _ in range(4):
out.append(FT())
if not k32.GetProcessTimes(h, *[ctypes.byref(x) for x in out]):
return None
cpu = (_q(out[2]) + _q(out[3])) * 1e-7 # 100ns → 秒
now = time.monotonic()
prev = getattr(self, '_cpu_prev', None)
self._cpu_prev = (cpu, now)
if not prev:
return None
d_cpu = cpu - prev[0]
d_wall = max(1e-6, now - prev[1])
return max(0.0, min(999.0, 100.0 * d_cpu / d_wall))
except Exception:
return None
def _report_cpu(self):
pct = self._cpu_pct()
if pct is None:
return
self.log('[dev] 进程 CPU 平均 %.0f%%(单核=100%%,界面卡不卡主要看这条:'
'常年在 60%% 以上就该查是谁在烧)' % pct)
def _log_machine(self):
"""开机记一行机器信息:现场「卡」时先看这行就知道底子多弱。"""
name = ''
try:
import winreg
k = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
r'HARDWARE\DESCRIPTION\System\CentralProcessor\0')
name = str(winreg.QueryValueEx(k, 'ProcessorNameString')[0]).strip()
except Exception:
pass
mem = ''
try:
import ctypes
class MS(ctypes.Structure):
_fields_ = [('dwLength', ctypes.c_ulong),
('dwMemoryLoad', ctypes.c_ulong),
('ullTotalPhys', ctypes.c_ulonglong),
('ullAvailPhys', ctypes.c_ulonglong),
('ullTotalPageFile', ctypes.c_ulonglong),
('ullAvailPageFile', ctypes.c_ulonglong),
('ullTotalVirtual', ctypes.c_ulonglong),
('ullAvailVirtual', ctypes.c_ulonglong),
('ullAvailExtendedVirtual', ctypes.c_ulonglong)]
st = MS()
st.dwLength = ctypes.sizeof(MS)
if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(st)):
mem = ' · 内存 %.1f GB' % (st.ullTotalPhys / 1073741824.0)
except Exception:
pass
self.log('[dev] 机器:%s · %d 逻辑核%s · 解码上限 %.0f fps · 预览 %.1f fps'
% (name or '未知 CPU', os.cpu_count() or 1, mem,
1.0 / max(0.02, self.engine.frames.decode_gap()),
self._preview_fps()))
def _preview_fps(self):
"""预览刷新率(config ui.preview_fps 可改)。
默认 8 fps;摄像头那侧实测「解一帧偏慢」(frames.weak)就降到 6 fps。
预览是给人看「货在哪」的,8 帧已经够跟手,13 帧纯属白烧 CPU。
"""
try:
v = (self.cfg.get('ui') or {}).get('preview_fps')
fps = float(v) if v else 0.0
except (TypeError, ValueError):
fps = 0.0
if fps <= 0:
weak = bool(getattr(getattr(self.engine, 'frames', None),
'weak', False))
fps = 6.0 if weak else 8.0
return max(3.0, min(15.0, fps))
def _preview_ms(self):
return int(round(1000.0 / self._preview_fps()))
def _sync_camera_size(self):
"""摄像头自动降档后把实际分辨率写回配置(下次启动不再白等一遍)"""
fs = getattr(self.engine, 'frames', None)
note = getattr(fs, 'perf_note', '') if fs is not None else ''
if note and note != getattr(self, '_perf_note_done', None):
self._perf_note_done = note
self.log('[dev] ' + note)
fix = getattr(fs, 'auto_size', None)
if not fix:
return
fs.auto_size = None
cam = self.cfg.setdefault('camera', {})
if (int(cam.get('width') or 0), int(cam.get('height') or 0)) == \
(int(fix['width']), int(fix['height'])):
return
cam['width'] = int(fix['width'])
cam['height'] = int(fix['height'])
try:
save_config(self.cfg)
except Exception:
pass
self.log('摄像头不支持 %s,已自动改用 %dx%d'
% (fix.get('from') or '原档位', fix['width'], fix['height']))
# ------------------------------------------------------------ 画面缩放
def _zoom_step(self, d):
"""+ / − 按钮:0.5 倍一档,1.0~3.0(再大就是马赛克,没意义)"""
try:
cur = float(self.engine.frames.zoom or 1.0)
except Exception:
cur = 1.0
self._apply_zoom(round(cur + d, 2))
def _zoom_wheel(self, ev):
self._zoom_step(0.5 if getattr(ev, 'delta', 0) > 0 else -0.5)
return 'break'
def _apply_zoom(self, z, save=True):
"""改缩放:预览、AI 识别照片、留档照片同时生效(同一份裁剪)"""
try:
z = self.engine.frames.set_zoom(z)
except Exception:
return
self._paint_zoom(z)
if save:
try:
self.cfg.setdefault('camera', {})['zoom'] = z
save_config(self.cfg)
except Exception:
pass
self.log('[dev] 画面缩放 %.1f×(识别/留档同视角)' % z)
def _paint_zoom(self, z=None):
if z is None:
try:
z = float(self.engine.frames.zoom or 1.0)
except Exception:
z = 1.0
try:
self.lbl_zoom.configure(text='%.1f×' % z)
self.btn_zin.configure(state='normal' if z < 2.95 else 'disabled')
self.btn_zout.configure(state='normal' if z > 1.05 else 'disabled')
except Exception:
pass
def _note_motion(self, _e=None):
"""用户正在拖名单/滚轮:记时刻,_poll_preview 据此让路"""
self._motion_at = time.monotonic()
def _poll_preview(self):
_t0 = time.monotonic()
if not getattr(self, '_zoom_painted', False):
self._zoom_painted = True
self._paint_zoom()
if not self.ready:
self.root.after(300, self._poll_preview)
return
# v1.0.49:手指正在拖名单时不刷新预览(也不让它挤占解码)。
# 现场 1080p 相机一帧解码 + 缩放要几十毫秒,正好卡在拖动那几帧上,
# 表现就是「一拖就顿」。松手 0.3 秒后自动恢复。
busy = (time.monotonic() - getattr(self, '_motion_at', 0.0)) < 0.3
try:
self.engine.frames.set_low_power(busy)
except Exception:
pass
if busy:
self.root.after(self._preview_ms(), self._poll_preview)
return
frame, seq, _ = self.engine.frames.get_frame()
if frame is not None:
if seq != getattr(self, '_last_preview_seq', None):
self._last_preview_seq = seq
lw = self.preview_lbl.winfo_width()
lh = self.preview_lbl.winfo_height()
if lw < 80 or lh < 80:
lw, lh = self._px(430), self._px(242)
h, w = frame.shape[:2]
# 铺满预览框(cover)而不是 contain:以前按宽度缩到 16:9,
# 框比画面宽时两侧就是大片黑边,现场看着像「画面不对」。
# 现在按较大的比例缩放后居中裁掉溢出部分,画面始终填满。
scale = max(lw / float(w), lh / float(h))
nw = max(lw, int(round(w * scale)))
nh = max(lh, int(round(h * scale)))
# v1.0.49:4.5 倍缩小用 INTER_LINEAR 就够(肉眼无差),
# INTER_AREA 在 1080p 上每帧要多花一倍时间。
small = cv2.resize(frame, (nw, nh),
interpolation=cv2.INTER_LINEAR)
x0 = max(0, (nw - lw) // 2)
y0 = max(0, (nh - lh) // 2)
small = small[y0:y0 + min(lh, nh), x0:x0 + min(lw, nw)]
rgb = cv2.cvtColor(small, cv2.COLOR_BGR2RGB)
# v1.0.52:尺寸没变就复用同一个 Tk 图,用 paste 原地换像素。
# 原来每帧都新建 PhotoImage(等于在 Tk 里 create/destroy 一个
# 540×307 的图片对象),弱机上这一下就要 10~20ms,一秒十几次。
img_pil = Image.fromarray(rgb)
ph = getattr(self, '_tkimg', None)
reused = False
if ph is not None:
try:
if ph.width() == lw and ph.height() == lh:
ph.paste(img_pil)
reused = True
except Exception:
reused = False
if not reused:
self._tkimg = ImageTk.PhotoImage(img_pil)
self.preview_lbl.configure(image=self._tkimg, text='')
self.preview_lbl.image = self._tkimg
else:
# 无画面时把原因写在画面上,便于现场排查
st = self.engine.frames.preview_status()
if st != getattr(self, '_prev_status', None):
self._prev_status = st
self.preview_lbl.configure(image='', text=st,
fg='#e8e8e8',
font=self._font(12),
wraplength=self._px(580),
justify='center')
self.preview_lbl.image = None
self._tkimg = None
self._prof('_poll_preview', _t0)
self.root.after(self._preview_ms(), self._poll_preview)
def _keepalive(self):
"""空闲保活:防云端 TLS 冷启动(设计文档 §12)"""
import time as _t
while True:
_t.sleep(30)
c = self.engine.recog
if c.cfg.get('api_key'):
try:
c._chat([{'role': 'user', 'content': 'hi'}],
c.cfg.get('text_model'), 3)
except Exception:
pass
# ------------------------------------------------------------ 事件处理
def _on_weight(self, st):
w = st['weight']
# 显示只到 0.1 kg(现场反馈:到 0.01 kg 都在跳,看着像不稳)。
# 内部仍按 0.001 记录/提交,这里只做显示去噪。
if abs(w) < 0.05:
w = 0.0
self._last_w = w # 「这是一件新货」要拿它跟上一笔比重量
# v1.0.52:只有显示的字真变了才 configure。这个回调每秒跑 6~7 次,
# 秤不动的时候每次都去改 5 个 Label,等于每秒催 Tk 重排重画 30 多次
# —— 弱机上全是白烧的。
cache = getattr(self, '_w_cache', None)
if cache is None:
cache = self._w_cache = {}
def _set(widget, key, **kw):
val = tuple(sorted(kw.items()))
if cache.get(key) == val:
return
cache[key] = val
widget.configure(**kw)
# 大数字只放数值,"kg" 是旁边单独的标签;斤数跟在后面
_set(self.lbl_weight, 'w', text='%.1f' % w)
_set(self.lbl_jin, 'j', text='%.1f 斤' % (w * 2.0))
tare = st.get('tare') or 0.0
zero = st.get('zero') or 0.0
if abs(tare) >= 0.0005:
tare_txt = '去皮 %.2f kg' % tare
elif abs(zero) >= 0.0005:
tare_txt = '已置零 %+.2f kg' % (-zero)
else:
tare_txt = '未去皮'
_set(self.lbl_w_tare, 't', text=tare_txt)
_set(self.lbl_weight, 'wc',
fg=C.brand if (st['connected'] and st['fresh']) else C.ink3)
errs = []
if not st['connected']:
errs.append('未连接')
if not st['fresh']:
errs.append('数据过期')
if st['overload']:
errs.append('超载')
port = self.cfg.get('scale', {}).get('port', 'COM?')
if self.cfg.get('scale', {}).get('simulate'):
port = '模拟'
if errs:
err_txt = '%s · %s' % (port, '·'.join(errs))
_set(self.lbl_scale, 's', text=err_txt)
_set(self.lbl_w_tare, 't', text=err_txt)
_set(self.lbl_w_tare, 'tc', fg=C.red)
else:
_set(self.lbl_scale, 's', text='%s · 正常' % port)
_set(self.lbl_w_tare, 'tc', fg=C.ink3)
def _on_state(self, s):
idx = STEP_STATE.get(s, -1)
try:
self.step_bar.set_state(idx)
except Exception:
pass
no = '不称重' if self.engine.station == 'picking' else '免称重'
texts = {'IDLE': '待机中:请放货', 'WEIGHING': '称重中…',
'CAPTURE': '抓拍中…', 'RECOGNIZE': 'AI 识别中…',
'CONFIRM': '认出来了:请看一眼再确认',
'SUBMIT': '提交中…', 'PRINT': '打印标签…',
'DONE': '完成:请取走货物', 'MANUAL': '请人工确认',
'MATCH': '匹配名单中…',
'COUNT_CAPTURE': no + ':抓拍中…',
'COUNT_RECOGNIZE': no + ':AI 识别中…',
'COUNT_CONFIRM': no + ':请核对数量'}
# 同一句「认出来了」既用于「AI 命中某一行」,也用于「没认出、等人点选」。
# 没认出时必须说「未识别出来」,否则操作员会以为 AI 已经认对了
# (2026-11-25 现场反馈)。这里按引擎当前 focus 是否命中行来定。
recognized = True
if s == 'CONFIRM':
try:
fr = getattr(self.engine, '_focus', None) or {}
rid_f = fr.get('row_id')
recognized = bool(rid_f) and bool(
self.engine._row_by_id(rid_f))
except Exception:
recognized = False
if not recognized:
texts['CONFIRM'] = '未识别出来:请点右边那一行'
hints = {'IDLE': '放货 → 自动识别 → 取走货物',
'WEIGHING': '重量稳定后自动抓拍,请勿移动',
'CAPTURE': '抓拍留档中…', 'RECOGNIZE': '云端识别中,约 1~2 秒',
'MATCH': '正在比对当前账号待办名单',
'MANUAL': '点击屏幕选择商品或搜索名称',
'CONFIRM': '对就点左下「确认」;不对就点正确的那一行(等于改判)',
'SUBMIT': '正在提交,请勿取货',
'PRINT': '正在打印标签…', 'DONE': '取走货物后自动回到待机',
'COUNT_CAPTURE': no + ':不用放秤,镜头对准商品',
'COUNT_RECOGNIZE': '云端识别中,约 1~2 秒',
'COUNT_CONFIRM': '核对商品和数量后点「确认」'}
picking = (self.engine.station == 'picking')
try:
auto = self.engine.auto_noweigh_on()
except Exception:
auto = False
try:
confirm_on = self.engine.confirm_before_submit()
except Exception:
confirm_on = False
if confirm_on:
# 认出商品不再直接记账:跳到那一行等人点左列「确认」
texts['IDLE'] = '待机中:放货,认出来后点确认'
hints['IDLE'] = '放货 → AI 认出后跳到那一行 → 点左下「确认」'
hints['COUNT_CONFIRM'] = 'AI 拿不准才要你核对:确认商品和数量'
elif auto:
# 不称重的商品(袋/包/桶;分拣站还包括斤类)放上去就自动记账,
# 提示必须改成「不用点」,否则操作员会一直等按钮亮起来。
verb = '分拣' if picking else '入库'
texts['IDLE'] = '待机中:放货即自动%s' % verb
hints['IDLE'] = ('放上去就行:AI 自动识别并%s,不用点屏幕'
% verb)
hints['COUNT_CONFIRM'] = 'AI 拿不准才要你核对:确认商品和数量'
if picking and not auto and not confirm_on:
# 分拣位经常没秤。v1.0.53 起撤掉了「不称重分拣」按钮:
# 放货到镜头前画面一动就自动识别;想指定哪一行,直接点名单。
hints['IDLE'] = '放货到镜头前就自动识别;也可以直接点名单里那一行'
texts['IDLE'] = '待机中:放货,或点名单里的行'
col = {'MANUAL': C.amber, 'CONFIRM': C.brand, 'DONE': C.green,
'SUBMIT': C.brand,
'PRINT': C.brand, 'IDLE': C.ink}.get(s, C.ink)
if s == 'CONFIRM' and not recognized:
col = C.amber
self.lbl_state.configure(text=texts.get(s, s), fg=col)
# 状态点:待机绿 / 中途琥珀 / 完成绿 / 确认橙
dot = {'IDLE': C.green, 'DONE': C.green, 'MANUAL': C.amber,
'SUBMIT': C.brand}.get(s, C.amber)
try:
self._state_dot.itemconfigure(self._dot, fill=dot)
except Exception:
pass
# 提示行颜色也归位(待确认时会被改成琥珀色的警示语)
self.lbl_hint.configure(text=hints.get(s, ''), fg=C.ink2)
# 确认条只在 CONFIRM 状态存在:提交/放弃/超时立刻收起
if s != 'CONFIRM':
try:
self._show_focus_bar(False)
self._focus_p = None
except Exception:
pass
# 离开免称重确认态(提交成功/放弃/超时)就收起确认页,别让它挂在屏幕上
if s != 'COUNT_CONFIRM':
try:
if self._count_top is not None \
and self._count_top.winfo_exists():
self._count_top.destroy()
self._count_top = None
except Exception:
pass
def _on_pending(self, p):
rows = p.get('rows') or []
self.lbl_pending.configure(text='待办 %d 行' % len(rows))
self.lbl_account.configure(
text='账号:%s · %s' % (p.get('account') or
self.cfg['account'].get('username'),
'分拣员' if self.engine.station == 'picking'
else '验收员'))
self._fill_todo(rows)
# ------------------------------------------------------------ 搜索(键盘/语音/手写)
def _search_placeholder(self):
self._search_ph_on = True
self.ent_search.configure(fg='#aab2bd')
self.var_search.set('搜索商品 / 规格 / 单号 / 客户')
def _search_text(self):
if getattr(self, '_search_ph_on', False):
return ''
try:
return self.ent_search.get().strip()
except Exception:
return ''
def _search_focus_in(self, _e=None):
if self._search_ph_on:
self._search_ph_on = False
self.var_search.set('')
self.ent_search.configure(fg='#333333')
def _search_focus_out(self, _e=None):
osk = getattr(self, '_osk_win', None)
if (osk is not None and getattr(osk, 'target', None) is self.ent_search
and osk.is_visible()):
return
if not self.ent_search.get().strip():
self._search_placeholder()
def _on_search_changed(self, *_a):
"""边打边过滤(120ms 防抖,避免每个字母都重建卡片)"""
if getattr(self, '_search_ph_on', False):
return
if self._search_job:
try:
self.root.after_cancel(self._search_job)
except Exception:
pass
self._search_job = self.root.after(120, self._apply_search)
def _apply_search(self):
self._search_job = None
if not getattr(self, 'ready', False):
return
self._fill_todo(getattr(self, '_all_rows', []))
def _set_search_text(self, txt):
"""语音/手写结果回填:清占位 → 写词 → 立即过滤"""
txt = (txt or '').strip()
if not txt:
return
self._search_ph_on = False
self.ent_search.configure(fg='#333333')
self.var_search.set(txt)
try:
self.ent_search.icursor('end')
except Exception:
pass
def _clear_search(self):
self._search_ph_on = False
if self._search_job:
try:
self.root.after_cancel(self._search_job)
except Exception:
pass
self._search_job = None
self.var_search.set('')
self.ent_search.configure(fg='#333333')
self._apply_search()
try:
self.ent_search.focus_set()
except Exception:
pass
@staticmethod
def _row_match(r, words):
if not words:
return True
hay = ' '.join(str(r.get(k) or '') for k in (
'item_name', 'spec', 'sku_code', 'order_code', 'pick_code',
'category_name', 'category',
'customer_name', 'company_name', 'supplier_name', 'supplier')).lower()
return all(w in hay for w in words)
@staticmethod
def _who_of(r):
"""卡片上的“对方”:分拣是客户(company_name),入库是供应商(supplier_name)"""
return (r.get('customer_name') or r.get('company_name')
or r.get('supplier_name') or r.get('supplier') or '')
@staticmethod
def _std_name(r):
"""显示用的标准商品名(v1.0.59)
分拣待办行的 item_name 是客户下单写法(带括号注释、方言别名,
比如「上海青(小棠菜)」);服务端同一行还带 standard_name
(SKU 主档名,COALESCE(sku_name, catalog.name))。称重/确认
界面对人报标准名,没带这个字段的(入库行、mock)退回 item_name。
只改显示:记账、标签、台账仍按行上的下单名提交。
"""
try:
std = str((r or {}).get('standard_name') or '').strip()
except Exception:
std = ''
if std:
return std
try:
return str((r or {}).get('item_name') or '').strip() or '—'
except Exception:
return '—'
def _flash_search_tip(self, text, ms=6000):
try:
self._set_todo_detail(text, fg='#185fa5')
self.root.after(ms, lambda: self._set_todo_detail(''))
except Exception:
pass
def _voice_input(self):
"""语音输入:调 Windows 自带语音输入(Win+H),说的话直接落进搜索框"""
self._search_focus_in()
try:
import ctypes
u = ctypes.windll.user32
u.keybd_event(0x5B, 0, 0, 0) # Win 按下
u.keybd_event(0x48, 0, 0, 0) # H 按下
u.keybd_event(0x48, 0, 2, 0)
u.keybd_event(0x5B, 0, 2, 0) # 都松开
self._flash_search_tip(
'已打开系统语音输入:对着麦克风说商品名,说完自动填入搜索框')
except Exception as e:
self._flash_search_tip('语音输入不可用(%s),请用键盘或手写' % e)
# ---- 手写:内置键盘的手写视图(不是系统输入法,随时能切回 ABC)
def _handwriting(self):
"""点「手写」= 内置键盘切到写板,写完自动识别。
画板、候选、退格都在同一套键盘里,顶栏一键切回 ABC;
不再去调 Windows 触摸键盘(这台机器上它根本唤不出来)。
"""
try:
self._search_focus_in()
self.ent_search.focus_set()
self.ent_search.icursor('end')
self._last_input_w = self.ent_search
except Exception:
pass
if self._show_osk('hand', self.ent_search):
self._flash_search_tip(
'手写板已打开:写字停一下自动识别,点结果填进搜索框;'
'要打字母/数字就点键盘顶部的「⌨ ABC 键盘」')
else:
self._flash_search_tip('手写板打不开,请用外接键盘或「语音」')
# ------------------------------------------------------------ 展示维度
def _group_key(self, r):
"""一行属于哪个组:分拣看客户,入库看供应商;另可按分类"""
m = self._group_mode
if m == 'customer':
return self._who_of(r) or '(无客户/供应商)'
if m == 'category':
return str(r.get('category_name') or r.get('category')
or '(无分类)')
return ''
def _product_sort_key(self, r):
"""待拣/待验卡片按「商品名」相邻(同名商品挨在一起)。
用界面展示的标准名(standard_name 优先,回退 item_name)排序;
同名时保留服务端原始顺序(sorted 是稳定排序),不改变提交/记账顺序。
"""
std = self._std_name(r)
raw = str(r.get('item_name') or '')
return (std.casefold(), raw.casefold())
def _sort_rows_by_product(self, rows):
return sorted(rows, key=self._product_sort_key)
@staticmethod
def _qty_of(r):
q = r.get('remaining_qty')
if q is None:
q = r.get('required_qty')
if q is None:
q = r.get('prepare_qty')
try:
return float(q or 0), str(r.get('unit') or '')
except (TypeError, ValueError):
return 0.0, str(r.get('unit') or '')
def _group_values(self):
"""当前维度下有哪些值(按行数从多到少)"""
if self._group_mode == 'none':
return []
cnt = {}
for r in getattr(self, '_all_rows', []):
k = self._group_key(r)
cnt[k] = cnt.get(k, 0) + 1
return sorted(cnt.items(), key=lambda kv: (-kv[1], kv[0]))
def _paint_group_bar(self):
"""维度按钮 + 客户/分类下拉的当前状态"""
# 界面选了哪一家,引擎就得锁哪一家(幂等,不会刷日志)。
# 放在最前面:重登/换账号后引擎是新建的,锁要重新告诉它。
self._sync_scope()
try:
for key, b in getattr(self, '_group_btns', {}).items():
on = (key == self._group_mode)
b.configure(fill=C.brand if on else '#eaeff6',
fg='white' if on else C.ink2)
except Exception:
pass
dd = getattr(self, '_group_dd', None)
if dd is None:
return
# 名单一变(刷新/筛选)就把开着的下拉收起来:列表内容和标题不能对不上
self._close_group_dd()
if self._group_mode == 'none':
dd.pack_forget()
return
vals = self._group_values()
names = [v for v, _n in vals]
# 名单暂时为空(重连/刷新中途)时别把锁定清掉,等下一轮拿到行再说
if self._group_pick is not None and names and self._group_pick not in names:
self._group_pick = None
self._sync_scope()
if not dd.winfo_ismapped():
dd.pack(side='left', padx=(self._px(8), 0))
total = len(getattr(self, '_all_rows', []))
if self._group_pick is None:
txt = '全部 %d 行' % total
else:
# 锁着某一家时把「还剩几行」写出来:一路拣到 0 就知道这家完了
left = 0
try:
left = int(self.engine.scope_left())
except Exception:
left = 0
if left <= 0 and not getattr(self.engine, 'rows', None):
# 引擎还没拿到待办(登录前):按界面分组数报,别显示「剩 0 行」
left = dict(vals).get(self._group_pick, 0)
txt = '%s · 剩 %d 行' % (self._short_name(self._group_pick, 9),
left)
txt += ' ▾'
dd.configure(text=txt)
dd.configure(fill=C.brand_soft if self._group_pick else C.surface,
fg=C.brand if self._group_pick else C.ink)
# 宽度跟着文字走:短名字不留大片空白,长名字也不会被压成省略号
try:
w = tkfont.Font(font=self._font(12)).measure(txt) + self._px(40)
dd.configure(width=min(self._px(360),
max(self._px(150), w)))
except Exception:
pass
# ---- 客户/分类下拉(不用 Combobox:系统下拉行高约 20px,触摸屏点不准)
@staticmethod
def _short_name(s, n=9):
s = str(s or '')
return s if len(s) <= n else s[:n] + '…'
def _toggle_group_dd(self):
if getattr(self, '_group_pop', None) is not None:
self._close_group_dd()
else:
self._open_group_dd()
def _open_group_dd(self):
px, font = self._px, self._font
dd = getattr(self, '_group_dd', None)
if dd is None or self._group_mode == 'none':
return
vals = self._group_values()
if not vals:
return
total = len(getattr(self, '_all_rows', []))
items = [('全部(%d 行)' % total, None)]
items += [('%s(%d 行)' % (self._short_name(v, 16), n), v)
for v, n in vals]
row_h = px(48) # 触摸目标 48px,跟维度按钮同量级
w = max(dd.winfo_width(), px(240))
pop = tk.Toplevel(self.root)
pop.overrideredirect(True)
pop.configure(bg=C.line) # 1px 描边,白底浮在列表上不糊
try:
pop.attributes('-topmost', True)
except Exception:
pass
self._group_pop = pop
# 能放多高就放多高:原来死写 8 行,客户一多就得往下拖,而拖动又会
# 立刻选中手指停住的那一家 —— 现场的现象就是「客户列表滑不动」。
try:
sh0 = pop.winfo_screenheight()
except Exception:
sh0 = 900
fit = max(4, int((sh0 - px(180)) / float(row_h)))
shown = min(len(items), fit)
shell = tk.Frame(pop, bg=C.surface)
shell.pack(fill='both', expand=True, padx=px(1), pady=px(1))
cv = tk.Canvas(shell, bg=C.surface, highlightthickness=0, bd=0,
width=max(1, w - px(2)), height=row_h * shown)
cv.pack(side='left', fill='both', expand=True)
inner = tk.Frame(cv, bg=C.surface)
win_id = cv.create_window(0, 0, window=inner, anchor='nw')
for txt, val in items:
on = (val == self._group_pick)
row = tk.Frame(inner, height=row_h, bg=C.brand_soft if on
else C.surface)
row.pack(fill='x')
row.pack_propagate(False)
lbl = tk.Label(row, text=txt, anchor='w', font=font(14),
bg=row['bg'], fg=C.brand if on else C.ink,
padx=px(16))
lbl.pack(fill='both', expand=True)
# 选中改到「按下→松手没挪过」:拖动列表时别把手指定住的那家选中
key = ('grp', val)
def on_press(e, k=key):
self._tap.press(e, k)
def on_motion(e):
self._tap.motion(e)
def on_release(e, k=key, v=val):
if self._tap.release(e, k):
self._pick_group(v)
for _w in (row, lbl):
_w.bind('<ButtonPress-1>', on_press, add='+')
_w.bind('<B1-Motion>', on_motion, add='+')
_w.bind('<ButtonRelease-1>', on_release, add='+')
if not on: # 悬停高亮,鼠标点也有反馈
row.bind('<Enter>', lambda e, r=row, g=lbl: (
r.configure(bg='#f1f5fb'), g.configure(bg='#f1f5fb')))
row.bind('<Leave>', lambda e, r=row, g=lbl: (
r.configure(bg=C.surface), g.configure(bg=C.surface)))
lbl.bind('<Enter>', lambda e, r=row, g=lbl: (
r.configure(bg='#f1f5fb'), g.configure(bg='#f1f5fb')))
lbl.bind('<Leave>', lambda e, r=row, g=lbl: (
r.configure(bg=C.surface), g.configure(bg=C.surface)))
inner.update_idletasks()
# 必须显式给内容窗口定宽:create_window 时内层还是 0 宽,
# 之后往里塞行也不会自动撑开,画出来就是一片空白
cv.itemconfigure(win_id, width=max(1, w - px(2)))
ch = inner.winfo_reqheight()
cv.configure(scrollregion=(0, 0, max(1, w - px(2)), ch))
# 组数多时手指往下拖(滚轮也走同一个 TouchScroll,绑在孩子控件上,
# 光标停在某一行上也能滚)
self._group_scroll = TouchScroll(cv)
self._group_scroll.attach_tree(inner)
h = row_h * shown + px(2)
x = dd.winfo_rootx()
y = dd.winfo_rooty() + dd.winfo_height() + px(4)
sw, sh = pop.winfo_screenwidth(), pop.winfo_screenheight()
if y + h > sh - px(8): # 下面放不下就往上翻
y = max(px(8), dd.winfo_rooty() - h - px(4))
if x + w > sw - px(8):
x = max(px(8), sw - w - px(8))
pop.geometry('%dx%d+%d+%d' % (w, h, x, y))
# 点别处收起:绑在 root 上,卡片/画布里的点击也能兜住
self._dd_bind = self.root.bind('<Button-1>', self._dd_outside,
add='+')
def _pick_group(self, val):
self._close_group_dd()
self._set_group_pick(val)
def _dd_outside(self, e):
"""下拉开着时点了别处就收起(点下拉按钮本身交给按钮自己收)"""
if getattr(self, '_group_pop', None) is None:
return
w = getattr(e, 'widget', None)
if self._is_inside(w, self._group_pop) \
or self._is_inside(w, getattr(self, '_group_dd', None)):
return
self._close_group_dd()
@staticmethod
def _is_inside(widget, ancestor):
if widget is None or ancestor is None:
return False
while widget is not None:
if widget is ancestor:
return True
widget = getattr(widget, 'master', None)
return False
def _close_group_dd(self):
pop = getattr(self, '_group_pop', None)
if pop is None:
return
self._group_pop = None
fid = getattr(self, '_dd_bind', None)
if fid:
try:
self.root.unbind('<Button-1>', fid)
except Exception:
pass
self._dd_bind = None
try:
pop.destroy()
except Exception:
pass
def _set_group_mode(self, mode):
if mode == self._group_mode:
mode = 'none' if mode != 'none' else mode
self._group_mode = mode
self._group_pick = None
# v1.0.70:切分组方式必须整表重建。不分组那条增量路径只改卡上的
# 字,不会拆掉上一模式留下的分组标题 —— 现场「按供应商」切回
# 「不分组」后页头一直挂在那里,占掉一行,最底一行被裁。
self._shown_ids = None
self._layout_key = None
self.cfg.setdefault('ui', {})['todo_group'] = mode
try:
save_config(self.cfg)
except Exception:
pass
self._sync_scope()
self._paint_group_bar()
self._fill_todo(getattr(self, '_all_rows', []))
self._refocus_current()
def _set_group_pick(self, val):
self._group_pick = val
self._sync_scope()
self._paint_group_bar()
self._fill_todo(getattr(self, '_all_rows', []))
self._refocus_current()
def _refocus_current(self):
"""选完客户(v1.0.60):把秤上认出/预选的那行翻到它所在的一页。
名单重建后停在第一页,认出的那张卡可能在后面几页——不翻过去,
现场看就是「选了客户,识别的商品没跳到对应卡片」。
锁定的客户和这一行对不上(这件是别家的货)时只提示,不乱翻,
更不能把锁定放开去够别家的卡。
"""
try:
# 引擎已把范围外的预选撤了(set_scope_who),界面高亮跟着撤
pre = getattr(self, '_pre_rid', None)
if pre and pre not in self.todo_cards:
self._pre_rid = None
self._repaint_cards([pre])
rid = None
p = self._focus_p
if p and p.get('row_id') is not None:
rid = str(p.get('row_id'))
elif getattr(self, '_pre_rid', None):
rid = str(self._pre_rid)
if not rid:
return
row = None
for r in getattr(self, '_all_rows', []):
if str(r.get('id')) == rid:
row = r
break
if (self._group_mode != 'none' and self._group_pick
and row is not None
and self._group_key(row) != self._group_pick):
who = self._short_name(self._group_pick, 12)
other = self._short_name(self._who_of(row) or '别家', 12)
self.log('这一件是「%s」的货,不在锁定的「%s」名单里'
% (other, who))
if p:
try:
self.lbl_hint.configure(
text='已锁定「%s」:这一件是「%s」的货,'
'点右边的卡改判,或换回「全部」'
% (who, other),
fg=C.amber)
except Exception:
pass
return
# 搜索词挡住了就先放开(客户锁定不动,_reveal_row 会清锁定不能用)
if rid not in self.todo_cards:
self._search_ph_on = False
try:
self.var_search.set('')
except Exception:
pass
self._fill_todo(getattr(self, '_all_rows', []))
c = self.todo_cards.get(rid)
if c is None:
return
self._paint_focus(rid)
self._scroll_to(c)
except Exception:
pass
def _sync_scope(self):
"""把「界面上选了哪一家」告诉引擎(v1.0.57)。
以前只把别家的卡藏起来,引擎还拿全部待办去匹配:同一件大葱会被
记到别家的同名行上,合并入库还会跨客户凑单 —— 现场的感受就是
「选了这家还在拣别人家的货」。
"""
who = self._group_pick if self._group_mode == 'customer' else None
try:
self.engine.set_scope_who(who)
except Exception:
pass
def _row_stocked(self, r):
"""这一行是不是刚由本机提交过(服务端还要等一轮轮询才撤下)"""
try:
return bool(self.engine._is_stocked(r.get('id')))
except Exception:
return False
def _advance_group_if_done(self):
"""锁定某一家客户时:这家拣完了自动切到下一家还有货的。
「选了一个客户就一直拣这家,直到拣完」—— 拣完之后不该停在一张空
名单上等人来点下拉。全都没货了才回到「全部」。
"""
if self._group_mode != 'customer' or not self._group_pick:
return False
# 手上还有一件在识别/确认/提交时别换名单:换掉会让确认条指着
# 一张已经不在界面上的卡。等这一件落定(回待机)再切。
if str(getattr(self.engine, 'state', 'IDLE')) not in ('IDLE', 'DONE'):
return False
rows = list(getattr(self, '_all_rows', []))
if not rows:
return False # 名单暂时空(重连/刷新)不算「拣完了」
done = self._group_pick
if any(self._group_key(r) == done and not self._row_stocked(r)
for r in rows):
return False
cnt = {}
for r in rows:
if self._row_stocked(r):
continue
k = self._group_key(r)
if k == done:
continue
cnt[k] = cnt.get(k, 0) + 1
if not cnt:
self._group_pick = None
self._sync_scope()
note = '「%s」拣完了 · 全部待办都处理完了' % done
else:
nxt = sorted(cnt.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]
self._group_pick = nxt
self._sync_scope()
note = ('「%s」拣完了,自动切到「%s」(还剩 %d 行)'
% (done, nxt, cnt[nxt]))
try:
self.engine.emit('log', note)
except Exception:
pass
# 排完版再提示(_todo_tail 会把详情行重写一遍)
try:
self.root.after(120, lambda t=note: self._flash_search_tip(t, 9000))
except Exception:
pass
return True
# ------------------------------------------------------------ 识别确认条
def _build_focus_bar(self, parent):
"""v1.0.61:确认弹条整块撤掉(现场要求「结果跳到对应卡片,不要弹窗」)。
原来这里是一张卡片:左边抓拍图、中间 AI 结论、右边「确认记账/重拍/
放弃」。现在确认动作交给左列的手动抓拍旁边那颗大「确认」按钮,
结论写进左侧状态卡的提示行,重拍/放弃做成同一行的小按钮 ——
屏幕上不再整块弹东西出来。
只保留状态位:_focus_p 有没有待确认件、_focus_vis 是否处于确认态、
_focus_busy 防连点;数量留在 var_fqty(免称重核对页自己也有输入)。
"""
self._focus_vis = False
self._focus_p = None
# 提交在途:这段时间里再点卡片不算(防止连点/滑手把同一件货打两张标签)
self._focus_busy = False
self.var_fqty = tk.StringVar(value='1')
self.focus_bar = None
def _show_focus_bar(self, on):
"""v1.0.61:没有确认条了 —— 只切「有没有待确认件」的状态位,
再同步左列那三个按钮(确认 / 重拍 / 放弃)。"""
self._focus_vis = bool(on)
self._sync_big_confirm()
def _pending_hint(self, f):
"""待确认件的提示语(写进左侧状态卡第二行)。
这行只有 ~380px 宽,写长了会被右边缘裁掉半个字(现场看着像「· 王记
饭」)。所以只留一眼要判断的信息:AI 认的和命中的不一样才提、把握
多少、下单名对照、这一件记多少、哪一家;kg 读数就在下面的重量卡上,
不重复占字。
"""
row = (f or {}).get('row') or {}
det = str((f or {}).get('detected') or '').strip()
conf = (f or {}).get('conf')
mode = (f or {}).get('mode') or 'weigh'
if not row:
if det:
msg = 'AI 识别为「%s」但不在名单,没认出对应行,请点右边或重拍' % det[:14]
else:
msg = '没认出是哪一件,请点右边对应商品或重拍'
return msg, f.get('warn') or ''
name = self._std_name(row)
bits = []
if det and det != name:
bits.append('AI 认为「%s」%s'
% (det[:14], '' if conf is None
else '(%d%%)' % int(conf)))
elif conf is not None:
bits.append('把握 %d%%' % int(conf))
order_name = str(row.get('item_name') or '').strip()
if order_name and order_name != name:
bits.append('下单名「%s」' % order_name[:16])
if mode == 'count':
q = float(f.get('business') or 0)
if f.get('from_scale'):
bits.append('数量 %.2f %s(按秤)'
% (q, f.get('unit') or ''))
else:
bits.append('数量按待办 %g %s' % (q, f.get('unit') or ''))
else:
w = float(f.get('weight') or 0)
bits.append('%.2f kg → 记 %.2f %s'
% (w, float(f.get('business') or 0),
f.get('unit') or ''))
who = self._who_of(row) if row else ''
if who:
bits.append(str(who))
line = '%s · %s' % (name, ' · '.join(bits)) if bits else name
return line, f.get('warn') or ''
def _on_focus(self, p):
"""引擎说「认出这一行了,等你点头」:跳到那张卡、高亮、亮左列「确认」"""
self._focus_p = p or {}
f = self._focus_p
rid = f.get('row_id')
row = f.get('row') or {}
mode = f.get('mode') or 'weigh'
# 引擎接管高亮:清掉「手动点过的那行 / 空秤预选」的琥珀框。
# 不然确认行(绿)会和之前点过的那张(琥珀)同时亮,看着像选了两张。
# v1.0.75:这里先只记账,真正的重画交给下面的 _reveal_row
# → _paint_focus 一次性做掉(撤琥珀 + 换确认行同一个 configure 批次)。
old_hl = [getattr(self, '_sel_rid', None),
getattr(self, '_pre_rid', None)]
self._sel_rid = None
self._pre_rid = None
self._hl_pending = [x for x in old_hl if x]
self._show_focus_bar(True)
# v1.0.61:不再弹确认条 —— 结论压成状态卡下面那一行提示,
# 有警示语就整行变琥珀色且顶到最前面。
line, warn = self._pending_hint(f)
try:
if warn:
self.lbl_hint.configure(text=warn, fg=C.amber)
else:
self.lbl_hint.configure(text=line, fg=C.ink2)
except Exception:
pass
# 标题跟着「这一件有没有认出来」走:AI 没命中任何一行时也会进 CONFIRM
# 让人手动点选,此时不能写「认出来了」(2026-11-25 现场反馈:
# 没识别却显示已识别,操作员以为已经确认了)。
try:
if row:
self.lbl_state.configure(text='认出来了:请看一眼再确认',
fg=C.brand)
else:
self.lbl_state.configure(text='未识别出来:请点右边那一行',
fg=C.amber)
except Exception:
pass
# 数量:数件的才用得上(称重路径数量就是秤读数)。
# 没有确认条上的步进器了,这里只把待办数量放进 var_fqty,
# 真要改数量去点那一行进免称重核对页(那里有完整的加减)。
if mode == 'count':
try:
qv = float(f.get('business'))
except (TypeError, ValueError):
qv = 0.0
try:
self.var_fqty.set('%g' % max(0.0, qv))
except Exception:
pass
# 跳过去 + 高亮(翻到那张卡所在的一页)
self._reveal_row(rid)
# 点「作废重拍」后若仍未识别出商品,弹出自定义美观提示窗
was_retry = bool(getattr(self, '_retry_pending', False))
self._retry_pending = False
if row:
self._close_unrecognized_popup()
elif was_retry:
self._show_unrecognized_popup(f)
def _close_unrecognized_popup(self):
pop = getattr(self, '_unrec_pop', None)
self._unrec_pop = None
if pop is not None:
try:
pop.destroy()
except Exception:
pass
def _show_unrecognized_popup(self, f=None):
"""作废重拍后仍未识别出来:自定义圆角轻模态提示窗(不用系统默认弹窗)。"""
self._close_unrecognized_popup()
px, font = self._px, self._font
f = f or {}
det = str(f.get('detected') or '').strip()
top = tk.Toplevel(self.root)
self._unrec_pop = top
top.overrideredirect(True)
top.configure(bg='#cbd5e1')
try:
top.transient(self.root)
top.attributes('-topmost', True)
except Exception:
pass
ww, hh = px(440), px(290)
try:
rx = self.root.winfo_rootx() + (self.root.winfo_width() - ww) // 2
ry = self.root.winfo_rooty() + (self.root.winfo_height() - hh) // 2
except Exception:
rx = (top.winfo_screenwidth() - ww) // 2
ry = (top.winfo_screenheight() - hh) // 2
top.geometry('%dx%d+%d+%d' % (ww, hh, max(0, rx), max(0, ry)))
# 外框细描边 + 内部白底卡片
shell = tk.Frame(top, bg='#ffffff', padx=px(24), pady=px(22))
shell.pack(fill='both', expand=True, padx=2, pady=2)
# 顶部柔和红底圆形感叹号图标
ic = tk.Canvas(shell, width=px(56), height=px(56), bg='#ffffff',
highlightthickness=0, bd=0)
ic.pack(pady=(0, px(10)))
ic.create_oval(px(2), px(2), px(54), px(54),
fill='#fde8e8', outline='#fecaca', width=2)
ic.create_text(px(28), px(28), text='!', fill='#dc2626',
font=font(26, 'bold'))
tk.Label(shell, text='未能识别出商品', font=font(19, 'bold'),
bg='#ffffff', fg=C.ink).pack()
if det:
desc = ('AI 识别为「%s」,但不在当前待办名单中。\n'
'请调整货品位置后重拍,或直接在右侧手动点选。' % det[:16])
else:
desc = ('重拍后仍未识别出当前货品。\n'
'请调整货品摆放或光线后重试,也可直接在右侧点选。')
tk.Label(shell, text=desc, font=font(12), bg='#ffffff', fg=C.ink2,
justify='center', wraplength=px(380)).pack(
pady=(px(8), px(18)))
btns = tk.Frame(shell, bg='#ffffff')
btns.pack(fill='x', side='bottom')
def _retry_again():
self._close_unrecognized_popup()
self._focus_retry()
TouchButton(btns, text='再次重拍', command=_retry_again,
fill=C.brand_soft, fg=C.brand, height=px(46),
radius=px(14), font=font(14, 'bold'),
surface='#ffffff').pack(
side='left', fill='x', expand=True, padx=(0, px(10)))
TouchButton(btns, text='去手动选择',
command=self._close_unrecognized_popup,
fill='#dc2626', fg='white', height=px(46),
radius=px(14), font=font(14, 'bold'),
surface='#ffffff').pack(
side='left', fill='x', expand=True)
top.bind('<Escape>', lambda _e: self._close_unrecognized_popup())
try:
top.lift()
top.focus_force()
except Exception:
pass
def _on_focus_clear(self, _p=None):
self._focus_p = None
self._show_focus_bar(False)
try:
self._paint_focus(None)
except Exception:
pass
# 提示行交还给状态机(否则会一直挂着上一件的结论)
try:
self._on_state(str(getattr(self.engine, 'state', 'IDLE')))
except Exception:
pass
self._sync_big_confirm()
def _reveal_row(self, rid):
"""把待办列表滚到那一行并高亮 —— 这就是「AI 跳到对应商品名去」"""
if rid is None:
self._paint_focus(None)
return
rid = str(rid)
if rid not in self.todo_cards:
# 被搜索词或分组筛选挡住了:先放开筛选,否则卡片根本不存在
self._search_ph_on = False
try:
self.var_search.set('')
except Exception:
pass
self._group_pick = None
self._fill_todo(getattr(self, '_all_rows', []))
self._paint_focus(rid)
c = self.todo_cards.get(rid)
if c is None:
return
self._scroll_to(c)
def _card_style(self, rid):
"""这张卡此刻应有的边框颜色
优先级:确认态那一行(红)> 最后点过的那张(琥珀)> 普通
v1.0.69:只变颜色、**不变边框粗细**。以前确认行是 4px、其余 2px,
一张卡变粗就把它那一行撑高 4px,整列跟着重排 —— 现场就是
「一点卡片界面就抖」。现在所有卡片统一 CARD_HL 浅灰,选中/确认只换色。
琥珀只有一个来源:`_sel_rid`(最后点过的那张),和上方详情行
同源——点哪张就亮哪张,不会出现“亮的是盐、详情写腐竹”。
以前看两个变量(手点 + 引擎预选),两者不同步时就是两张同时亮。
"""
rid = str(rid)
fp = getattr(self, '_focus_p', None) or {}
if fp.get('row_id') is not None and str(fp.get('row_id')) == rid:
return CARD_FOCUS_BORDER
if str(getattr(self, '_sel_rid', '') or '') == rid:
return C.amber
return C.line
def _repaint_cards(self, rids):
"""只重画「高亮真的变了」的那几张卡(v1.0.56)
原来 _select_card / _paint_focus / _on_preselect 三处都遍历全部卡片
configure 一遍:120 行时一次点击 35ms(现场 i5 要 100ms+),日志里
那些「ev:focus 用时 438 ms」就是这么来的。改完一次点击最多碰 2 张。
v1.0.69:只改颜色(不碰粗细)—— 粗细一变几何就变,
grid 重排让整屏卡跟着跳。
v1.0.75:连**背景色也不改**(ui.focus_fill=true 才恢复粉底)。
实测(tools/probe:点一次卡,逐 1~16ms 采样 + 逐帧比像素):
· 卡片 x/y/宽 高全程一个像素都没动,没有重排、没有翻页;
· 屏幕上真正变化的只有三块:两张卡整块换色(190×121 ×2)、
左列「确认「X」」按钮上的白字、状态卡第二行提示。
也就是说「点一下界面抖」不是布局在动,是**两张卡整块粉底+红框
在同一帧里互换**——大面积色块跳位置,看着就是闪/抖。
现在高亮只留 4px 红边 + 数量数字变红(真正重绘面积从约 46000
像素降到约 2000),颜色没变就一个 configure 都不发。
"""
cache = getattr(self, '_paint_cache', None)
if cache is None:
cache = self._paint_cache = {}
cards = getattr(self, 'todo_cards', {})
fill = bool(self._get('ui.focus_fill', False))
for rid in rids:
if rid is None:
continue
rid = str(rid)
c = cards.get(rid)
if c is None:
continue
color = self._card_style(rid)
if cache.get(rid) == color:
continue # 没变,一个 configure 都不发
cache[rid] = color
is_focus = (color == CARD_FOCUS_BORDER)
bg = CARD_FOCUS_BG if (is_focus and fill) else C.surface
qty_fg = CARD_FOCUS_BORDER if is_focus else C.green
try:
# 粗细只在真不一致时写回(创建时已是 CARD_HL)。Tk 的 Frame
# 把 highlightthickness 算进请求尺寸,无谓地反复写它等于每
# 次点击都让 Tk 重算一遍几何。
if int(c.cget('highlightthickness')) != CARD_HL:
c.configure(highlightthickness=CARD_HL)
c.configure(highlightbackground=color, highlightcolor=color)
if str(c.cget('bg')) != bg:
c.configure(bg=bg)
for attr in ('_name_lbl', '_meta_lbl', '_qty_lbl',
'_thumb_label'):
w = getattr(c, attr, None)
if w is None:
continue
if attr == '_qty_lbl' and str(w.cget('fg')) != qty_fg:
w.configure(fg=qty_fg)
if str(w.cget('bg')) != bg:
w.configure(bg=bg)
except Exception:
pass
def _paint_focus(self, rid):
old = getattr(self, '_focus_rid', None)
self._focus_rid = None if rid is None else str(rid)
# v1.0.75:_on_focus 先把「琥珀框要撤掉哪几张」记在这里,
# 和「旧确认行 / 新确认行」合成**一次** _repaint_cards —— 一次点击
# 只发一轮 configure,不会出现两张卡先各自闪一下再互换的过程。
extra = getattr(self, '_hl_pending', None) or []
self._hl_pending = None
self._repaint_cards(list(extra) + [old, self._focus_rid])
def _on_preselect(self, rid):
"""引擎回的「空秤预选」:只记录,不重画
高亮已经由 _select_card 当场画好了(点哪张亮哪张),这里再动会和
「最后点过谁」打架。事件是排队来的,旧事件晚到时直接丢掉。
只有一种例外:界面还没有选中行(比如刚从确认态回来),才把引擎
的预选补成选中,别让预选变哑炮。
"""
rid = str(rid)
cur = str(getattr(self.engine, '_pre_pick_rid', None) or '')
if cur != rid:
return # 过期的旧事件,丢掉
self._pre_rid = rid
if not str(getattr(self, '_sel_rid', '') or ''):
self._sel_rid = rid
self._repaint_cards([rid])
def _scroll_to(self, card, _retry=0):
"""v1.0.58:名单不滚动了,「跳过去」= 翻到这张卡所在那一页"""
try:
pg = getattr(self, '_page_of', {}).get(id(card))
if pg is None:
# 分批建卡时这张可能还没建出来/还没摆上,稍后再试
if _retry < 10:
self.root.after(
150, lambda: self._scroll_to(card, _retry + 1))
return
if pg != self._page:
self._page = pg
self._layout_cards()
except Exception:
pass
def _focus_pick(self, rid):
"""确认状态下点别的卡 = 改判"""
ok, msg = self.engine.pick_focus(rid)
if not ok and msg:
self._set_todo_detail(msg, fg=C.red)
def _capture_or_retry(self):
"""手动抓拍 / 重拍合一(v1.0.62)
没有待确认件 = 手动抓拍识别;正等着确认 = 作废这一件重新抓拍
(原来单独那颗「重拍」)。按钮文案跟着切,操作员看字就知道
现在按下去会发生什么。
"""
if getattr(self, '_focus_vis', False) and self._focus_p:
self._focus_retry()
return
self.engine.manual_capture()
def _big_confirm(self):
"""左列大「确认」按钮:等价于原来确认条上的「确认记账」。
只有确认条开着(有待确认件)才响应,其余时候按钮是置灰的。
"""
if not getattr(self, '_focus_vis', False) or not self._focus_p:
return
self._focus_confirm()
def _sync_big_confirm(self):
"""左列三颗按钮的状态跟着「有没有待确认件」走(v1.0.61)。
点亮时把品名写到大「确认」上,操作员瞄一眼就知道这下确认的是哪件;
v1.0.62 起「重拍」并进了抓拍按钮 —— 有待确认件时它变「作废重拍」,
「放弃」仍只在确认态可点,平时置灰。
"""
b = getattr(self, 'btn_confirm', None)
if b is None:
return
try:
on = bool(getattr(self, '_focus_vis', False)
and self._focus_p)
name = ''
if on:
row = (self._focus_p or {}).get('row') or {}
if row:
name = self._std_name(row)
b.configure_btn(
text=('确认「%s」' % name[:10]) if on and name else '确认',
enabled=on)
cap = getattr(self, 'btn_capture', None)
if cap is not None:
cap.configure_btn(text='作废重拍' if on else '手动抓拍识别')
c = getattr(self, 'btn_cancel', None)
if c is not None:
c.configure_btn(enabled=on)
except Exception:
pass
def _focus_confirm(self):
if getattr(self, '_focus_busy', False):
return # 上一次确认还在提交,连点不重复记账/打单
p = self._focus_p or {}
qty = None
if p.get('mode') == 'count':
try:
qty = float(self.var_fqty.get())
except (TypeError, ValueError):
messagebox.showwarning('数量不对', '数量请填数字,例如 1 或 2。',
parent=self.root)
return
if qty <= 1e-6:
# 还没选商品时待办给的数量就是 0,别只丢一句「必须大于 0」
if not p.get('row'):
messagebox.showwarning(
'还没选商品',
'先在右边点一下这次要记账的那一行。\n\n'
'按斤/公斤称重的行:点完就按秤上读数记,不用填数量;\n'
'按件/按桶/按袋的行:点完在「数量」里填实际点数。',
parent=self.root)
else:
messagebox.showwarning(
'数量不对', '数量要大于 0,请点「+」或直接输入。',
parent=self.root)
return
ok, msg = self.engine.confirm_focus(qty)
if not ok:
messagebox.showwarning('不能记账', msg, parent=self.root)
return
self._focus_busy = True
def _release():
self._focus_busy = False
try:
self.root.after(1500, _release)
except Exception:
self._focus_busy = False
def _focus_cancel(self):
self._retry_pending = False
self._close_unrecognized_popup()
self.engine.cancel_focus('放弃这一件(未记账)')
def _focus_retry(self):
"""重拍:放弃这一件,再起一轮识别"""
st = self.engine.state
count = (self._focus_p or {}).get('mode') == 'count'
self._retry_pending = True
self._close_unrecognized_popup()
self.engine.cancel_focus('重拍:本件作废')
if count:
self._start_count()
else:
try:
self.engine.force_idle('重拍:清掉上一件,等重新放货')
except Exception:
pass
def _fill_todo(self, rows):
"""待办名单铺到右列卡片网格;有搜索词时只画匹配的卡
分组维度(客户/分类)打开时,先插一条分节标题再摆该组的卡;
选中某个客户就只画那一家 —— 一趟货给谁拣,一眼能看出来。
"""
picking = self.engine.station == 'picking'
self._all_rows = list(rows)
# 这家拣完了就自动换下一家(只在这一步判,避免递归重排)
try:
self._advance_group_if_done()
except Exception:
pass
kw = self._search_text()
words = [w for w in kw.lower().split() if w]
show = [r for r in self._all_rows if self._row_match(r, words)]
if self._group_mode != 'none' and self._group_pick:
show = [r for r in show if self._group_key(r) == self._group_pick]
# 2026-11-24:待拣/待验卡片按商品名相邻;同名保留原顺序。
# 分组模式(客户/分类)下在组内排序,不跨组打散客户/分类。
if self._group_mode == 'none':
show = self._sort_rows_by_product(show)
# 现场已统一成商品入库(不再有独立入库/无单直入),标题保持简洁不与右侧合计重叠
if words:
self.lbl_todo_title.configure(
text='待办 · 匹配 %d/%d 行'
% (len(show), len(self._all_rows)))
else:
self.lbl_todo_title.configure(
text='待办名单(%d 行)' % len(self._all_rows))
totals = {}
for r in show:
q, unit = self._qty_of(r)
totals[unit] = totals.get(unit, 0.0) + q
ids = [str(r.get('id')) for r in show]
# v1.0.47 增量更新:行没变就只改卡片文字,绝不销毁重建。
# 原来每次刷新都全量重建,120 行要 ~1 秒 —— 现场每提交一单待办
# 都会变,界面跟着冻一下,拖动/提交都显得卡。
# 注意这段必须在下面「销毁全部卡片」之前判断,否则卡片已经没了。
if (self._group_mode == 'none' and self.todo_cards
and not getattr(self, '_hdr_widgets', None)
and getattr(self, '_shown_ids', None) == ids):
for r in show:
self._update_card(r)
self._todo_tail(picking, show, words, kw, totals)
return
# 只是少了行(提交完/清零):销毁那几张,其余原地不动
if (self._group_mode == 'none' and getattr(self, '_shown_ids', None)
and not getattr(self, '_hdr_widgets', None)
and set(ids) < set(self._shown_ids)):
gone = [x for x in self._shown_ids if x not in set(ids)]
for rid in gone:
c = self.todo_cards.pop(rid, None)
self.todo_rows.pop(rid, None)
if c is not None:
try:
c.destroy()
except Exception:
pass
self._grid_items = [('card', self.todo_cards[x])
for x in ids if x in self.todo_cards]
for r in show:
self._update_card(r)
self._shown_ids = ids
self._todo_tail(picking, show, words, kw, totals)
self._layout_cards()
return
for w in getattr(self, 'todo_cards', {}).values():
w.destroy()
for h in getattr(self, '_hdr_widgets', []):
try:
h.destroy()
except Exception:
pass
self._hdr_widgets = []
self._grid_items = []
self.todo_cards = {}
self.todo_rows = {}
self._sel_rid = None
# 卡片全销毁重建:高亮缓存要一起清,否则新卡片被当成「画过了」
self._paint_cache = {}
self._focus_rid = None
self._pre_rid = None
self._layout_key = None # 重建后必须真的重排一次
self._geom_dirty = True # 新卡高未知,摆完要做一次几何校验
self._page = 0 # 名单内容换了,回第一页(v1.0.58)
if getattr(self, '_empty_lbl', None) is not None:
try:
self._empty_lbl.destroy()
except Exception:
pass
self._empty_lbl = None
def add_card(r):
rid = str(r.get('id'))
q, unit = self._qty_of(r)
who = self._who_of(r)
self.todo_cards[rid] = self._make_card(r, rid, q, unit, who)
self.todo_rows[rid] = r
self._grid_items.append(('card', self.todo_cards[rid]))
if self._group_mode == 'none':
# v1.0.47:分批建卡 —— 120 行同步建要 ~1 秒,界面整块冻住。
# 首帧建 24 张(~0.15 秒),其余每帧补 24 张,看着是"卡片刷出来"
# 而不是"点了没反应"。
gen = self._build_gen = self._build_gen + 1
pending = list(show[:500])
def step():
if gen != self._build_gen:
return # 已有更新的一轮,本批作废
chunk = pending[:24]
del pending[:24]
for r in chunk:
add_card(r)
self._layout_cards()
if pending:
self.root.after(1, step)
else:
self._shown_ids = ids # 全部建完才算「这一屏就是这些行」
step()
else:
groups, order = {}, []
for r in show[:500]:
k = self._group_key(r)
if k not in groups:
groups[k] = []
order.append(k)
groups[k].append(r)
for k in order:
rows_k = self._sort_rows_by_product(groups[k])
gq = {}
for r in rows_k:
q, unit = self._qty_of(r)
gq[unit] = gq.get(unit, 0.0) + q
qty_txt = ' + '.join('%g %s' % (v, u)
for u, v in gq.items() if v) or '0'
hdr = tk.Frame(self.todo_grid, bg=C.bg)
tk.Label(hdr, text=k, font=self._font(15, 'bold'),
bg=C.bg, fg=C.ink, anchor='w').pack(side='left')
tk.Label(hdr, text=' %d 行 · 合计 %s' % (len(rows_k), qty_txt),
font=self._font(12), bg=C.bg, fg=C.ink2,
anchor='w').pack(side='left')
self._hdr_widgets.append(hdr)
self._grid_items.append(('hdr', hdr))
for r in rows_k:
add_card(r)
# 分批建卡时不能提前登记 ids,否则下一轮刷新会误以为"行没变"
if self._group_mode != 'none' or not show:
self._shown_ids = ids
self._todo_tail(picking, show, words, kw, totals)
self._layout_cards()
def _set_todo_detail(self, text, fg=None):
"""更新待办提示/选中详情文案:不动态 pack/pack_forget,避免整列高度变化引发界面抖动。"""
txt = (text or '').strip()
try:
if fg is not None:
self.lbl_todo_detail.configure(text=txt, fg=fg)
else:
self.lbl_todo_detail.configure(text=txt, fg=C.ink2)
except Exception:
pass
def _todo_tail(self, picking, show, words, kw, totals):
"""待办区底部/空态文字与分组条(重建与增量更新两条路共用)"""
if not show:
self.lbl_todo_sum.configure(text='')
if words:
tip = '没有匹配「%s」的待办 · 点搜索框右侧 × 清空' % kw
self._empty_lbl = tk.Label(
self.todo_grid, text=tip, font=self._font(13),
bg=C.bg, fg=C.ink3, anchor='w', justify='left')
self._empty_lbl.grid(row=0, column=0, sticky='w',
padx=self._px(12), pady=self._px(18))
self._set_todo_detail(tip)
elif self._group_pick:
tip = '「%s」这一组已经没有待办了 · 点「全部」看别的' \
% self._group_pick
self._empty_lbl = tk.Label(
self.todo_grid, text=tip, font=self._font(13),
bg=C.bg, fg=C.ink3, anchor='w', justify='left')
self._empty_lbl.grid(row=0, column=0, sticky='w',
padx=self._px(12), pady=self._px(18))
self._set_todo_detail(tip)
else:
self._set_todo_detail('当前账号没有待办行')
self.todo_canvas.configure(scrollregion=(0, 0, 1, 1))
return
# 合计:精简展示,不与标题栏冲突
tot = ' + '.join('%g %s' % (v, u) for u, v in totals.items() if v)
self.lbl_todo_sum.configure(text=tot or '0')
if words:
self._set_todo_detail('搜索「%s」命中 %d 行' % (kw, len(show)))
elif self._group_pick:
self._set_todo_detail('只看「%s」· %d 行'
% (self._group_pick, len(show)))
else:
self._set_todo_detail('')
self._paint_group_bar()
@staticmethod
def _is_independent_inbound(r):
"""仅用于待办卡片展示:判断是否为独立入库原材料。"""
if not isinstance(r, dict):
return False
details = r.get('processing_details')
value = (details.get('independent_inbound')
if isinstance(details, dict) else None)
if value is None:
value = r.get('independent_inbound')
if isinstance(value, str):
return value.strip().lower() in ('1', 'true', 'yes', 'y', '是')
return bool(value)
def _indep_badge_text(self, r):
"""卡片上黄底提示的文案(返回空串 = 不显示)
同一商品可能既有「独立入库·加工原材料」又有普通订单行,合并成一张卡
后只挂一个“独立入库”会让人以为这 32 斤全是原料;有明细就分开写:
「独立入库原料 12 斤 · 普通入库 20 斤」
"""
parts = [p for p in ((r or {}).get('group_parts') or [])
if isinstance(p, dict)]
if parts:
inde = sum(float(p.get('qty') or 0) for p in parts
if p.get('kind') == 'independent')
norm = sum(float(p.get('qty') or 0) for p in parts
if p.get('kind') == 'normal')
unit = str((r or {}).get('unit') or '')
if inde > 0 and norm > 0:
return ('独立入库原料 %g %s · 普通入库 %g %s'
% (inde, unit, norm, unit))
if inde > 0:
return '独立入库 · 加工原材料'
return ''
return '独立入库 · 加工原材料' if self._is_independent_inbound(r) else ''
def _paint_independent_badge(self, card, r):
"""在商品名下方显示/隐藏独立入库提示,不参与业务数据。"""
badge = getattr(card, '_independent_badge', None)
if badge is None:
return
text = self._indep_badge_text(r)
if text:
try:
badge.configure(text=text)
except Exception:
pass
if badge.winfo_manager() != 'pack':
badge.pack(before=getattr(card, '_meta_lbl', None),
side='top', anchor='w', padx=self._px(12),
pady=(self._px(4), 0))
elif badge.winfo_manager() == 'pack':
badge.pack_forget()
def _update_card(self, r):
"""就地刷新一张卡(数量/客户/规格变了但行没变)——只改文本不重建"""
rid = str(r.get('id'))
c = self.todo_cards.get(rid)
if c is None:
return
self.todo_rows[rid] = r
q, unit = self._qty_of(r)
who = self._who_of(r)
meta = ' · '.join(x for x in [
('规格 ' + str(r['spec'])) if r.get('spec') else '',
str(who or '')] if x)
self._paint_independent_badge(c, r)
pairs = ((getattr(c, '_name_lbl', None), r.get('item_name') or '—'),
(getattr(c, '_qty_lbl', None), '%g %s' % (q, unit)),
(getattr(c, '_meta_lbl', None), meta))
changed = False
for lbl, txt in pairs:
if lbl is None:
continue
try:
if lbl.cget('text') != txt:
lbl.configure(text=txt)
changed = True
except Exception:
pass
c._meta_who = meta
# 卡上的字/徽标变了 → 卡高可能变,下一次重排要做几何校验
badge = getattr(c, '_independent_badge', None)
if changed or (badge is not None
and badge.winfo_manager() == 'pack'):
self._geom_dirty = True
# 字变了卡就可能变高(客户名/徽标折行)——idle 里复查一次
# 最底一张是否被视口裁到,裁到就重排(宁少放一行)。
self._schedule_reflow()
def _make_card(self, r, rid, q, unit, who):
"""一张待办卡:品名 / 数量 / 规格·客户(缩略图浮在右上角)
v1.0.47 瘦身:原来 8 个控件(两层 Frame + 4 个 Label),Tk 滚动时
每帧要把子控件全部重绘 —— 实测 120 行一帧 30ms,现场拖动就是卡。
改成 3 个 Label(缩略图另算),同样 120 行一帧只要 2ms。
"""
px = self._px
c = tk.Frame(self.todo_grid, bg=C.surface, bd=0,
highlightthickness=CARD_HL, highlightbackground=C.line,
highlightcolor=C.line)
c._thumb_label = None
name = r.get('item_name') or '—'
lbl_name = tk.Label(c, text=name, font=self._font(16, 'bold'),
bg=C.surface, fg=C.ink, anchor='w',
justify='left',
wraplength=int(150 * self.S))
lbl_name.pack(side='top', fill='x', padx=px(10), pady=(px(8), 0))
c._name_lbl = lbl_name # _layout_cards 按列宽改 wraplength
badge = tk.Label(c, text='独立入库 · 加工原材料',
font=self._font(10, 'bold'), bg='#fff4d6',
fg='#9a5b00', anchor='w', justify='left',
wraplength=int(150 * self.S))
c._independent_badge = badge
self._paint_independent_badge(c, r)
meta = ' · '.join(x for x in [
('规格 ' + str(r['spec'])) if r.get('spec') else '',
str(who or '')] if x)
lbl_meta = tk.Label(c, text=meta, font=self._font(10), bg=C.surface,
fg=C.ink3, anchor='w', justify='left',
wraplength=int(150 * self.S))
lbl_meta.pack(side='top', fill='x', padx=px(10), pady=(px(2), 0))
c._meta_lbl = lbl_meta
c._meta_who = meta
lbl_qty = tk.Label(c, text='%g %s' % (q, unit),
font=self._font(16, 'bold'), bg=C.surface,
fg=C.green, anchor='w')
lbl_qty.pack(side='top', fill='x', padx=px(10), pady=(px(2), px(8)))
c._qty_lbl = lbl_qty
img = self._thumb_for(r, rid) if self._thumb_on() else None
if img is not None:
tl = tk.Label(c, image=img, bg=C.surface, bd=0)
tl.image = img
tl.place(relx=1.0, x=-px(8), y=px(8), anchor='ne')
c._thumb_label = tl
c._thumb_lbl = tl
# 品名给图让位,别钻到图下面
lbl_name.configure(wraplength=max(
int(64 * self.S), int(150 * self.S) - int(70 * self.S)))
# 选中只在「按下→松手没挪过」时发生,见 _bind_card_tap
self._bind_card_tap(c, rid)
# v1.0.58:名单改分页不再滚动;卡上滚轮 = 翻页
try:
for w in [c] + list(c.winfo_children()):
w.bind('<MouseWheel>', self._page_wheel, add='+')
except Exception:
pass
return c
def _bind_card_tap(self, card, rid):
"""把一张卡(含里头的 Label)接成「点一下选中、拖动滚名单」。
v1.0.56 改成松手再选还不够:`TouchScroll.moved` 只在「内容高于视口
且纵向拖动」时才置位,斜着划一下、或名单刚好一屏装得下,它就一直是
False —— 结果还是滑一下选中一张。确认状态下每选中一次就走一次改判,
现场看到的是「一滑就打印,一直打印标签」。
这里用 TapGate 只认几何位移:挪过 12px 就只当拖动,不选中。
"""
gate = self._tap
def on_press(e, rid=rid):
gate.press(e, rid)
def on_motion(e):
gate.motion(e)
def on_release(e, rid=rid):
if gate.release(e, rid):
self._select_card(rid)
for w in [card] + list(card.winfo_children()):
try:
w.bind('<ButtonPress-1>', on_press, add='+')
w.bind('<B1-Motion>', on_motion, add='+')
w.bind('<ButtonRelease-1>', on_release, add='+')
except Exception:
pass
self._bind_swipe(w)
# ---- 卡片缩略图:本地 data/photos 按 商品名/SKU 查找;
# 真实接口可带 image_url,后台下载到 data/thumb_cache 再回填 ----
def _thumb_on(self):
"""待办卡是否显示商品缩略图(ui.todo_thumb,默认关)
v1.0.48:服务端待办接口目前不下发商品图,现场 data/photos 只有
几张样张 —— 绝大多数卡片本来就没图。每建一次卡仍要对每行做 8 次
文件探测、有图的还要重新解码缩放,「有没有图」的收益远小于开销,
所以默认关;要开就在 高级设置 里打开(或 ui.todo_thumb=true)。
"""
try:
return bool(self.cfg.get('ui', {}).get('todo_thumb', False))
except Exception:
return False
def _thumb_for(self, r, rid):
# 1) 真实接口的 image_url 严格优先(已缓存则直接显示,否则后台下载)
url = r.get('image_url')
if url:
cp = self._thumb_cache_path(url)
if os.path.exists(cp):
return self._load_thumb(cp)
self._fetch_thumb_async(rid, url)
return None
# 2) 兜底:本地 data/photos 按 商品名 / SKU 查找(仅离线/mock 演示用)
for key in (r.get('item_name'), r.get('sku_code')):
if key:
for ext in ('jpg', 'png', 'jpeg', 'webp'):
p = os.path.join('data', 'photos',
'%s.%s' % (key, ext))
if os.path.exists(p):
return self._load_thumb(p)
return None
def _thumb_cache_path(self, url):
h = abs(hash(url)) % 10 ** 12
return os.path.join('data', 'thumb_cache', '%d.png' % h)
def _load_thumb(self, path):
"""读一张缩略图(内存缓存:同一路径同一尺寸只解码一次)
原来每次重建卡片都把 PNG 重新 Image.open + thumbnail(一张约
8~10ms),商品照片一多,重建就成倍变慢。缓存后二次只有查字典。
"""
try:
key = (os.path.abspath(path), int(60 * self.S))
except Exception:
key = (path, 0)
cache = getattr(self, '_thumb_mem', None)
if cache is None:
cache = self._thumb_mem = {}
ph = cache.get(key)
if ph is not None:
return ph
try:
im = Image.open(path).convert('RGB')
t = int(60 * self.S)
im.thumbnail((t, t))
ph = ImageTk.PhotoImage(im)
if len(cache) > 400: # 别无限涨(400 张 ≈ 几 MB)
cache.clear()
cache[key] = ph
return ph
except Exception:
return None
def _fetch_thumb_async(self, rid, url):
import threading
os.makedirs('data/thumb_cache', exist_ok=True)
cp = self._thumb_cache_path(url)
def _run():
try:
resp = requests.get(url, timeout=8)
if not resp.ok:
return
with open(cp, 'wb') as f:
f.write(resp.content)
im = Image.open(cp).convert('RGB')
t = int(60 * self.S)
im.thumbnail((t, t))
ph = ImageTk.PhotoImage(im)
self.root.after(0, self._set_thumb, rid, ph)
except Exception:
pass
threading.Thread(target=_run, daemon=True).start()
def _set_thumb(self, rid, ph):
c = self.todo_cards.get(rid)
if not c or getattr(c, '_thumb_label', None) is not None:
return
top = getattr(c, '_top', None)
host = top if top is not None else c
tl = tk.Label(host, image=ph, bg=host.cget('bg'), bd=0)
tl.image = ph
if host is top:
tl.pack(side='right', padx=(int(6 * self.S), 0))
else:
tl.place(relx=1.0, rely=0.0,
x=-int(6 * self.S), y=int(6 * self.S), anchor='ne')
c._thumb_label = tl
c._thumb_lbl = tl
cw = c.winfo_width()
if cw >= 40: # 刚建好还没布局(宽 1)时先别判,等 _layout_cards
self._fit_thumb(c, cw)
# ---- 待办每行列数:0=按宽度自动,>0 固定列数(标题栏小按钮可切)----
def _cols_setting(self):
try:
n = int((self.cfg.get('ui') or {}).get('todo_cols', 0) or 0)
except (TypeError, ValueError):
n = 0
return max(0, min(8, n))
def _cols_text(self):
n = self._cols_setting()
return '列数 自动' if not n else '列数 %d' % n
def _cycle_cols(self):
"""自动 → 4 → 5 → 6 → 自动:现场想一屏多看几行时点这里"""
seq = [0, 4, 5, 6]
cur = self._cols_setting()
nxt = seq[(seq.index(cur) + 1) % len(seq)] if cur in seq else 0
self.cfg.setdefault('ui', {})['todo_cols'] = nxt
try:
save_config(self.cfg)
except Exception:
pass
if getattr(self, 'btn_cols', None) is not None:
try:
self.btn_cols.configure(text=self._cols_text())
except Exception:
pass
self._layout_cards()
self.log('[dev] 待办排列:%s' % self._cols_text())
def _fit_thumb(self, c, card_w):
"""列数拉多时卡片只有 140 出头,再摆 60px 图品名就没地方了:
先把图收起来,列数调回去自动放回来(图本身不销毁,不重下)。
v1.0.47:缩略图改成 place 浮在右上角(不再单独占一层 Frame),
这里只负责宽了摆回去、窄了藏起来。
"""
tl = getattr(c, '_thumb_lbl', None)
if tl is None:
return
thumb = int(60 * self.S)
wide = card_w >= thumb + int(90 * self.S)
try:
if wide:
if tl.winfo_manager() != 'place':
tl.place(relx=1.0, x=-int(8 * self.S),
y=int(8 * self.S), anchor='ne')
elif tl.winfo_manager() == 'place':
tl.place_forget()
except Exception:
pass
def _refresh_scrollregion(self, retry=True):
"""按内容真实高度刷新可滚范围(v1.0.56)
刚建完卡片的那一个事件里 canvas.bbox('all') 还可能返回建卡之前的
旧值(高度 1),滚动区域就变成「0 0 824 1」——名单看着有货,滚轮
和拖动却一动不动(现场「滑动不流畅」最狠的一种表现)。
所以 bbox 明显比 grid 的请求高度小时,用请求高度兜底;两者都还没
算出来(同一个事件循环里刚建完控件)就排一次 idle 再量。
"""
cv = self.todo_canvas
try:
bb = cv.bbox('all')
h = (bb[3] - bb[1]) if bb else 0
try:
need = self.todo_grid.winfo_reqheight()
except Exception:
need = 0
if need > h + 2:
h = need
w = cv.winfo_width() or (bb[2] - bb[0] if bb else 1)
if h <= 2 and retry:
# 还没量出来:等这一轮布局跑完再补一次,只补一次
try:
self.root.after_idle(
lambda: self._refresh_scrollregion(False))
except Exception:
pass
cv.configure(scrollregion=(0, 0, max(1, int(w)),
max(1, int(h))))
except Exception:
pass
def _layout_cards(self, _e=None):
items = getattr(self, '_grid_items', None)
if items is None: # 老调用路径(没有分组信息)
items = [('card', c) for c in
getattr(self, 'todo_cards', {}).values()]
self._grid_items = items
cards = [o for k, o in items if k == 'card']
cw = self.todo_canvas.winfo_width()
if cw < 40:
return
if not cards:
self.todo_canvas.configure(scrollregion=(0, 0, 1, 1))
self._page = 0
self._page_count = 1
self._paint_pager()
return
gap = int(8 * self.S)
# 平板尺寸:一张卡至少 196px(品名 16 号、应拣 16 号,手指点得准),
# 1440 屏右栏约 1400px → 6 列;列数按钮可锁 4/5/6。
min_card = int(196 * self.S)
fixed = self._cols_setting()
if fixed > 0:
ncols = max(1, min(len(cards), fixed))
else:
ncols = max(1, min(len(cards), (cw + gap) // (min_card + gap)))
# v1.0.58:不再滚动,按「一页放得下几行」分页。卡高用上次实测值
# (第一次用估值,摆完 _calibrate_row_h 量真实的再校正),名字
# 换 1 行还是 2 行差 20px,写死会最底行被切一半或下半页空着。
view_h = max(1, self.todo_canvas.winfo_height())
# 分页改成「按每行实际高度装箱」(_paginate_by_height):带黄底徽标/
# 长名字的行更高,这类页少吃一行;全是矮卡时多放一行;
# 不再用固定行高估一个页容量,避免最底行被视口裁掉。
key = (cw, view_h, ncols, self._thumb_on(), self._page,
len(items),
tuple(str(x) for x in (getattr(self, '_shown_ids', None) or ())))
if getattr(self, '_layout_key', None) == key:
self._refresh_scrollregion()
return
self._layout_key = key
# 先清掉上一轮留下的列宽约束,否则切列数/搜索筛完后
# 右边会残留一条空白,甚至出现横向滚动
for col in range(12):
self.todo_grid.columnconfigure(col, weight=0, minsize=0,
uniform='')
card_w = (cw - gap * (ncols + 1)) // ncols
thumb = int(60 * self.S) if self._thumb_on() else 0
# v1.0.72(性能):列宽/缩略图变了,换行宽度跟着变 → 卡高会变,
# 这一次必须做几何校验;没变就不用(普通翻页/重排剩 30ms)。
if (card_w, thumb) != getattr(self, '_mw_prev', None):
self._mw_prev = (card_w, thumb)
self._geom_dirty = True
# 仅当列宽/缩略图/卡片列表变动时才重算所有卡的换行宽度,普通翻页直接跳过(省数百次 Tk configure)
if getattr(self, '_geom_dirty', False):
for kind, obj in items:
if kind != 'card':
continue
# 卡片里的字宽必须跟着列宽走:写死 150/240 会把列撑开,
# 列数越多越明显(最后表现为「怎么调都只有 4 列」)
name_lbl = getattr(obj, '_name_lbl', None)
if name_lbl is not None:
wrap = max(int(64 * self.S),
card_w - thumb - int(22 * self.S))
# v1.0.60:长名字自动降一号字。「上海青(小棠菜)」这种
# 16 号放不下会折成两行,右括号孤零零挂在第二行,很难看。
# 能压成一行就压(14 号),压不下才照旧折行。
size = 16
try:
txt = str(name_lbl.cget('text') or '')
if txt and self._name_font(16).measure(txt) > wrap \
and self._name_font(14).measure(txt) <= wrap:
size = 14
except Exception:
pass
name_lbl.configure(font=self._name_font(size),
wraplength=wrap)
self._fit_thumb(obj, card_w)
meta_lbl = getattr(obj, '_meta_lbl', None)
if meta_lbl is not None:
# 卡上只有客户/供应商名了(v1.0.41 起不再放单号),
# 宽窄卡内容一致,只需要跟着列宽调换行宽度。
meta_lbl.configure(
text=getattr(obj, '_meta_who', ''),
wraplength=max(int(80 * self.S),
card_w - int(16 * self.S)))
badge = getattr(obj, '_independent_badge', None)
if badge is not None:
# 「独立入库原料 12 斤 · 普通入库 20 斤」比原来长,跟着列宽折行
badge.configure(
wraplength=max(int(80 * self.S),
card_w - int(16 * self.S)))
def _item_height(kind, obj):
"""这一项单独占的高度(卡片行取本行最高,见 _paginate_by_height)"""
try:
h = int(obj.winfo_reqheight())
except Exception:
h = 0
if h <= 10: # 还没量出来:用保守估值
h = int(118 * self.S)
return h + (2 * gap if kind == 'card' else gap)
pages = _paginate_by_height(items, ncols, view_h, _item_height)
def _grid_page(pages):
"""按分好的页摆当前页;返回本页对象列表。"""
self._page_count = len(pages)
self._page = max(0, min(self._page, len(pages) - 1))
page = pages[self._page]
# 只摘掉当前在屏但不在新页的控件(不用遍历全部百来张离屏卡)
on_page = set(id(o) for _, o in page)
for obj in list(self.todo_grid.grid_slaves()):
if id(obj) not in on_page:
try:
obj.grid_forget()
except Exception:
pass
# 所有卡(含不在本页的)都记下页码:AI 跳行要靠它翻过去
self._page_of = {}
for pi, pg in enumerate(pages):
for _, o in pg:
self._page_of[id(o)] = pi
row, col = 0, 0
for kind, obj in page:
if kind == 'hdr':
# 分组标题:整行铺满,后面紧跟这一组的卡。
if col > 0:
row += 1
col = 0
obj.grid(row=row, column=0, columnspan=ncols,
sticky='ew', padx=gap, pady=(gap, 0))
row += 1
continue
if col >= ncols:
col = 0
row += 1
obj.grid(row=row, column=col, padx=gap, pady=gap,
sticky='nsew')
obj.configure(width=card_w)
col += 1
for c in range(ncols):
# v1.0.75:uniform —— 所有列必须一样宽。
# 不加这一句时:点一下卡(只改了 Frame 的 highlightbackground,
# 颜色而已)Tk 会把这张卡的请求宽度算成 198,grid 一算总宽超了
# 就把**别的列**从 190 压到 182,等下一次 idle 再排回 190:
# 实测 15ms 内整屏 8 张卡来回跳 64 次(190↔198、卡内 label
# 162↔154↔170),肉眼看就是「点一下界面抖一下」。
# 加了 uniform 后同样的操作 0 次几何跳变(tools/_ui_jitter_check.py
# 会盯着这条,别再删)。
self.todo_grid.columnconfigure(c, weight=1, minsize=card_w,
uniform='cf')
return page
# v1.0.70:摆完按**真实几何**兜底。卡高是靠 winfo_reqheight 估的,
# 总有估不对的时候(重建后还没量出来、客户名那时还没到、
# DPI 或字体差异、页头比估的高……)。与其猜是哪个,不如摆完量一次:
# 最底一张真的超出视口,就把「每行平均低估的那几像素」加到行高上
# 重排,**宁少放一行,绝不裁半行**。最多试 4 次。
#
# v1.0.72(性能):校验按「高度版本 + 页码」缓存 —— 卡高变了
# (重建卡片 / 字改了 / 列宽变了)或这一页还没校验过,才真去
# update_idletasks;同一页再翻回来就不用。校验一次约 30ms。
def _paginate(extra=0.0):
return _paginate_by_height(
items, ncols, view_h,
lambda k, o: _item_height(k, o) + extra)
hs = tuple(sorted({int(_item_height(k, o)) for k, o in items}))
if hs != getattr(self, '_geom_sig', None) \
or getattr(self, '_geom_dirty', False):
self._geom_sig = hs
self._geom_ok = set()
self._geom_dirty = False
ok_pages = getattr(self, '_geom_ok', set())
_pages0 = _paginate()
_target = max(0, min(self._page, len(_pages0) - 1))
check_geom = _target not in ok_pages
extra = 0.0 # 每行平均被低估的高度
page = []
over = 0
for _try in range(4 if check_geom else 1):
page = _grid_page(_paginate(extra))
if not check_geom:
break
try:
self.todo_grid.update_idletasks()
slaves = self.todo_grid.grid_slaves()
rows = len({w.winfo_y() for w in slaves})
over = max([w.winfo_y() + w.winfo_height()
for w in slaves] or [0]) - view_h
except Exception:
rows, over = 0, 0
if over <= 0 or rows <= 0 or len(page) <= 1:
break
extra += float(over) / rows
if check_geom:
# 缩过行(extra>0)说明分页变了,其它页的校验结果作废
self._geom_ok = {self._page} if extra > 0 else \
(set(ok_pages) | {self._page})
self._last_over = max(0, over) # 供 idle 复查用,免得反复重排
self.todo_canvas.itemconfig(self._todo_win, width=cw)
try:
self.todo_canvas.yview_moveto(0)
except Exception:
pass
self._refresh_scrollregion()
self._paint_pager()
self._calibrate_row_h()
# 重新摆放会打断高亮,确认条还开着就把当前行再对一次
if self._focus_p and self._focus_p.get('row_id') is not None:
self._paint_focus(str(self._focus_p.get('row_id')))
# ---------------------------------------------------------- 分页
# ---------------- 待办区左右滑动翻页(v1.0.68)
def _bind_swipe(self, w):
"""给待办卡/空白区接上左右滑动翻页(竖向拖动不参与)
现场 19 寸触摸屏点底部「上一页/下一页」要跨半个屏幕,翻一页很累。
只认「横向位移 >60px 且明显大于纵向」——点还是点(TapGate 的 12px
阈值不动),竖向 / 斜向拖动也不会误翻页。
"""
try:
w.bind('<ButtonPress-1>', self._swipe_press, add='+')
w.bind('<B1-Motion>', self._swipe_move, add='+')
w.bind('<ButtonRelease-1>', self._swipe_release, add='+')
except Exception:
pass
def _swipe_press(self, e):
try:
self._swipe = {'x': float(e.x_root), 'y': float(e.y_root),
'on': False}
except Exception:
self._swipe = None
def _swipe_move(self, e):
s = getattr(self, '_swipe', None)
if not s:
return
try:
dx = float(e.x_root) - s['x']
dy = float(e.y_root) - s['y']
except Exception:
return
if abs(dx) > self._px(30) and abs(dx) > abs(dy) * 1.5:
s['on'] = True
def _swipe_release(self, e):
s = getattr(self, '_swipe', None)
self._swipe = None
if not s or not s.get('on'):
return
try:
dx = float(e.x_root) - s['x']
except Exception:
return
if abs(dx) < self._px(60):
return
# 手指往左划 → 下一页;往右划 → 上一页
self._page_turn(-1 if dx > 0 else 1)
def _page_turn(self, d):
"""上一页/下一页:_layout_cards 的 key 里有页码,改了页它自然重排"""
n = getattr(self, '_page_count', 1)
if n <= 1:
return
p = max(0, min(n - 1, getattr(self, '_page', 0) + d))
if p == self._page:
return
self._page = p
self._layout_cards()
def _page_wheel(self, e):
"""滚轮 = 翻页(v1.0.58 起名单不再滚动)"""
try:
d = -1 if getattr(e, 'delta', 0) > 0 else 1
self._page_turn(d)
except Exception:
pass
return 'break'
def _paint_pager(self):
"""翻页条:页码 + 两端按钮置灰"""
try:
n = getattr(self, '_page_count', 1)
p = getattr(self, '_page', 0)
self.lbl_page.configure(
text='第 %d / %d 页' % (p + 1, n) if n > 1 else '')
self.btn_pg_prev.configure_btn(enabled=n > 1 and p > 0)
self.btn_pg_next.configure_btn(enabled=n > 1 and p < n - 1)
except Exception:
pass
def _schedule_reflow(self):
"""idle 里复查一次「最底一张是否超出视口」,超出就重排。
多次调用合并成一次;几何已经稳定时什么也不做。
"""
if getattr(self, '_reflow_sched', False):
return
self._reflow_sched = True
try:
self.root.after_idle(self._reflow_idle)
except Exception:
self._reflow_sched = False
def _reflow_idle(self):
self._reflow_sched = False
try:
view_h = max(1, self.todo_canvas.winfo_height())
over = max([w.winfo_y() + w.winfo_height()
for w in self.todo_grid.grid_slaves()] or [0]) \
- view_h
# 超出量和上次重排时一样多 → 缩预算也救不了(单张卡就比视口高),
# 别再反复重排
if over <= max(0, getattr(self, '_last_over', 0)) + 2:
return
self._geom_dirty = True # 重排时走一次几何校验(会缩行)
self._layout_key = None # 强制真的重排一次
self._layout_cards()
except Exception:
pass
def _calibrate_row_h(self):
"""量一下本页卡的真实高度,和估值差太多就按实测重排一次。
卡高取决于名字换 1 行还是 2 行、界面缩放 S,估不准就会一页塞
不下(最底行被切一半)或下半页空着。摆完在 idle 里量,差超过
8% 就用实测值重排一次;重排后卡高不变,自然不会再来回抖。
"""
if getattr(self, '_cal_sched', False):
return
self._cal_sched = True
try:
self.root.after_idle(self._calibrate_row_h_idle)
except Exception:
self._cal_sched = False
def _calibrate_row_h_idle(self):
self._cal_sched = False
try:
# 量**全部**卡(不只是当前页):徽标/长名字会让某些卡更高,
# 只量当前页会把行高估值偏小,翻到有徽标的那页就多塞一行、
# 最底一张被裁(现场入库第 2 页开始出现的遮挡)。
hs = [c.winfo_reqheight() for c in self.todo_cards.values()]
hs = [h for h in hs if h > 10]
if not hs:
return
real = max(hs)
est = getattr(self, '_row_h_est', 0)
if est and abs(real - est) <= max(6, int(est * 0.08)):
return
self._row_h_est = real
self._geom_dirty = True # 卡高变了,重排时做一次几何校验
self._layout_key = None
self._layout_cards()
except Exception:
pass
def _todo_on_resize(self, _e=None):
self._layout_cards()
def _select_card(self, rid):
# 两道闸:TapGate(只认位移,滑名单/斜划都算拖动)+ 提交在途。
# 保留 TouchScroll.moved 判断做兜底 —— 它认的是「滚了多远」,
# 和位移判定互补,宁可少选一次也别把货打错行。
if getattr(self, '_focus_busy', False):
return
ts = getattr(self, '_todo_scroll', None)
if ts is not None and getattr(ts, 'moved', False):
return
# 确认状态下点卡片 = 改判:把这一件记到刚点的这一行
if self.engine.state == 'CONFIRM':
self._focus_pick(rid)
return
# v1.0.40:空秤(待机)点卡片 = 预选这一行 —— 放货识别后以 AI
# 命中为准,识别不出仍走人工确认页。高亮下面统一画。
# v1.0.69:高亮和详情行同源,永远跟着「最后点过的那张」;引擎收不收
# 预选只影响 _pre_rid(记账参考),不能再决定画哪张,否则会出现
# 「亮的是旧预选、详情是新点的」两张错位。
if self.engine.state == 'IDLE':
try:
self._pre_rid = rid if self.engine.preselect(rid) else None
except Exception:
self._pre_rid = None
old = getattr(self, '_sel_rid', None)
self._sel_rid = rid
# 只重画变了的这两张(原来遍历整张名单 configure,120 行 35ms)
self._repaint_cards([old, rid])
r = self.todo_rows.get(rid) or {}
bits = [r.get('item_name') or '—']
if r.get('spec'):
bits.append(str(r['spec']))
if r.get('sku_code'):
bits.append(str(r['sku_code']))
who = self._who_of(r)
if who:
bits.append(str(who))
qty = r.get('remaining_qty')
if qty is None:
qty = r.get('required_qty')
if qty is None:
qty = r.get('prepare_qty')
bits.append('应%s %s%s' % ('拣' if self.engine.station == 'picking'
else '验', qty, r.get('unit') or ''))
if r.get('order_code'):
bits.append('单号 %s' % r['order_code'])
self._set_todo_detail(' · '.join(bits))
def _on_log(self, s):
self.log(s)
def _on_hint(self, text):
"""引擎发来的临时提示(如「3 秒后自动提交」):写在状态卡提示行
空字符串 = 撤掉临时提示,恢复待确认件的正常提示。
"""
try:
if text:
self.lbl_hint.configure(text=str(text), fg=C.amber)
else:
line, warn = self._pending_hint(getattr(self, '_focus_p', None)
or {})
self.lbl_hint.configure(text=warn or line,
fg=C.amber if warn else C.ink2)
except Exception:
pass
def _show_recent_records(self, n_last=20):
"""最近提交台账(records.csv 倒序 N 条):点一行看抓拍照片。
提交后服务端没有撤销接口,错了只能后台更正 —— 这页就是给「后台
更正」找证据用的:什么时候、哪一单、记了多少、哪张照片。
"""
import csv
rf = self.cfg.get('record_file', 'data/records.csv')
rows = []
try:
with open(rf, encoding='utf-8-sig', newline='') as f:
rows = list(csv.DictReader(f))
except Exception:
pass
rows = rows[-n_last:][::-1]
px, font = self._px, self._font
top = tk.Toplevel(self.root)
top.title('最近提交')
top.configure(bg='#ffffff')
w, h = px(860), px(560)
try:
top.geometry('%dx%d+40+40' % (w, h))
except Exception:
pass
tk.Label(top, text='最近提交(台账倒序,点一行看抓拍照片;'
'记错的请拿操作号到后台更正)',
font=font(14, 'bold'), bg='#ffffff', fg='#1f2937',
anchor='w').pack(fill='x', padx=px(14), pady=(px(12), px(6)))
cv = tk.Canvas(top, bg='#ffffff', highlightthickness=0)
cv.pack(fill='both', expand=True, padx=px(10), pady=(0, px(10)))
sb = ttk.Scrollbar(top, orient='vertical', command=cv.yview)
sb.place(relx=1.0, rely=0.12, relheight=0.85, anchor='ne')
cv.configure(yscrollcommand=sb.set)
lst = tk.Frame(cv, bg='#ffffff')
cv.create_window((0, 0), window=lst, anchor='nw')
def show_photo(path):
if not path:
return
p = path if os.path.isabs(path) else os.path.join(
os.path.dirname(os.path.abspath(sys.argv[0])), path)
if not os.path.exists(p):
# v1.0.36 起抓拍改存 D 盘。老台账里还是 data/snapshots\xxx.jpg,
# 文件已经迁走但同名还在,跟着当前抓拍目录再找一次。
alt = os.path.join(
getattr(self.engine.frames, 'snap_dir', '') or '',
os.path.basename(p))
if os.path.exists(alt):
p = alt
if not os.path.exists(p):
days = int(self.engine.snap_settings()[1])
messagebox.showinfo(
'照片已清理',
'这张抓拍已经不在了:\n%s\n\n抓拍只保留最近 %d 天(可在'
'「设置 → 抓拍存放与清理」里调),过期自动删除。\n'
'台账里的记录不受影响,金额和数量都还在。'
% (path, days), parent=top)
return
ph = tk.Toplevel(top)
ph.title(os.path.basename(p))
ph.configure(bg='#111418')
try:
img = Image.open(p)
img.thumbnail((px(640), px(480)))
ph_img = ImageTk.PhotoImage(img)
lbl = tk.Label(ph, image=ph_img, bg='#111418')
lbl.image = ph_img
lbl.pack(padx=px(10), pady=px(10))
except Exception as e:
tk.Label(ph, text='照片打不开:%s' % e, font=font(12),
bg='#111418', fg='#ff9d9d').pack(padx=20, pady=20)
if not rows:
tk.Label(lst, text='台账里还没有记录', font=font(13),
bg='#ffffff', fg='#8a94a3').pack(padx=px(20),
pady=px(24), anchor='w')
for i, r in enumerate(rows):
bgc = '#ffffff' if i % 2 == 0 else '#f6f8fb'
line = ' · '.join(x for x in [
str(r.get('时间') or ''),
{'picking': '分拣', 'inspection': '入库'}.get(
str(r.get('工位') or ''), str(r.get('工位') or '')),
'%s(%s)' % (r.get('确认商品') or '—', r.get('方式') or '—'),
'kg %.2f' % float(r.get('重量kg') or 0),
] if x)
f = tk.Frame(lst, bg=bgc)
f.pack(fill='x')
op = str(r.get('操作号') or '')
lbl = tk.Label(f, text=line, font=font(12), bg=bgc,
fg='#1f2937', anchor='w', justify='left')
lbl.pack(side='left', fill='x', expand=True, padx=(px(10), 0),
pady=px(4))
if op:
tk.Label(f, text=op[-10:], font=font(10), bg=bgc,
fg='#8a94a3').pack(side='right', padx=(0, px(10)))
for ch in (f, lbl):
ch.bind('<Button-1>',
lambda e, p=str(r.get('照片') or ''): show_photo(p))
lst.bind('<Configure>', lambda _e: cv.configure(
scrollregion=cv.bbox('all')))
def _refresh_today(self):
"""今日统计:直接数台账 records.csv,重启也不丢"""
import csv
rf = self.cfg.get('record_file', 'data/records.csv')
today = datetime.date.today().strftime('%Y-%m-%d')
n, kg = 0, 0.0
try:
with open(rf, encoding='utf-8-sig', newline='') as f:
for r in csv.DictReader(f):
if not (r.get('时间') or '').startswith(today):
continue
if (r.get('工位') or '') != self.engine.station:
continue
n += 1
try:
kg += float(r.get('重量kg') or 0)
except (TypeError, ValueError):
pass
except Exception:
pass
try:
self.lbl_today.configure(
text='今日已完成 %d 件 · 共 %.2f kg' % (n, kg)
if n else '今日已完成 0 件')
except Exception:
pass
def _on_result(self, pair):
ok, msg = pair
self.log(('✔ ' if ok else '✘ ') + msg)
self.lbl_result.configure(text=msg, fg='#27500a' if ok else '#a32d2d')
if ok:
self._refresh_today()
else:
self.lbl_state.configure(text=msg, fg='#a32d2d')
def _on_print_result(self, pair):
"""异步打印回来的结果:成功淡淡标一下,失败必须显眼(要手工补打)"""
ok, msg = pair
self.lbl_print.configure(
text=('✔ 标签已发送打印' if ok else '⚠ 标签未打印:%s' % msg),
fg='#0f6e56' if ok else '#a32d2d')
self.log(('打印已发送: ' if ok else '打印失败: ') + msg)
if not ok:
try:
self.root.bell()
except Exception:
pass
self.lbl_last.configure(
text=self._fit_text('⚠ 标签打印失败(%s),请手工补打' % msg,
self._px(536)),
fg='#a32d2d')
def _tick_clock(self):
# v1.0.52:秒没变就别改(这个函数每 120ms 跑一次,秒级时钟每秒
# 改 8 次纯属白催 Tk 重画)
try:
txt = datetime.datetime.now().strftime('%m-%d %H:%M:%S')
if txt == getattr(self, '_clock_txt', None):
return
self._clock_txt = txt
self.lbl_clock.configure(text=txt)
except Exception:
pass
def _autodetect_devices(self, on_done=None, deep_camera=False):
"""自动认设备:摄像头 / 电子秤 / 标签打印机。
为什么放后台线程:秤要逐个串口、逐个波特率试(最慢十几秒),
放主线程会把界面冻住。识别完回主线程写配置并让运行中的引擎热切换。
现场意义:换了备机、线插到别的 USB 口、秤换了波特率,都不需要
操作员进设置页一个个点 —— 开机自己认回来。
"""
if getattr(self, '_detecting', False):
return
self._detecting = True
self.log('正在自动识别设备(摄像头 / 电子秤 / 标签打印机)…')
def work():
from core import devices as dv
running = bool(getattr(self.engine, '_running', False))
fs = getattr(self.engine, 'frames', None)
# 要验证画面就得先把取帧子进程停掉,否则探测只能拿到「设备被占用」
deep = bool(deep_camera and fs is not None
and not self.cfg.get('camera', {}).get('simulate'))
if deep:
try:
fs.suspend()
time.sleep(0.45)
except Exception:
deep = False
res, changes, summary = {}, [], ''
try:
res = dv.detect_all(
self.cfg, deep_camera=deep,
# release() 会连句柄一起关掉,否则探测端只会拿到「拒绝访问」
stop=(self.engine.scale.release if running else None),
start=(self.engine.scale.start if running else None),
# 秤正出数就别打扰它,直接沿用
is_connected=(self.engine.scale.is_fresh if running else None))
changes = dv.apply_detect(self.cfg, res)
summary = dv.summary_text(res)
except Exception as e: # noqa: BLE001
summary = '识别失败:%s' % e
finally:
if deep:
try:
fs.resume() # 探测完把摄像头交还给取帧
except Exception:
pass
def fin():
self._detecting = False
if changes:
try:
save_config(self.cfg)
except Exception:
pass
txt = '已自动切换:' + ';'.join(
'%s %s → %s' % (k, o, n) for k, o, n in changes)
self.log(txt)
# 运行中的引擎热切换(不用重启程序)
if running:
try:
self.engine.scale.reconfigure(self.cfg['scale'])
except Exception:
pass
try:
self.engine.frames.reconfigure(self.cfg['camera'])
except Exception:
pass
else:
txt = '设备已就绪:' + (summary or '无变化')
self.log(txt)
self._detect_summary = txt
try:
self._refresh_devices()
except Exception:
pass
if on_done:
try:
on_done(res, changes)
except Exception:
pass
# 收尾必须回主线程做(worker 里碰 Tk 会报
# "main thread is not in main loop"),交给 _poll 取走执行
self._detect_pending = fin
threading.Thread(target=work, daemon=True).start()
def _refresh_devices(self):
"""设备状态压成一行放状态卡底部:秤 / 相机 / 打印 / 服务端"""
try:
sc = self.cfg.get('scale', {})
if sc.get('simulate'):
dev = '秤 模拟'
else:
dev = '秤 %s' % (sc.get('port') or 'COM?')
cam_cfg = self.cfg.get('camera', {})
fs = self.engine.frames
op = getattr(fs, 'opened', None)
if cam_cfg.get('simulate'):
cam = '相机 模拟'
elif op:
cam = '相机 %d 号 %dx%d' % (op[0], op[2], op[3])
else:
cam = '相机 %s' % (getattr(fs, 'status', '') or '未就绪')
pr = self.cfg.get('printer', {})
if not pr.get('enabled'):
ptxt = '打印 未启用'
else:
nm = pr.get('printer_name') or '未选择'
ptxt = '打印 %s' % (nm if len(nm) <= 14 else nm[:13] + '…')
srv = self.cfg.get('server', {})
if srv.get('mock'):
stxt = '服务端 离线模拟'
else:
url = (srv.get('base_url') or '').replace('https://', '')
url = url.replace('http://', '').split('/')[0]
stxt = '服务端 %s' % (url or '未配置')
# v1.0.42:这行设备信息不在界面显示,只写日志(排障用)。
# v1.0.44:_poll 每 2 秒调一次这里,原样写日志=每 2 秒刷一条,
# app.log 一天能涨 70MB。只在设备行真的变化时才记一条。
line = '[dev] 设备:' + ' · '.join([dev, cam, ptxt, stxt])
if line != getattr(self, '_last_dev_line', None):
self._last_dev_line = line
self.log(line)
except Exception:
pass
def _on_locked(self, msg):
self.log('⛔ ' + msg)
try:
messagebox.showwarning(
'提交待核实', msg + '\n\n点「确定」后打开核实窗口,'
'核对后台这一笔到底有没有入库。')
except Exception:
pass
# messagebox 是模态的,返回后再开核实窗口,避免两层窗口叠在一起
self._unresolved_dialog()
def _on_unlocked(self, _p=None):
try:
self.lbl_state.configure(text='本机提交锁已解除,可以继续称重',
fg='#1f7a3d')
except Exception:
pass
self.log('✔ 未决提交已核实,本机提交锁已解除')
def _close_flow_pages(self):
"""收起挡在屏幕前面的全屏页(人工确认 / 免称重确认)"""
fn = getattr(self, '_cf_unbind', None)
if callable(fn):
try:
fn()
except Exception:
pass
for attr in ('_confirm_top', '_count_top'):
top = getattr(self, attr, None)
try:
if top is not None and top.winfo_exists():
top.destroy()
except Exception:
pass
setattr(self, attr, None)
# 确认条也一起收(刷新待办 / 退出登录时不该还挂着上一条)
try:
self._show_focus_bar(False)
self._focus_p = None
except Exception:
pass
def _refresh_pending_now(self):
"""顶栏「刷新待办」:拉名单,同时把卡住的工作状态拉回待机。
现场「卡在工作状态」无非三种:抓拍/识别线程没回来(停在
CAPTURE/RECOGNIZE)、人工确认页开着没人点、免称重确认页开着。
以前这颗按钮只调 refresh_pending,名单刷了机器还在上一件里,
看着就是「按钮没反应」,最后只能重启程序。
"""
if not getattr(self, 'ready', False):
return
# 连点保护:1.5 秒内重复点只认第一次(现场日志里 1 秒点了两次)
now = time.monotonic()
if now - getattr(self, '_refresh_at', 0.0) < 1.5:
return
self._refresh_at = now
st = getattr(self.engine, 'state', 'IDLE')
ok, msg = True, ''
try:
ok, msg = self.engine.hard_refresh(
'刷新待办:作废当前这一件(%s)' % ST_STATE_CN.get(st, st))
except Exception as e: # noqa: BLE001
ok, msg = False, '刷新失败:%s' % e
self._close_flow_pages()
if msg:
self.log(('✔ ' if ok else '刷新待办:') + msg)
if not ok:
try:
messagebox.showinfo('刷新待办', msg, parent=self.root)
except Exception:
pass
try:
# v1.0.49:不再同步等网络(现场待办接口经常读超时 4 秒,
# 这一下就把整个界面冻住,操作员越急越点、越点越冻)。
# 走后台拉取,结果由 _drain_pending 回到这里。
self.engine.refresh_pending_async()
self.log('正在刷新待办…')
except Exception as e: # noqa: BLE001
self.log('待办刷新失败:%s' % e)
def _on_force_idle(self, msg=''):
"""置零/去皮后回到待机(UI 线程);顺带把确认页收起"""
try:
if self._confirm_top is not None \
and self._confirm_top.winfo_exists():
self._confirm_top.destroy()
except Exception:
pass
self._confirm_top = None
try:
self.engine.force_idle()
except Exception:
pass
if msg:
self.log(msg)
# ------------------------------------------------ 重复收货防护
def _on_hold(self, p=None):
"""秤上还是刚才提交过的那堆货(flow 判定的重复收货)
现场 19:21:4.11kg 土豆提交成功,货没取走,12 秒后 DONE 超时回
待机,又抓拍一次,同一堆货被识别成「冰糖橙」再提交一遍。
现在 flow 会拦住这一轮,但操作员只看到机器"不动了"——必须有
一句话和一颗按钮告诉他为什么、以及怎么继续。
"""
btn = getattr(self, '_btn_newitem', None)
if btn is None or not self.ready:
return
try:
if p:
if not btn.winfo_ismapped():
btn.pack(fill='x')
kg = float(p.get('kg') or 0)
name = (p.get('name') or '').strip()
if name:
txt = ('秤上还是刚才那件(%.1f kg,已入过「%s」):'
'取走再放,或点「这是一件新货」' % (kg, name))
else:
# 刷新待办锁定的一堆(还没有归属商品)
txt = ('秤上这堆 %.1f kg 已锁定,不再自动识别:'
'取走再放,或点「这是一件新货」' % kg)
self.lbl_state.configure(text=txt)
else:
btn.pack_forget()
except Exception:
pass
def _accept_new_item(self):
"""人工确认秤上是新的一件:解除锁定,重新识别
秤上重量和刚才入过的那笔几乎一样时先问一句:21:34 现场就是按了
这颗按钮、又在人工页里选了「大白菜」,同一堆 11.9 kg 在 90 秒内
被入了两次(23.80 斤 × 2)。确认通过才解除 SKU 屏蔽。
"""
kg = float(getattr(self, '_last_w', 0.0) or 0.0)
lo = getattr(self.engine, '_last_ok', None) or {}
try:
prev = float(lo.get('kg') or 0.0)
except (TypeError, ValueError):
prev = 0.0
if prev > 0 and abs(kg - prev) <= max(0.02, min(0.06, max(kg, prev) * 0.015)):
ok = messagebox.askyesno(
'确认是另一件货?',
'秤上还是 %.1f kg,和刚才入过的「%s」一模一样。\n\n'
'同一堆货请点「否」,把货取走再放;\n'
'确实是另一件(同规格)再点「是」。' % (kg, lo.get('name') or '这堆货'),
parent=self.root)
if not ok:
return
self.engine.force_idle('已确认秤上是新的一件货,解除重复防护',
clear_dup=True)
try:
self.lbl_state.configure(text='待机中:请放货')
except Exception:
pass
# ------------------------------------------------------ 未决提交核实/解锁
def _unresolved_dialog(self, parent=None):
"""列本机的未决提交,允许逐笔向服务端核实或人工标记后解锁。
之前没有这个入口:一旦“结果不明”就把新提交永久锁死,现场只能
手工去删 data/journal/*.json,等于把机器锁成砖。
"""
recs = self.engine.unresolved_records()
d = self._dlg('未决提交核实', 720, 470, parent)
tk.Label(d, text='下面这些是“发出去了但没拿到明确结果”的提交。'
'在新旧结果核实清楚之前,本机不会发新的提交。',
font=FONT_MID, bg='#ffffff', fg='#5b6472', anchor='w',
justify='left', wraplength=660).pack(
fill='x', padx=16, pady=(12, 4))
body = tk.Text(d, height=10, font=FONT_MID, bd=1, relief='solid',
bg='#fbfcfd', fg='#22303c', wrap='word')
body.pack(fill='both', expand=True, padx=16, pady=6)
if not recs:
body.insert('end', '(当前没有未决提交,提交锁是开的)')
for r in recs:
body.insert('end', '%s\n' % r.get('operationId'))
body.insert('end', ' 工位 %s · 行 %s · %.3f kg · 数量 %s %s\n'
% (r.get('kind'), r.get('targetId'),
float(r.get('weight') or 0), r.get('qty'),
r.get('unit') or ''))
body.insert('end', ' 状态 %s · 建于 %s%s\n'
% (r.get('state'), r.get('createdAt'),
(' · ' + str(r.get('message')))
if r.get('message') else ''))
body.configure(state='disabled')
hint = tk.Label(d, text='', font=FONT_MID, bg='#ffffff', fg='#185fa5',
anchor='w', justify='left', wraplength=660)
hint.pack(fill='x', padx=16)
foot = tk.Frame(d, bg='#ffffff')
foot.pack(fill='x', padx=16, pady=(6, 12))
def close():
try:
d.grab_release()
except Exception:
pass
d.destroy()
def recheck():
hint.configure(text='逐笔向服务端核实中(只查不重发)…', fg='#185fa5')
btn_r.config(state='disabled')
def work():
try:
done, left, lines = self.engine.recheck_unresolved()
except Exception as e: # noqa: BLE001
done, left, lines = 0, len(recs), ['核实异常:%s' % e]
def fin():
self.log('未决提交核实:解除 %d 笔,仍待核实 %d 笔'
% (done, left))
for ln in lines:
self.log(' ' + ln)
close()
if left:
self._unresolved_dialog(parent)
self.root.after(0, fin)
threading.Thread(target=work, daemon=True).start()
def mark_uncommitted():
if not recs:
close()
return
if not messagebox.askyesno(
'标记为未提交',
'确认已经在后台核对过:这 %d 笔都没有真正入库?\n\n'
'标记后本机解锁,不会打印标签、也不会写台账。' % len(recs),
parent=d):
return
for r in recs:
self.engine.resolve_unresolved(
r.get('operationId'), 'not_committed',
'人工在后台核对:未入库')
self.engine.refresh_pending(initial=True)
close()
btn_r = tk.Button(foot, text='逐笔重新核实', font=FONT_BTN, bd=0,
bg='#185fa5', fg='white', cursor='hand2',
padx=18, pady=7, command=recheck)
btn_r.pack(side='left')
tk.Button(foot, text='我已核对:标记为未入库并解锁', font=FONT_MID,
bd=0, bg='#eef1f5', fg='#5b6472', cursor='hand2',
padx=14, pady=7, command=mark_uncommitted).pack(
side='left', padx=(8, 0))
tk.Button(foot, text='关 闭', font=FONT_MID, bd=0, bg='#eef1f5',
fg='#5b6472', cursor='hand2', padx=18, pady=7,
command=close).pack(side='right')
def _on_confirm(self, p):
self._show_confirm(p)
# ------------------------------------------------------------ 人工确认
def _show_confirm(self, p):
"""人工确认页(平板版):左边看货,右边圆角卡片网格,手指能拖着滑。
现场三点要求:
① 和主工作台一致的平板外观(圆角卡、大按钮、按下回弹)
② 商品选项多了要能用手指滑动(带惯性),不是只能滚鼠标
③ 卡片上直接看得到单号、客户和应验斤数,底部「已选」再对一遍
"""
px, font = self._px, self._font
top = self._confirm_top = tk.Toplevel(self.root)
top.title('人工确认')
top.attributes('-fullscreen', True)
top.configure(bg=C.bg)
rows = p.get('rows') or []
by_id = {r.get('id'): r for r in rows}
cand_ids = {c.get('id') for c in (p.get('candidates') or [])}
picking = self.engine.station == 'picking'
verb = '拣' if picking else '验'
wkg = float(p.get('weight') or 0)
state = {'sel': None}
cards = {}
badges = {}
# ---------------- 顶部红条 ----------------
bar = tk.Frame(top, bg='#a32d2d', height=px(76))
bar.pack(fill='x')
bar.pack_propagate(False)
tk.Label(bar, text='需要人工确认', font=font(22, 'bold'),
bg='#a32d2d', fg='white').pack(side='left', padx=px(20))
det = (p.get('detected') or '').strip()
if len(det) > 24:
det = det[:24] + '…'
tk.Label(bar,
text=('AI 识别:%s' % det) if det
else 'AI 识别:没认出名单里的商品',
font=font(17, 'bold'), bg='#a32d2d',
fg='#ffffff' if det else '#ffd166').pack(
side='left', padx=(px(4), px(18)))
tk.Label(bar, text='重量 %.2f kg · %.1f 斤' % (wkg, wkg * 2.0),
font=font(17, 'bold'), bg='#a32d2d', fg='white').pack(
side='left')
TouchButton(bar, text='✕ 放弃', command=lambda: do_cancel(),
fill='#8c2626', fg='white', height=px(48),
width=px(110), radius=px(24), font=font(14, 'bold'),
surface='#a32d2d').pack(side='right', padx=px(14))
# 这一页盖住整屏时,顶栏那颗「刷新待办」点不到,这里再放一颗
TouchButton(bar, text='刷新待办', command=self._refresh_pending_now,
fill='#8c2626', fg='white', height=px(48),
width=px(120), radius=px(24), font=font(14, 'bold'),
surface='#a32d2d').pack(side='right', padx=(0, px(8)))
body = tk.Frame(top, bg=C.bg)
body.pack(fill='both', expand=True, padx=px(14), pady=px(12))
# ---------------- 左列:抓拍图 + AI 结论 ----------------
left = Card(body, radius=px(18), pad=px(14), width=px(400))
left.pack(side='left', fill='y')
left.pack_propagate(False)
tk.Label(left.body, text='抓拍图片', font=font(12, 'bold'),
bg=C.surface, fg=C.ink2, anchor='w').pack(fill='x')
holder = tk.Frame(left.body, bg='#111418', height=px(250))
holder.pack(fill='x', pady=(px(8), 0))
holder.pack_propagate(False)
img_lbl = tk.Label(holder, bg='#111418')
img_lbl.pack(fill='both', expand=True)
try:
img = Image.open(p['snapshot'])
w, h = img.size
bw, bh = px(368), px(250)
k = max(bw / float(w), bh / float(h)) # cover:铺满不留黑边
nw, nh = max(bw, int(w * k)), max(bh, int(h * k))
try:
resample = Image.LANCZOS
except AttributeError:
resample = Image.ANTIALIAS
im2 = img.convert('RGB').resize((nw, nh), resample)
ox, oy = (nw - bw) // 2, (nh - bh) // 2
tkimg = ImageTk.PhotoImage(im2.crop((ox, oy, ox + bw, oy + bh)))
img_lbl.configure(image=tkimg)
img_lbl.image = tkimg
except Exception:
img_lbl.configure(text='(没有抓到图片)', font=font(12),
fg='#8a94a3')
info = Card(left.body, radius=px(14), pad=px(12), fill='#f7f9fc',
surface=C.surface)
info.pack(fill='both', expand=True, pady=(px(12), 0))
tk.Label(info.body, text='AI 识别结果', font=font(11), bg='#f7f9fc',
fg=C.ink3, anchor='w').pack(fill='x')
tk.Label(info.body, text=det or '无法识别', font=font(22, 'bold'),
bg='#f7f9fc', fg='#1f2937' if det else '#a32d2d',
anchor='w', justify='left', wraplength=px(330)).pack(fill='x')
tk.Label(info.body, text='称重 %.2f kg = %.1f 斤' % (wkg, wkg * 2),
font=font(16, 'bold'), bg='#f7f9fc', fg=C.green,
anchor='w').pack(fill='x', pady=(px(4), px(2)))
if p.get('warn'):
tk.Label(info.body, text=p['warn'], font=font(11), bg='#f7f9fc',
fg='#854f0b', anchor='w', justify='left',
wraplength=px(330)).pack(fill='x', pady=(px(4), 0))
tk.Label(info.body,
text='点卡片选中 → 底部对单号与斤数 → 点「确认选中这一行」\n'
'名单可以用手指上下拖动',
font=font(11), bg='#f7f9fc', fg=C.ink3, anchor='w',
justify='left', wraplength=px(330)).pack(
side='bottom', fill='x', pady=(px(8), 0))
# ---------------- 右列:搜索 + 商品卡片(可滑动) ----------------
right = Card(body, radius=px(18), pad=px(12))
right.pack(side='left', fill='both', expand=True, padx=(px(12), 0))
head = tk.Frame(right.body, bg=C.surface)
head.pack(fill='x')
self.lbl_cf_cnt = tk.Label(head, text='', font=font(13, 'bold'),
bg=C.surface, fg=C.ink, anchor='w')
self.lbl_cf_cnt.pack(side='left')
sbox = Card(head, radius=px(24), pad=px(2), height=px(52),
border='#cfd8e3')
sbox.pack(side='left', fill='x', expand=True, padx=(px(14), 0))
sbox.pack_propagate(False)
sv = tk.StringVar()
ent = tk.Entry(sbox.body, textvariable=sv, font=font(15), bd=0,
relief='flat', bg=C.surface, fg=C.ink,
insertbackground=C.brand)
ent._kb_mode = 'hand' # 找商品:默认中文手写
ent._kb_sys = True # 点输入框优先弹 Windows 系统键盘(手写)
ent._field_label = '搜索'
ent.pack(side='left', fill='x', expand=True, padx=px(12))
# 占位提示:输入框空着时给一句灰字,点一下就清掉
ph_txt = '搜索商品名称…'
ph_on = {'v': True}
def _ph_in(_e=None):
if ph_on['v']:
ph_on['v'] = False
sv.set('')
ent.configure(fg=C.ink)
def _ph_out(_e=None):
if not sv.get().strip():
ph_on['v'] = True
sv.set(ph_txt)
ent.configure(fg=C.ink3)
ent.insert(0, ph_txt)
ent.configure(fg=C.ink3)
ent.bind('<Button-1>', _ph_in, add='+')
ent.bind('<FocusIn>', _ph_in, add='+')
ent.bind('<FocusOut>', _ph_out, add='+')
for txt, cmd, bw in (('×', lambda: _clear_search(), 48),
('内置手写', lambda: self._show_osk('hand', ent), 88),
('系统键盘', lambda: self._sys_osk_fallback(ent), 88)):
TouchButton(head, text=txt, command=cmd, fill='#eef2f7',
fg=C.ink2, height=px(48), width=px(bw),
radius=px(24), font=font(12),
surface=C.surface).pack(side='right',
padx=(px(6), 0))
wrap = tk.Frame(right.body, bg=C.bg)
wrap.pack(fill='both', expand=True, pady=(px(10), 0))
cv = tk.Canvas(wrap, bg=C.bg, highlightthickness=0, bd=0,
takefocus=0)
cv.pack(side='left', fill='both', expand=True)
sb = ttk.Scrollbar(wrap, orient='vertical', command=cv.yview)
sb.pack(side='right', fill='y')
cv.configure(yscrollcommand=sb.set, yscrollincrement=1)
grid = tk.Frame(cv, bg=C.bg)
cv_win = cv.create_window((0, 0), window=grid, anchor='nw')
# 手指拖动 + 惯性;卡片上也能拖(attach_tree)
self._cf_scroll = TouchScroll(cv)
self._cf_scroll.attach(cv)
self._cf_scroll.attach(grid)
order = []
def sel_text(rid):
"""底部「已选」一行:品名 · 规格 · 单号 · 客户 · 应验斤数 · 称重斤数"""
r = by_id.get(rid) or {}
if not r:
return '已选:—(上方点一张商品卡片,这里显示单号与斤数)'
req = float(r.get('required_qty') or r.get('prepare_qty') or 0)
unit = r.get('unit') or ''
parts = ['已选:%s' % (self._std_name(r))]
if r.get('spec'):
parts.append('规格 %s' % r['spec'])
if r.get('order_code'):
parts.append('单号 %s' % r['order_code'])
if r.get('customer_name'):
parts.append(str(r['customer_name']))
if unit == '斤':
parts.append('应%s %.1f 斤' % (verb, req))
else:
parts.append('应%s %g %s' % (verb, req, unit))
parts.append('称重 %.2f kg(%.1f 斤)' % (wkg, wkg * 2.0))
return ' · '.join(parts)
def paint(rid):
state['sel'] = rid
for k, c in cards.items():
on = (k == rid)
try:
c.set_border(C.brand if on else C.line)
except Exception:
pass
b = badges.get(k)
if b is not None:
try:
b.configure(text='✓ 已选' if on else '',
bg=C.brand_soft if on else C.surface,
fg=C.brand if on else C.ink3)
except Exception:
pass
try:
self._cf_sel.configure(text=sel_text(rid))
except Exception:
pass
def submit(rid=None):
rid = rid or state['sel']
row = by_id.get(rid)
if row is None:
messagebox.showwarning('提示', '请先点一张商品卡片', parent=top)
return
_teardown()
self._confirm_top = None
self.engine.manual_submit(row)
def do_cancel():
_teardown()
self._confirm_top = None
self.engine.cancel_manual()
def _teardown():
try:
cv.unbind_all('<MouseWheel>')
except Exception:
pass
try:
top.destroy()
except Exception:
pass
def make_card(r):
rid = r.get('id')
c = Card(grid, radius=px(16), pad=px(12), border=C.line)
cards[rid] = c
nm = self._std_name(r)
top_row = tk.Frame(c.body, bg=C.surface)
top_row.pack(fill='x')
tk.Label(top_row, text=nm, font=font(17, 'bold'), bg=C.surface,
fg=C.ink, anchor='w', justify='left',
wraplength=px(210)).pack(side='left', fill='x',
expand=True)
b = tk.Label(top_row, text='', font=font(10, 'bold'),
bg=C.surface, fg=C.brand, padx=px(6))
b.pack(side='right')
badges[rid] = b
spec = r.get('spec') or ''
if spec:
tk.Label(c.body, text='规格 %s' % spec, font=font(11),
bg=C.surface, fg=C.ink3, anchor='w').pack(
fill='x', pady=(px(2), 0))
req = r.get('required_qty') or r.get('prepare_qty')
unit = r.get('unit') or ''
req_txt = '应%s %g %s' % (verb, float(req or 0), unit)
if unit == 'kg':
req_txt += '(%.1f 斤)' % (float(req or 0) * 2.0)
tk.Label(c.body, text=req_txt, font=font(16, 'bold'),
bg=C.surface, fg=C.green, anchor='w').pack(
fill='x', pady=(px(6), 0))
meta = ' · '.join(x for x in [r.get('order_code') or '',
r.get('customer_name') or ''] if x)
if meta:
tk.Label(c.body, text=meta, font=font(10), bg=C.surface,
fg=C.ink3, anchor='w', justify='left',
wraplength=px(220)).pack(fill='x', pady=(0, px(2)))
for wdg in [c] + _descendants(c):
wdg.bind('<ButtonRelease-1>',
lambda e, rid=rid: (
None if getattr(self._cf_scroll, 'moved', False)
else paint(rid)))
wdg.bind('<Double-Button-1>',
lambda e, rid=rid: submit(rid))
try:
self._cf_scroll.attach_tree(c)
except Exception:
pass
return c
def _descendants(w, depth=0):
out = []
if depth > 4:
return out
for ch in w.winfo_children():
out.append(ch)
out.extend(_descendants(ch, depth + 1))
return out
def relayout(_e=None):
w = cv.winfo_width()
if w < 120:
return
cols = max(2, int((w + px(10)) // px(280)))
for i, rid in enumerate(order):
cards[rid].grid(row=i // cols, column=i % cols,
sticky='nsew', padx=px(5), pady=px(5))
for c in range(cols):
grid.columnconfigure(c, weight=1, uniform='cf')
for c in range(cols, 12):
grid.columnconfigure(c, weight=0, uniform='')
_sync_scroll()
def _sync_scroll(_e=None):
try:
cv.configure(scrollregion=cv.bbox('all') or (0, 0, 0, 0))
except Exception:
pass
def fill(*_a):
q = '' if ph_on['v'] else ''.join(sv.get().split()).lower()
shown = [r for r in rows
if not q or q in ''.join(
(str(r.get('item_name') or '') + ' '
+ str(r.get('standard_name') or '')).split()).lower()]
if not q: # 本轮候选排前面,其余按原顺序垫后
shown = [r for r in shown if r.get('id') in cand_ids] + \
[r for r in shown if r.get('id') not in cand_ids]
shown = shown[:60]
for c in cards.values():
c.destroy()
cards.clear()
badges.clear()
order[:] = [r.get('id') for r in shown]
for r in shown:
make_card(r)
try:
self.lbl_cf_cnt.configure(
text='共 %d 行 · 点选,双击直接确认' % len(shown))
except Exception:
pass
relayout()
cv.yview_moveto(0)
_sync_scroll()
sv.trace_add('write', fill)
cv.bind('<Configure>',
lambda e: (cv.itemconfigure(cv_win, width=e.width),
relayout()))
grid.bind('<Configure>', _sync_scroll)
def _wheel(e):
# yscrollincrement=1(为了手指拖动精细),滚轮按像素走 60px 一格
step = -60 if getattr(e, 'delta', 0) > 0 else 60
cv.yview_scroll(step, 'units')
cv.bind_all('<MouseWheel>', _wheel)
# 清空按钮要把占位状态一起复位,否则点了 × 看不出变化
def _clear_search():
ph_on['v'] = False
sv.set('')
ent.configure(fg=C.ink)
# ---- 底部:已选摘要 + 平板大按钮 ----
self._cf_sel = tk.Label(right.body, text=sel_text(state['sel']),
font=font(14, 'bold'), bg='#eaf2ff',
fg='#17427a', anchor='w', justify='left',
padx=px(12), pady=px(9),
wraplength=px(600))
self._cf_sel.pack(fill='x', pady=(px(10), px(8)))
bf = tk.Frame(right.body, bg=C.surface)
bf.pack(fill='x')
TouchButton(bf, text='✔ 确认选中这一行', command=submit,
fill=C.green, fg='white', height=px(62), radius=px(16),
font=font(17, 'bold'), surface=C.surface).pack(
side='left', fill='x', expand=True)
TouchButton(bf, text='✘ 放弃本次', command=do_cancel,
fill='#f0f2f5', fg='#a32d2d', height=px(62),
width=px(170), radius=px(16), font=font(15, 'bold'),
surface=C.surface).pack(side='left', padx=(px(10), 0))
fill()
top.protocol('WM_DELETE_WINDOW', lambda: (do_cancel(), ))
self._cf_unbind = _teardown
# -------------------------------------------------- 免称重(拍照计数)
def _count_btn_text(self):
try:
picking = self.engine.station == 'picking'
n = len(self.engine.noweigh_rows())
except Exception:
picking, n = False, 0
verb = '不称重分拣' if picking else '免称重收货'
return ('%s(%d)' % (verb, n)) if n else verb
def _start_count(self):
ok, msg = self.engine.start_count_cycle()
if ok:
return
self.log('免称重:' + msg)
try:
messagebox.showinfo('不称重(不用上秤)', msg, parent=self.root)
except Exception:
pass
def _on_count_confirm(self, p):
"""免称重确认页:左边看货,右边核对商品和数量。
这类商品重量帮不上忙(桶装水 18.9kg ≠ 18.9 桶),所以数量必须让
人看一眼再提交 —— 这也是没有称重核对时唯一的防错手段。
"""
px, font = self._px, self._font
try:
if self._count_top is not None and self._count_top.winfo_exists():
self._count_top.destroy()
except Exception:
pass
d = self._count_top = self._dlg(
'不称重分拣 · 核对数量' if (p.get('station') or self.engine.station) == 'picking'
else '免称重 · 核对数量', 960, 740)
picking = (p.get('station') or self.engine.station) == 'picking'
verb = '分拣' if picking else '收货'
rows = p.get('rows') or []
sel = {'row': p.get('row')}
cand = set(p.get('candidates') or [])
# ---- 顶条 ----
head = tk.Frame(d, bg='#0f6e56', height=px(62))
head.pack(fill='x')
head.pack_propagate(False)
tk.Label(head, text=('不称重分拣 · 核对商品与数量' if picking
else '免称重 · 不称重商品%s' % verb),
font=font(18, 'bold'), bg='#0f6e56', fg='white').pack(
side='left', padx=px(16))
det = (p.get('detected') or '').strip()
tk.Label(head, text=('AI 识别:%s' % (det[:20] + ('…' if len(det) > 20
else '')))
if det else 'AI 识别:没认出(请手动点选)',
font=font(13, 'bold'), bg='#0f6e56',
fg='#d7f0e6' if det else '#ffd166').pack(
side='left', padx=px(8))
tk.Button(head, text='✕ 放弃', font=font(12, 'bold'), bd=0,
bg='#0b5a47', fg='white', activebackground='#084535',
activeforeground='white', cursor='hand2',
padx=px(14), pady=px(6),
command=lambda: do_cancel()).pack(side='right', padx=px(12))
body = tk.Frame(d, bg='#ffffff')
body.pack(fill='both', expand=True, padx=px(12), pady=px(10))
# ---- 左:抓拍图 + 提示 ----
left = tk.Frame(body, bg='#ffffff', width=px(360))
left.pack(side='left', fill='y')
left.pack_propagate(False)
holder = tk.Frame(left, bg='#111418', width=px(340), height=px(230))
holder.pack()
holder.pack_propagate(False)
img_lbl = tk.Label(holder, bg='#111418')
img_lbl.pack(fill='both', expand=True)
try:
img = Image.open(p['snapshot'])
w, h = img.size
k = min(px(340) / float(w), px(230) / float(h))
nw, nh = max(1, int(w * k)), max(1, int(h * k))
try:
rs = Image.LANCZOS
except AttributeError:
rs = Image.ANTIALIAS
tkimg = ImageTk.PhotoImage(
img.convert('RGB').resize((nw, nh), rs))
img_lbl.configure(image=tkimg)
img_lbl.image = tkimg
except Exception:
img_lbl.configure(text='(没有抓到图片)', font=font(12),
fg='#8a94a3')
tk.Label(left, text=('镜头里的货要和下面选中的商品一致。\n'
+ ('数量填实际拣的(不用上秤)。'
if picking else
'数量按实际点数填。')),
font=font(11), bg='#ffffff', fg='#8a94a3',
anchor='w', justify='left', wraplength=px(340)).pack(
fill='x', pady=(px(8), 0))
# ---- 右:商品 + 数量 ----
right = tk.Frame(body, bg='#ffffff')
right.pack(side='left', fill='both', expand=True, padx=(px(12), 0))
tk.Label(right, text='本次%s的商品' % verb, font=font(11),
bg='#ffffff', fg='#8a94a3', anchor='w').pack(fill='x')
lbl_name = tk.Label(right, text='(未选)', font=font(26, 'bold'),
bg='#ffffff', fg='#1f2937', anchor='w',
justify='left', wraplength=px(470))
lbl_name.pack(fill='x')
lbl_left = tk.Label(right, text='', font=font(13), bg='#ffffff',
fg='#0f6e56', anchor='w')
lbl_left.pack(fill='x', pady=(px(2), px(6)))
# 行多的时候(分拣待办动辄几十行)按名字过滤,别让人在列表里翻
var_q = tk.StringVar(value='')
srow = tk.Frame(right, bg='#f0f2f5')
srow.pack(fill='x', pady=(0, px(6)))
tk.Label(srow, text='🔍', font=font(12), bg='#f0f2f5',
fg='#8a94a3').pack(side='left', padx=(px(8), 0))
ent_s = tk.Entry(srow, textvariable=var_q, font=font(13), bd=0,
bg='#f0f2f5', fg='#1f2937',
insertbackground='#1f2937')
ent_s._kb_mode = 'text'
ent_s._kb_sys = True # 优先系统键盘(手写)
ent_s._field_label = '搜索商品'
ent_s.pack(side='left', fill='x', expand=True, padx=px(6), pady=px(7))
wrap = tk.Frame(right, bg='#f7f9fc', height=px(320 if picking else 180))
wrap.pack(fill='x')
wrap.pack_propagate(False)
cv = tk.Canvas(wrap, bg='#f7f9fc', highlightthickness=0)
sb = ttk.Scrollbar(wrap, orient='vertical', command=cv.yview)
sb.pack(side='right', fill='y')
cv.pack(side='left', fill='both', expand=True)
cv.configure(yscrollcommand=sb.set)
lst = tk.Frame(cv, bg='#f7f9fc')
cv.create_window((0, 0), window=lst, anchor='nw')
lst.bind('<Configure>',
lambda e: cv.configure(scrollregion=cv.bbox('all')))
cv.bind('<Configure>',
lambda e: cv.itemconfigure(cv.find_all()[0], width=e.width))
cards = {}
def paint(rid):
for k, b in cards.items():
on = (k == rid)
try:
b.configure(bg='#e6f4ee' if on else '#ffffff',
highlightbackground='#0f6e56' if on
else '#e2e8f2')
except Exception:
pass
def pick(row):
sel['row'] = row
lbl_name.configure(text=self._std_name(row))
req = M.required_qty_of(row, None)
unit = row.get('unit') or ''
if M.can_scale_determine_qty(unit):
lbl_left.configure(text='待办还剩 %g %s(不称重,按实际%s数填)'
% (float(req or 0), unit, unit))
else:
lbl_left.configure(text='待办还剩 %g %s(按件计量,不用放秤)'
% (float(req or 0), unit))
var_qty.set('%g' % (req or 1.0))
lbl_unit.configure(text=unit)
paint(row.get('id'))
def rebuild(*_a):
for ch in lst.winfo_children():
ch.destroy()
cards.clear()
kw = (var_q.get() or '').strip().lower()
shown = [r for r in rows
if not kw or kw in (str(r.get('item_name') or '')
+ ' ' + str(r.get('standard_name')
or '')).lower()]
for r in shown:
rid = r.get('id')
b = tk.Frame(lst, bg='#ffffff', highlightthickness=2,
highlightbackground='#e2e8f2')
b.pack(fill='x', padx=px(6), pady=px(3))
cards[rid] = b
tk.Label(b, text=self._std_name(r),
font=font(15, 'bold'), bg='#ffffff', fg='#1f2937',
anchor='w').pack(side='left', padx=px(10),
pady=px(8))
req = M.required_qty_of(r, None)
tk.Label(b, text='%g %s' % (float(req or 0),
r.get('unit') or ''),
font=font(14, 'bold'), bg='#ffffff', fg='#0f6e56',
anchor='e').pack(side='right', padx=px(10))
for w in [b] + list(b.winfo_children()):
w.bind('<Button-1>', lambda e, row=r: pick(row))
if not shown:
tk.Label(lst, text='没有匹配的商品,清空搜索框看全部',
font=font(12), bg='#f7f9fc', fg='#8a94a3',
pady=px(16)).pack(fill='x')
paint((sel.get('row') or {}).get('id'))
try:
cv.update_idletasks()
cv.configure(scrollregion=cv.bbox('all'))
except Exception:
pass
var_q.trace_add('write', rebuild)
rebuild()
qrow = tk.Frame(right, bg='#ffffff')
qrow.pack(fill='x', pady=(px(10), 0))
tk.Label(qrow, text='数量', font=font(14, 'bold'), bg='#ffffff',
fg='#333').pack(side='left')
var_qty = tk.StringVar(value='1')
def step(dv):
try:
q = float(var_qty.get() or 0) + dv
except ValueError:
q = dv
if q < 0:
q = 0
var_qty.set('%g' % q)
tk.Button(qrow, text='−', font=font(20, 'bold'), bd=0, bg='#eef1f5',
fg='#333', width=3, cursor='hand2',
command=lambda: step(-1)).pack(side='left', padx=(px(12), 0))
ent_q = tk.Entry(qrow, textvariable=var_qty, font=font(22, 'bold'),
width=6, justify='center', bd=0, bg='#f7f9fc',
fg='#0f6e56', insertbackground='#0f6e56')
ent_q._kb_mode = 'num'
ent_q._field_label = '数量'
ent_q.pack(side='left', padx=px(6), pady=px(2))
tk.Button(qrow, text='+', font=font(20, 'bold'), bd=0, bg='#eef1f5',
fg='#333', width=3, cursor='hand2',
command=lambda: step(+1)).pack(side='left')
lbl_unit = tk.Label(qrow, text='', font=font(15, 'bold'),
bg='#ffffff', fg='#5f5e5a')
lbl_unit.pack(side='left', padx=px(10))
if p.get('warn'):
tk.Label(right, text=p['warn'], font=font(11), bg='#ffffff',
fg='#854f0b', anchor='w', justify='left',
wraplength=px(470)).pack(fill='x', pady=(px(6), 0))
def close():
try:
d.destroy()
except Exception:
pass
self._count_top = None
def do_submit():
row = sel['row']
if row is None:
messagebox.showwarning('还没选商品',
'请先在列表里点一下这次要%s的商品。' % verb,
parent=d)
return
try:
qty = float(var_qty.get())
except (TypeError, ValueError):
messagebox.showwarning('数量不对', '数量请填数字,例如 1 或 2。',
parent=d)
return
ok, msg = self.engine.submit_count(row, qty)
if not ok:
messagebox.showwarning('不能提交', msg, parent=d)
return
close()
def do_cancel():
self.engine.cancel_count('免称重:已放弃')
close()
def do_retry():
self.engine.cancel_count('')
close()
self._start_count()
bf = tk.Frame(right, bg='#ffffff')
bf.pack(side='bottom', fill='x', pady=(px(12), 0))
tk.Button(bf, text='✔ 确认%s' % verb, font=font(18, 'bold'), bd=0,
bg='#0f6e56', fg='white', activebackground='#0c5744',
activeforeground='white', cursor='hand2',
pady=px(12), command=do_submit).pack(
side='left', fill='x', expand=True)
tk.Button(bf, text='重拍', font=font(14, 'bold'), bd=0, bg='#eef1f5',
fg='#378add', cursor='hand2', padx=px(16), pady=px(12),
command=do_retry).pack(side='left', padx=(px(8), 0))
tk.Button(bf, text='放弃', font=font(14, 'bold'), bd=0, bg='#f0f2f5',
fg='#a32d2d', cursor='hand2', padx=px(16), pady=px(12),
command=do_cancel).pack(side='left', padx=(px(8), 0))
# 预选:AI 命中的行优先,没命中时单选候选里的第一行
pre = sel['row']
if pre is None:
cand_rows = [r for r in rows if r.get('id') in cand]
if len(cand_rows) == 1:
pre = cand_rows[0]
if pre is None and len(rows) == 1:
pre = rows[0]
if pre is not None:
pick(pre)
d.protocol('WM_DELETE_WINDOW', lambda: do_cancel())
# ------------------------------------------------------------ 设置(简化)
def _dlg(self, title, ww, hh, parent=None):
"""居中弹出的小窗(相对父窗口),统一白底、模态。"""
base = parent or self.root
d = tk.Toplevel(base)
d.title(title)
d.configure(bg='#ffffff')
d.transient(base)
d.resizable(False, False)
try:
d.grab_set()
except Exception:
pass
try:
px = base.winfo_rootx() + (base.winfo_width() - ww) // 2
py = base.winfo_rooty() + (base.winfo_height() - hh) // 2
except Exception:
px = (d.winfo_screenwidth() - ww) // 2
py = (d.winfo_screenheight() - hh) // 2
d.geometry('%dx%d+%d+%d' % (ww, hh, max(0, px), max(0, py)))
return d
def _prompt_sync(self, win=None, refresh=None):
"""手动同步识别提示词(后台跑,UI 不卡)。"""
store = getattr(self.engine.recog, 'prompts', None)
if store is None:
messagebox.showinfo('提示词', '当前识别器不读取服务端模板',
parent=win or self.root)
return
if not store.enabled:
messagebox.showinfo(
'提示词',
'配置里已关闭服务端提示词(vision.prompt_source=local),\n'
'现在用的是程序内置的那份。要恢复请在高级设置里改回来。',
parent=win or self.root)
return
self.engine._sync_prompts(force=True)
def later():
try:
if refresh:
refresh()
origin = store.origin_label()
if store.online:
messagebox.showinfo('提示词已同步',
'当前用词:%s\n%s'
% (origin, store.summary()),
parent=win or self.root)
else:
messagebox.showwarning(
'没连上服务端',
'继续用%s。\n原因:%s'
% (origin, store.last_error or '网络不通'),
parent=win or self.root)
except Exception:
pass
(win or self.root).after(1200, later)
def _prompt_detail(self, win=None):
"""看当前真正发给模型的提示词(含本次名单占位说明)。"""
store = getattr(self.engine.recog, 'prompts', None)
if store is None:
return
top = tk.Toplevel(win or self.root)
top.title('当前识别提示词')
top.configure(bg=C.bg)
top.transient(win or self.root)
px, font = self._px, self._font
WW, HH = px(760), px(600)
try:
base = win or self.root
cx = base.winfo_rootx() + (base.winfo_width() - WW) // 2
cy = base.winfo_rooty() + (base.winfo_height() - HH) // 2
cx = max(0, min(cx, base.winfo_screenwidth() - WW))
cy = max(0, min(cy, base.winfo_screenheight() - HH - px(40)))
except Exception:
cx = cy = px(60)
top.geometry('%dx%d+%d+%d' % (WW, HH, cx, cy))
try:
top.lift()
top.focus_force()
except Exception:
pass
keys = [('weigh.recognize.pick_list', '看图认品(限名单)'),
('weigh.recognize.synonym', '同物异名核查'),
('weigh.recognize.handwrite', '手写读字')]
tk.Label(top, text='当前识别提示词', font=font(18, 'bold'),
bg=C.bg, fg=C.ink).pack(anchor='w', padx=px(18),
pady=(px(12), 0))
tk.Label(top, text='这些文字由服务端「AI 提示词」页维护;'
'这里是端上此刻真正用的版本(含离线缓存)。',
font=font(11), bg=C.bg, fg=C.ink2).pack(
anchor='w', padx=px(18), pady=(px(2), px(8)))
wrap = tk.Frame(top, bg=C.bg)
wrap.pack(fill='both', expand=True, padx=px(16),
pady=(0, px(12)))
txt = tk.Text(wrap, font=font(11), bg='#ffffff', fg=C.ink,
wrap='char', bd=0, padx=px(10), pady=px(8))
bar = tk.Scrollbar(wrap, command=txt.yview)
txt.configure(yscrollcommand=bar.set)
bar.pack(side='right', fill='y')
txt.pack(side='left', fill='both', expand=True)
parts = []
for key, cn in keys:
tpl, meta = store.template(key)
parts.append('【%s】%s\n来源:%s 版本:%s\n%s\n'
% (cn, key,
{'server': '服务端', 'cache': '服务端缓存(离线)',
'builtin': '程序内置'}.get(meta['source'],
meta['source']),
meta['version'] if meta['version'] is not None
else '内置',
'-' * 46))
parts.append(tpl + '\n\n')
txt.insert('1.0', ''.join(parts))
txt.configure(state='disabled')
def _settings(self):
"""简化设置:只看三台设备 + 服务端,点「更换」才展开细节。
现场只用得着「换摄像头 / 换秤 / 换打印机」,所以主页只放这三张卡
和一行的服务端信息;30 多个参数全部收进「高级设置…」,平时不用看。
"""
px, font = self._px, self._font
sw = self.root.winfo_screenwidth()
sh = self.root.winfo_screenheight()
# 高度按屏幕给足(1440×900 现场机器取 860):卡片已经 7 张,
# 1080p 与 900p 用同一个值也能放下,不再靠「猜 800 够不够」。
W, H = min(sw - px(40), px(760)), min(sh - px(40), px(860))
s = tk.Toplevel(self.root)
s.title('设置')
s.configure(bg=C.bg)
s.resizable(False, False)
s.transient(self.root)
s.geometry('%dx%d+%d+%d' % (W, H, max(0, (sw - W) // 2),
max(0, (sh - H) // 2)))
def info_text():
"""工位 · 账号 · 版本 · 今日完成 —— 并进标题行,省一张卡的位置。"""
who = str(self._get('account.username', '') or '未登录')
station = '分拣工位' if self.engine.station == 'picking' \
else '入库工位'
today = getattr(self, 'lbl_today', None)
t = today.cget('text') if today is not None else ''
return '%s · %s · v%s%s' % (
station, who, APP_VERSION, (' · ' + t) if t else '')
head = tk.Frame(s, bg=C.bg)
head.pack(fill='x', padx=px(22), pady=(px(14), 0))
tk.Label(head, text='设置', font=font(22, 'bold'),
bg=C.bg, fg=C.ink).pack(side='left')
lbl_info = tk.Label(head, text=info_text(), font=font(11),
bg=C.bg, fg=C.ink3)
lbl_info.pack(side='right', pady=(px(10), 0))
tk.Label(s, text='点「自动识别设备」程序自己找;要指定某台就点右边「更换…」。',
font=font(12), bg=C.bg, fg=C.ink2).pack(
anchor='w', padx=px(22), pady=(px(2), px(10)))
box = tk.Frame(s, bg=C.bg)
box.pack(fill='both', expand=True, padx=px(18))
def card(name, text, buttons):
c = tk.Frame(box, bg=C.surface, highlightthickness=1,
highlightbackground=C.line)
c.pack(fill='x', pady=(0, px(10)))
left = tk.Frame(c, bg=C.surface)
left.pack(side='left', fill='both', expand=True,
padx=(px(16), px(6)), pady=px(11))
tk.Label(left, text=name, font=font(15, 'bold'),
bg=C.surface, fg=C.ink, anchor='w').pack(fill='x')
lbl = tk.Label(left, text=text, font=font(12), bg=C.surface,
fg=C.ink2, anchor='w', justify='left',
wraplength=px(380))
lbl.pack(fill='x', pady=(px(3), 0))
right = tk.Frame(c, bg=C.surface)
right.pack(side='right', padx=(0, px(12)))
for txt, fn, kind in buttons:
bg, fg = ((C.brand_soft, C.brand) if kind == 'ghost'
else (C.brand, '#ffffff'))
tk.Button(right, text=txt, font=font(12), bd=0, bg=bg, fg=fg,
cursor='hand2', padx=px(14), pady=px(9),
activebackground=shade(bg, 0.94),
activeforeground=fg,
command=fn).pack(side='left', padx=(px(8), 0))
return lbl
# ---- 状态文案:实时读设备真状态,不靠配置猜 ----
def short(t, n=26):
t = str(t or '').replace('\n', ' ').strip()
return t if len(t) <= n else t[:n] + '…'
def err_cn(e):
"""把串口/摄像头的英文异常翻成一句话,卡片上才放得下。"""
t = str(e or '')
low = t.lower()
if 'permission' in low or '拒绝访问' in t or 'access is denied' in low:
return '串口被其它程序占用'
if 'could not open port' in low or 'filenotfound' in low:
return '串口打不开(查线/驱动)'
if 'timeout' in low or 'timed out' in low:
return '收不到数据'
return short(t, 18)
def cam_text():
if self._get('camera.simulate', False):
return '模拟画面(没接真实摄像头)'
op = getattr(self.engine.frames, 'opened', None)
if op:
vals = (list(op) + [''] * 5)[:5]
return '%s · %s×%s' % (vals[4] or ('%s 号' % vals[0]),
vals[2], vals[3])
return '未就绪 · ' + short(self.engine.frames.preview_status(), 16)
def scale_text():
st = self.engine.scale.state(self.cfg.get('flow', {}))
port = self._get('scale.port', '')
baud = self._get('scale.baudrate', '')
if self._get('scale.simulate', False):
return '模拟秤 · %.3f kg(没接真实秤)' % st.get('weight', 0)
if st.get('connected'):
return '%s · %s 波特率 · 已连接 %.3f kg' % (
port, baud, st.get('weight', 0))
err = err_cn(st.get('error'))
return '%s · %s 波特率 · 没数据%s' % (
port, baud, (':' + err) if err else '(点「更换」自动找波特率)')
def prn_text():
if not self._get('printer.enabled', True):
return '已停用(分拣完不打标签)'
name = str(self._get('printer.printer_name', '') or '')
if not name:
return '未选择(分拣完不打标签)'
try:
from core.printing import label as _LB
w = _LB._num(self._get('printer.width_mm', 50), 50)
h = _LB._num(self._get('printer.height_mm', 50), 50)
return '%s · %g×%gmm' % (name, w, h)
except Exception:
return name
def srv_text():
if self._get('server.mock', False):
return '离线模拟 · 不连服务器(内置演示数据)'
url = str(self._get('server.base_url', '') or '')
for pre in ('https://', 'http://'):
url = url.replace(pre, '')
url = url.rstrip('/')
if url.endswith('/api'):
url = url[:-4]
who = getattr(self.engine.api, 'account_name', '') or \
str(self._get('account.username', '') or '')
return '在线 · %s%s' % (url, (' · ' + who) if who else '')
lbl_cam = card('摄像头', cam_text(),
[('更换…', lambda: self._pick_camera(s, refresh),
'ghost')])
lbl_scale = card('电子秤', scale_text(),
[('去皮/置零…', lambda: self._scale_cmd_dialog(
s, refresh), 'ghost'),
('更换…', lambda: self._pick_scale(s, refresh),
'ghost')])
lbl_prn = card('标签打印机', prn_text(),
[('换机…', lambda: self._pick_printer(s, refresh),
'ghost'),
('标签纸…', lambda: self._label_setup(s, refresh),
'ghost'),
('试打', lambda: self._test_print(s), 'solid')])
lbl_srv = card('服务端与账号', srv_text(),
[('设置…', lambda: self._conn_settings(s, refresh),
'ghost')])
def prompt_text():
store = getattr(self.engine.recog, 'prompts', None)
if store is None:
return '内置(当前识别器不读取服务端模板)'
s = store.summary()
if not store.enabled:
return '内置默认 · 已关闭服务端提示词'
if s.startswith('内置默认'):
return '内置默认 · 没取到服务端模板,识别照常'
return s + ('(离线,用上次同步的)' if not store.online else '')
lbl_prompt = card(
'AI 识别提示词(服务端下发,改完不用重装)', prompt_text(),
[('看当前用词…', lambda: self._prompt_detail(s), 'ghost'),
('立即同步', lambda: self._prompt_sync(s, refresh), 'solid')])
def snap_text():
d, days, keep_min, max_mb, _iv = self.engine.snap_settings()
# 目录里可能上万张,每次刷新都 stat 一遍会拖慢设置页,30 秒缓存
at, n, b = getattr(self, '_snap_usage', (0, 0, 0))
if time.monotonic() - at > 30:
try:
n, b = retention.usage(d)
except Exception:
n, b = 0, 0
self._snap_usage = (time.monotonic(), n, b)
tail = ('上限 %s' % retention.human(max_mb * 1024 * 1024)
if max_mb else '不限总量')
txt = '%s · %d 张 / %s · 保留 %d 天、至少留 %d 张(%s)' % (
d, n, retention.human(b), int(days), keep_min, tail)
note = getattr(self.engine.frames, 'snap_note', '') or ''
return txt + ('· ' + note if note else '')
def open_snap_dir():
d = self.engine.snap_settings()[0]
try:
os.makedirs(d, exist_ok=True)
os.startfile(d)
except Exception as e: # noqa: BLE001
messagebox.showwarning('打不开目录', str(e), parent=s)
def clean_snap_now():
self.engine.cleanup_now()
self._snap_usage = (0, 0, 0)
lbl_snap.configure(text='正在清理…(删旧图,不影响正在过秤)')
def done():
self._snap_usage = (0, 0, 0)
try:
lbl_snap.configure(text=snap_text())
except Exception:
pass
s.after(1500, done)
lbl_snap = card('抓拍存放与清理(自动按天/按总量淘汰)', snap_text(),
[('打开目录', open_snap_dir, 'ghost'),
('立即清理', clean_snap_now, 'solid')])
def refresh():
try:
lbl_cam.configure(text=cam_text())
lbl_scale.configure(text=scale_text())
lbl_prn.configure(text=prn_text())
lbl_srv.configure(text=srv_text())
lbl_prompt.configure(text=prompt_text())
lbl_snap.configure(text=snap_text())
lbl_info.configure(text=info_text())
except Exception:
return
try:
s.after(2000, refresh)
except Exception:
pass
# ---- 识别状态行:开机/点按钮后在这里回话 ----
lbl_detect = tk.Label(s,
text=getattr(self, '_detect_summary', '')
or '还没识别过,点下面「自动识别设备」',
font=font(11), bg=C.bg, fg=C.ink3, anchor='w',
justify='left', wraplength=W - px(56))
lbl_detect.pack(fill='x', padx=px(22), pady=(0, px(2)))
def auto_detect():
lbl_detect.configure(
text='正在识别…(会短暂停一下预览以验证摄像头画面;'
'电子秤逐个波特率试,最多十几秒)', fg='#185fa5')
def done(res, changes):
try:
if changes:
txt = '已自动切换:' + ';'.join(
'%s → %s' % (k, n) for k, _o, n in changes)
lbl_detect.configure(text=txt, fg='#185fa5')
else:
from core import devices as dv
lbl_detect.configure(text='识别完成:' + dv.summary_text(res),
fg='#1f7a3d')
except Exception as e: # noqa: BLE001
self.log('设置页状态行没刷新:%s' % e)
refresh()
self._autodetect_devices(on_done=done, deep_camera=True)
foot = tk.Frame(s, bg=C.bg)
foot.pack(fill='x', padx=px(18), pady=(px(6), px(16)))
tk.Button(foot, text='自动识别设备', font=font(13, 'bold'), bd=0,
bg=C.brand, fg='white', cursor='hand2', padx=px(18),
pady=px(10), command=auto_detect).pack(side='left')
tk.Button(foot, text='高级设置…', font=font(12), bd=0, bg='#eef1f5',
fg=C.ink2, cursor='hand2', padx=px(16), pady=px(10),
command=lambda: (s.destroy(),
self._settings_advanced())).pack(
side='left', padx=(px(8), 0))
n_un = len(self.engine.unresolved_records()) \
if hasattr(self.engine, 'unresolved_records') else 0
tk.Button(foot, text='未决提交(%d)…' % n_un, font=font(12), bd=0,
bg=C.amber_soft if n_un else '#eef1f5',
fg=C.amber if n_un else C.ink2, cursor='hand2',
padx=px(16), pady=px(10),
command=lambda: self._unresolved_dialog(s)).pack(
side='left', padx=(px(8), 0))
tk.Button(foot, text='关 闭', font=font(13, 'bold'), bd=0,
bg=C.brand, fg='white', cursor='hand2', padx=px(30),
pady=px(10), command=s.destroy).pack(side='right')
refresh()
s.after(300, lambda: lbl_cam.configure(text=cam_text()))
# ---- 小窗:换摄像头(只列 USB,选中立即生效)----
def _pick_camera(self, parent=None, on_done=None):
d = self._dlg('更换摄像头', 600, 610, parent)
d.columnconfigure(0, weight=1)
d.rowconfigure(1, weight=1)
lbl_hint = tk.Label(
d, text='只列 USB 摄像头(手机投屏 / 虚拟摄像头 / 网络摄像头会被忽略)',
font=FONT_MID, bg='#ffffff', fg='#6b7480', anchor='w',
justify='left', wraplength=520)
lbl_hint.grid(row=0, column=0, sticky='ew', padx=16, pady=(14, 8))
lb = tk.Listbox(d, font=FONT_MID, height=6, activestyle='none',
exportselection=False, relief='solid', bd=1)
found = []
def done(res, err):
b_scan.configure(text='重新扫描', state='normal')
lb.delete(0, 'end')
found[:] = (res or {}).get('usb') or []
b_use.configure(state='normal' if found else 'disabled')
note = str((res or {}).get('note') or '')
if '|' in note: # 有设备扫到了但没画面 → 写清楚是哪台、为什么
lbl_hint.configure(
text='只列 USB 摄像头(虚拟/网络摄像头忽略)。'
+ note.split('|', 1)[1], fg='#b45309')
if err is not None:
lb.insert('end', '扫描失败:%s' % err)
return
if not found:
lb.insert('end', (res or {}).get('error')
or '没找到 USB 摄像头,检查线是否插好')
return
op = getattr(self.engine.frames, 'opened', None)
cur = op[0] if op else None
sel = 0
for i, c in enumerate(found):
mark = ''
if c['index'] == cur:
mark, sel = ' ← 正在用', i
lb.insert('end', '%d 号 | %s | %dx%d%s'
% (c['index'], c.get('name') or 'USB 摄像头',
c['width'], c['height'], mark))
lb.selection_set(sel)
def scan():
b_scan.configure(text='扫描中,最多 1 分钟…', state='disabled')
b_use.configure(state='disabled')
def work():
res, err = None, None
fs = getattr(self.engine, 'frames', None)
try:
from core.evidence.frames import list_cameras_full
if fs is not None and not self._get('camera.simulate',
False):
fs.suspend() # 让出设备,扫描才打得开
res = list_cameras_full(
4, int(self._get('camera.width', 0) or 0),
int(self._get('camera.height', 0) or 0))
except Exception as e: # noqa: BLE001
err = e
finally:
if fs is not None:
try:
fs.resume()
except Exception:
pass
self.root.after(0, lambda: done(res, err))
threading.Thread(target=work, daemon=True).start()
def use():
sel = lb.curselection()
if not sel or not found:
return
if self.engine.state != 'IDLE':
messagebox.showwarning('提示', '正在处理货物,等这件完成再换摄像头',
parent=d)
return
dev = found[sel[0]]
try:
self.engine.frames.select_device(
dev['index'], dev['backend'], dev['width'], dev['height'])
except Exception as e: # noqa: BLE001
messagebox.showerror('换不了', str(e), parent=d)
return
self._set('camera.simulate', False)
self._set('camera.index', int(dev['index']))
self._set('camera.backend', dev['backend'])
self._set('camera.name', dev.get('name') or '')
save_config(self.cfg)
self.log('已换到摄像头 %d(%s)'
% (dev['index'], dev.get('name') or ''))
d.destroy()
if on_done:
on_done()
row = tk.Frame(d, bg='#ffffff')
row.grid(row=4, column=0, sticky='ew', padx=16, pady=(4, 12))
b_scan = tk.Button(row, text='扫描 USB 摄像头', font=FONT_MID, bd=0,
bg='#eef1f5', fg='#185fa5', cursor='hand2',
padx=16, pady=8, command=scan)
b_scan.pack(side='left')
b_use = tk.Button(row, text='用这台', font=FONT_BTN, bd=0,
bg='#185fa5', fg='white', cursor='hand2',
padx=24, pady=8, state='disabled', command=use)
b_use.pack(side='right')
tk.Button(row, text='取消', font=FONT_MID, bd=0, bg='#ffffff',
fg='#8a8f98', cursor='hand2', padx=12, pady=8,
command=d.destroy).pack(side='right', padx=(0, 8))
lb.grid(row=1, column=0, sticky='nsew', padx=16)
# ---- 对焦:锁定焦距(固定工位最省事,相机不再每件来回找焦)----
foc = tk.Frame(d, bg='#ffffff')
foc.grid(row=2, column=0, sticky='ew', padx=16, pady=(8, 0))
lbl_foc = tk.Label(foc, text='对焦:—', font=FONT_MID, bg='#ffffff',
fg='#6b7480', anchor='w', justify='left',
wraplength=520)
lbl_foc.pack(side='left')
def _num(v):
try:
return str(int(round(float(v))))
except (TypeError, ValueError):
return '—'
def _locked():
v = str(self._get('camera.focus', '') or '').strip()
return v not in ('', '-1', 'None')
def focus_tick():
try:
if not d.winfo_exists():
return
except Exception:
return
info = getattr(self.engine.frames, 'focus_info', None) or {}
af = info.get('autofocus')
txt = ('对焦:%s | 相机回报 焦距=%s · 自动=%s'
% ('已锁定' if _locked() else '自动对焦',
_num(info.get('focus')), _num(af)))
color = '#6b7480'
if _locked() and af is not None and float(af) >= 0.5:
txt += '(这台相机不接受锁定,仍会自动找焦)'
color = '#b45309'
lbl_foc.configure(text=txt, fg=color)
try:
d.after(1000, focus_tick)
except Exception:
pass
def apply_focus(focus_val, af_val):
self._set('camera.focus', focus_val)
self._set('camera.autofocus', af_val)
try:
save_config(self.cfg)
self.engine.frames.reconfigure(self.cfg['camera'])
except Exception as e: # noqa: BLE001
messagebox.showerror('保存失败', str(e), parent=d)
def lock_focus():
info = getattr(self.engine.frames, 'focus_info', None) or {}
try:
f = int(round(float(info.get('focus'))))
except (TypeError, ValueError):
f = -1
if f <= 0:
messagebox.showwarning(
'锁不了',
'相机没有回报焦距值(这台型号可能不支持)。\n'
'那就只能用自动对焦,抓拍前程序会先等它收敛。',
parent=d)
return
apply_focus(str(f), '0')
self.log('摄像头焦距已锁定在 %d(此后不再来回找焦)' % f)
def auto_focus():
apply_focus('', '1')
self.log('摄像头已恢复自动对焦')
b_lock = tk.Button(foc, text='锁定这个焦距', font=FONT_MID, bd=0,
bg='#eef1f5', fg='#185fa5', cursor='hand2',
padx=12, pady=6, command=lock_focus)
b_lock.pack(side='right')
b_auto = tk.Button(foc, text='恢复自动', font=FONT_MID, bd=0,
bg='#ffffff', fg='#8a8f98', cursor='hand2',
padx=10, pady=6, command=auto_focus)
b_auto.pack(side='right', padx=(0, 6))
tk.Label(d, text='把要称的货放在秤上,等画面清楚后点「锁定这个焦距」,'
'之后每件都直接清晰,不再等对焦。\n'
'没锁也没关系:程序每次放货会主动催一次对焦,'
'并记得上次对好的位置,从近处起步(不用从零找)。',
font=('Microsoft YaHei', 9), bg='#ffffff', fg='#9aa3ae',
anchor='w', justify='left', wraplength=520).grid(
row=3, column=0, sticky='ew', padx=16, pady=(2, 0))
zrow = tk.Frame(d, bg='#ffffff')
zrow.grid(row=4, column=0, sticky='ew', padx=16, pady=(6, 0))
tk.Label(zrow, text='画面缩放', font=('Microsoft YaHei', 10),
bg='#ffffff', fg='#5f5e5a').pack(side='left')
tk.Button(zrow, text='−', font=FONT_MID, bd=0, bg='#eef1f5',
fg='#185fa5', cursor='hand2', padx=12, pady=2,
command=lambda: self._zoom_step(-0.5)).pack(side='left',
padx=(10, 0))
lbl_z = tk.Label(zrow, text='%.1f×' % getattr(self.engine.frames,
'zoom', 1.0),
font=('Microsoft YaHei', 10, 'bold'),
bg='#ffffff', fg='#185fa5', width=5)
lbl_z.pack(side='left')
tk.Button(zrow, text='+', font=FONT_MID, bd=0, bg='#eef1f5',
fg='#185fa5', cursor='hand2', padx=12, pady=2,
command=lambda: self._zoom_step(+0.5)).pack(side='left')
tk.Label(zrow, text='货物在画面里太小/太乱就放大:对焦更快、AI 也更准',
font=('Microsoft YaHei', 9), bg='#ffffff', fg='#9aa3ae').pack(
side='left', padx=(12, 0))
def zoom_tick():
try:
if not d.winfo_exists():
return
lbl_z.configure(text='%.1f×' % self.engine.frames.zoom)
d.after(600, zoom_tick)
except Exception:
pass
d.after(700, zoom_tick)
d.after(120, scan)
d.after(600, focus_tick)
# ---- 小窗:换电子秤(串口 + 波特率,可自动探测)----
def _pick_scale(self, parent=None, on_done=None):
d = self._dlg('更换电子秤', 560, 530, parent)
d.columnconfigure(0, weight=1)
d.rowconfigure(1, weight=1)
tk.Label(d, text='选串口 → 不确定波特率就点「自动探测」,程序挨个速率试,'
'能读出正常重量的就是它',
font=FONT_MID, bg='#ffffff', fg='#6b7480', anchor='w',
justify='left', wraplength=520).grid(row=0, column=0, sticky='ew',
padx=16, pady=(14, 8))
lb = tk.Listbox(d, font=FONT_MID, height=5, activestyle='none',
exportselection=False, relief='solid', bd=1)
found = []
baud_row = tk.Frame(d, bg='#ffffff')
baud_row.grid(row=2, column=0, sticky='ew', padx=16, pady=(10, 0))
tk.Label(baud_row, text='波特率', font=FONT_MID, bg='#ffffff',
fg='#41505f').pack(side='left')
var_baud = tk.StringVar(value=str(self._get('scale.baudrate', '9600')))
ttk.Combobox(baud_row, textvariable=var_baud, width=9,
state='readonly',
values=['600', '1200', '2400', '4800', '9600',
'19200']).pack(side='left', padx=(8, 12))
b_auto = tk.Button(baud_row, text='自动探测波特率', font=FONT_MID,
bd=0, bg='#eef1f5', fg='#185fa5', cursor='hand2',
padx=14, pady=6)
b_auto.pack(side='left')
def ports_done(ports, err=None):
b_scan.configure(text='重新扫描', state='normal')
lb.delete(0, 'end')
found[:] = ports or []
b_use.configure(state='normal' if found else 'disabled')
if err is not None:
lb.insert('end', '扫描失败:%s' % err)
return
if not ports:
lb.insert('end', '没发现串口,检查 RS232 线 / USB 转串口驱动')
return
cur = str(self._get('scale.port', ''))
sel = 0
for i, p in enumerate(ports):
mark = ''
if p['port'] == cur:
mark, sel = ' ← 正在用', i
lb.insert('end', '%s %s%s'
% (p['port'], p['description'], mark))
lb.selection_set(sel)
def scan():
b_scan.configure(text='扫描中…', state='disabled')
def work():
ports, err = [], None
try:
from core.scale.reader import list_serial_ports
ports = list_serial_ports()
except Exception as e: # noqa: BLE001
err = e
self.root.after(0, lambda: ports_done(ports, err))
threading.Thread(target=work, daemon=True).start()
def fin(hit, detail):
b_auto.configure(text='自动探测波特率', state='normal')
b_use.configure(state='normal')
if hit:
var_baud.set(str(hit))
messagebox.showinfo(
'找到了', '这台秤的波特率是 %d。\n点「用这个串口」保存即可。'
% hit, parent=d)
else:
messagebox.showwarning(
'没探到', '试了 1200 / 9600 / 4800 / 2400 / 19200 / 600 '
'都没读到正常数据。\n\n逐项检查:\n'
'· 秤是否已开机、屏幕有数\n'
'· 秤的通讯方式是否设为「连续发送」\n'
'· 线是否插在秤的 RS232 口(不是 USB 打印口)\n%s'
% (('\n· ' + detail) if detail else ''), parent=d)
def autodetect():
sel = lb.curselection()
port = (found[sel[0]]['port'] if (sel and found)
else str(self._get('scale.port', '')))
if not port:
messagebox.showwarning('提示', '先扫描并选一个串口', parent=d)
return
b_auto.configure(text='探测中…(约 10 秒)', state='disabled')
b_use.configure(state='disabled')
def work():
import time as _t
sc = getattr(self.engine, 'scale', None)
if sc is not None:
try:
sc.stop() # 放开串口才能独占探测
except Exception:
pass
_t.sleep(1.3)
hit, detail = None, ''
try:
import serial
for baud in (1200, 9600, 4800, 2400, 19200, 600):
try:
sp = serial.Serial(port, baud, bytesize=8,
parity='N', stopbits=1,
timeout=0.3)
except Exception as e: # noqa: BLE001
detail = '打不开 %s:%s' % (port, e)
break
sp.reset_input_buffer()
buf = b''
t0 = _t.time()
while _t.time() - t0 < 1.5:
buf += sp.read(256)
sp.close()
if not buf:
continue
good = sum(1 for c in buf
if 32 <= c < 127 or c in (10, 13))
if good / float(len(buf)) > 0.85:
hit = baud
break
except Exception as e: # noqa: BLE001
detail = str(e)
finally:
if sc is not None:
try:
sc.start()
except Exception:
pass
self.root.after(0, lambda: fin(hit, detail))
threading.Thread(target=work, daemon=True).start()
def use():
sel = lb.curselection()
if not sel or not found:
messagebox.showwarning('提示', '先扫描并选一个串口', parent=d)
return
if self.engine.state != 'IDLE':
messagebox.showwarning('提示', '正在处理货物,等这件完成再换秤',
parent=d)
return
p = found[sel[0]]
try:
baud = int(var_baud.get())
except Exception:
baud = 9600
self._set('scale.simulate', False)
self._set('scale.port', p['port'])
self._set('scale.baudrate', baud)
save_config(self.cfg)
try:
self.engine.scale.reconfigure(self.cfg['scale'])
except Exception as e: # noqa: BLE001
messagebox.showerror('换不了', str(e), parent=d)
return
self.log('已换到秤 %s · %d 波特率' % (p['port'], baud))
d.destroy()
if on_done:
on_done()
b_auto.configure(command=autodetect)
row = tk.Frame(d, bg='#ffffff')
row.grid(row=3, column=0, sticky='ew', padx=16, pady=(4, 12))
b_scan = tk.Button(row, text='扫描串口', font=FONT_MID, bd=0,
bg='#eef1f5', fg='#185fa5', cursor='hand2',
padx=16, pady=8, command=scan)
b_scan.pack(side='left')
b_use = tk.Button(row, text='用这个串口', font=FONT_BTN, bd=0,
bg='#185fa5', fg='white', cursor='hand2',
padx=20, pady=8, state='disabled', command=use)
b_use.pack(side='right')
tk.Button(row, text='取消', font=FONT_MID, bd=0, bg='#ffffff',
fg='#8a8f98', cursor='hand2', padx=12, pady=8,
command=d.destroy).pack(side='right', padx=(0, 8))
lb.grid(row=1, column=0, sticky='nsew', padx=16)
d.after(120, scan)
# ---- 小窗:去皮 / 置零 命令(真的落到秤上)----
def _scale_cmd_dialog(self, parent=None, on_done=None):
"""把「去皮 / 置零」从软件偏移改成真的发给秤。
现场问题(2026-11-04):点「置零」界面回「已置零(软件清零)」,可秤面
一动不动 —— 因为 config 里 zero_cmd / tare_cmd 是空的,程序只在软件里
减了个偏移。这里做成可现场验证的两步:
放货 → 点「自动探测」→ 程序挨个试常见命令,谁把秤面打到 0 就记下谁。
探测不出结果的秤(只发不收)也能明确告诉操作员:只能按秤面板的按键。
"""
from core.scale.reader import CMD_FAMILIES
d = self._dlg('去皮 / 置零(秤命令)', 640, 650, parent)
body = tk.Frame(d, bg='#ffffff')
body.pack(fill='both', expand=True, padx=18, pady=(14, 0))
tk.Label(body, text='去皮 / 置零 有没有真的落到秤上',
font=('Microsoft YaHei', 13, 'bold'), bg='#ffffff',
fg='#17334f', anchor='w').pack(fill='x')
tk.Label(body, text='① 在秤上放一件 0.2kg 以上的东西 ② 点下面「自动探测」\n'
'程序会把常见的 5 种去皮命令挨个发一遍,谁把秤面打到 0 '
'就记下它,配对的置零命令一起填好。',
font=FONT_MID, bg='#ffffff', fg='#6b7480', anchor='w',
justify='left', wraplength=580).pack(fill='x', pady=(4, 10))
live = tk.Label(body, text='秤:读取中…',
font=('Microsoft YaHei', 12, 'bold'),
bg='#f4f7fb', fg='#185fa5', anchor='w', padx=10,
pady=6)
live.pack(fill='x')
rawlbl = tk.Label(body, text='最近帧:—', font=('Consolas', 9),
bg='#ffffff', fg='#8a94a3', anchor='w',
justify='left', wraplength=580)
rawlbl.pack(fill='x', pady=(4, 0))
def cmd_row(label, key, hint):
tk.Label(body, text=label, font=('Microsoft YaHei', 10, 'bold'),
bg='#ffffff', fg='#5f6b7a', anchor='w').pack(
fill='x', pady=(10, 0))
var = tk.StringVar(value=str(self._get(key, '') or ''))
tk.Entry(body, textvariable=var, font=FONT_MID, relief='solid',
bd=1).pack(fill='x', ipady=3)
tk.Label(body, text=hint, font=('Microsoft YaHei', 9),
bg='#ffffff', fg='#9aa3ae', anchor='w').pack(fill='x')
return var
var_tare = cmd_row('去皮命令', 'scale.tare_cmd',
'留空 = 只做软件去皮(界面净重归 0,秤面不变)。格式:T\\r\\n 或 hex:1B 54')
var_zero = cmd_row('置零命令', 'scale.zero_cmd',
'留空 = 软件置零(界面毛重归 0.000,秤面不变)。空秤时按「置零」才有效')
fam_row = tk.Frame(body, bg='#ffffff')
fam_row.pack(fill='x', pady=(10, 0))
tk.Label(fam_row, text='已知型号', font=FONT_MID, bg='#ffffff',
fg='#5f6b7a').pack(side='left')
var_fam = tk.StringVar(value='')
cb = ttk.Combobox(fam_row, textvariable=var_fam,
state='readonly', width=34,
values=[n for n, _t, _z in CMD_FAMILIES])
cb.pack(side='left', fill='x', expand=True, padx=(8, 0))
msg = tk.Label(body, text='', font=FONT_MID, bg='#ffffff',
fg='#1f7a3d', anchor='w', justify='left',
wraplength=580)
msg.pack(fill='x', pady=(10, 0))
def fam_pick(_e=None):
for n, t, z in CMD_FAMILIES:
if n == var_fam.get():
var_tare.set(t)
var_zero.set(z)
msg.configure(text='已填入「%s」的命令,点「测试去皮」验证。'
% n.split('(')[0], fg='#185fa5')
break
cb.bind('<<ComboboxSelected>>', fam_pick)
foot = tk.Frame(d, bg='#ffffff')
foot.pack(fill='x', padx=18, pady=(8, 14))
b_probe = tk.Button(foot, text='自动探测', font=FONT_BTN, bd=0,
bg='#185fa5', fg='white', cursor='hand2',
padx=18, pady=8)
b_probe.pack(side='left')
b_tare = tk.Button(foot, text='测试去皮', font=FONT_MID, bd=0,
bg='#eef1f5', fg='#185fa5', cursor='hand2',
padx=14, pady=8)
b_tare.pack(side='left', padx=(8, 0))
b_zero = tk.Button(foot, text='测试置零', font=FONT_MID, bd=0,
bg='#eef1f5', fg='#185fa5', cursor='hand2',
padx=14, pady=8)
b_zero.pack(side='left', padx=(8, 0))
b_save = tk.Button(foot, text='保存并生效', font=FONT_BTN, bd=0,
bg='#0f6e56', fg='white', cursor='hand2',
padx=20, pady=8)
b_save.pack(side='right')
tk.Button(foot, text='关闭', font=FONT_MID, bd=0, bg='#ffffff',
fg='#8a8f98', cursor='hand2', padx=12, pady=8,
command=d.destroy).pack(side='right', padx=(0, 8))
def alive():
try:
return bool(d.winfo_exists())
except Exception:
return False
def busy(on, text=''):
for b in (b_probe, b_tare, b_zero, b_save):
try:
b.configure(state='disabled' if on else 'normal')
except Exception:
pass
if text:
msg.configure(text=text, fg='#185fa5')
def probe():
if self.engine.state != 'IDLE':
messagebox.showwarning('请稍候', '正在处理一件货,等它完成再探测',
parent=d)
return
busy(True, '正在挨个试常见命令,最多十几秒,别碰秤…')
def work():
try:
hit, txt = self.engine.scale.probe_tare_cmd()
except Exception as e: # noqa: BLE001
hit, txt = None, '探测出错:%s' % e
def done():
if not alive():
return
busy(False)
if hit:
_n, t, z = hit
var_tare.set(t)
var_zero.set(z)
msg.configure(
text=txt + ';已填好,点「保存并生效」。\n'
'现在秤面显示 0 是正常的(去皮生效了):'
'把东西拿走、按「测试置零」验证置零命令。',
fg='#1f7a3d')
else:
msg.configure(text=txt, fg='#a32d2d')
try:
self.root.after(0, done)
except Exception:
pass
threading.Thread(target=work, daemon=True).start()
def test(which):
busy(True, '正在给秤发命令…')
def work():
fn = (self.engine.scale.tare if which == 'tare'
else self.engine.scale.zero)
try:
ok, txt = fn()
except Exception as e: # noqa: BLE001
ok, txt = False, str(e)
def done():
if alive():
busy(False)
msg.configure(text=txt,
fg='#1f7a3d' if ok else '#a32d2d')
try:
self.root.after(0, done)
except Exception:
pass
threading.Thread(target=work, daemon=True).start()
def save():
self._set('scale.tare_cmd', var_tare.get().strip())
self._set('scale.zero_cmd', var_zero.get().strip())
try:
save_config(self.cfg)
self.engine.scale.reconfigure(self.cfg['scale'])
except Exception as e: # noqa: BLE001
messagebox.showerror('保存失败', str(e), parent=d)
return
self.log('秤命令已保存:去皮 %s / 置零 %s'
% (var_tare.get().strip() or '(未配置·软件去皮)',
var_zero.get().strip() or '(未配置·软件清零)'))
d.destroy()
if on_done:
on_done()
b_probe.configure(command=probe)
b_tare.configure(command=lambda: test('tare'))
b_zero.configure(command=lambda: test('zero'))
b_save.configure(command=save)
def tick():
if not alive():
return
try:
st = self.engine.scale.state(self.cfg.get('flow', {}))
fr = self.engine.scale.last_frames(2)
live.configure(
text='秤:毛重 %.3f kg · 净重 %.3f kg · %s'
% (st.get('gross', 0), st.get('weight', 0),
'有数据' if st.get('fresh') else '没数据'),
fg='#185fa5' if st.get('fresh') else '#a32d2d')
rawlbl.configure(text='最近帧:' + (
' | '.join('%s [%s]' % (f['text'], f['hex']) for f in fr)
if fr else '—'))
except Exception:
pass
try:
d.after(800, tick)
except Exception:
pass
tick()
# ---- 小窗:选标签打印机 ----
def _pick_printer(self, parent=None, on_done=None):
d = self._dlg('选择标签打印机', 560, 450, parent)
d.columnconfigure(0, weight=1)
d.rowconfigure(1, weight=1)
tk.Label(d, text='列出本机已安装的打印机;选完下一次打印就用它',
font=FONT_MID, bg='#ffffff', fg='#6b7480', anchor='w',
justify='left', wraplength=520).grid(row=0, column=0, sticky='ew',
padx=16, pady=(14, 8))
lb = tk.Listbox(d, font=FONT_MID, height=6, activestyle='none',
exportselection=False, relief='solid', bd=1)
found = []
def done(names, err=None):
b_scan.configure(text='重新列出', state='normal')
lb.delete(0, 'end')
found[:] = names or []
b_use.configure(state='normal' if found else 'disabled')
if err is not None:
lb.insert('end', '列出失败:%s' % err)
return
if not names:
lb.insert('end', '没发现打印机,检查 USB / 驱动')
return
cur = str(self._get('printer.printer_name', ''))
for i, n in enumerate(names):
if n == cur:
lb.insert('end', n + ' ← 当前')
lb.selection_set(i)
else:
lb.insert('end', n)
def scan():
b_scan.configure(text='读取中…', state='disabled')
def work():
names, err = [], None
try:
from core.printing.label import list_printers
names = list_printers()
except Exception as e: # noqa: BLE001
err = e
self.root.after(0, lambda: done(names, err))
threading.Thread(target=work, daemon=True).start()
def use():
sel = lb.curselection()
if not sel or not found:
return
name = found[sel[0]]
self._set('printer.enabled', True)
self._set('printer.printer_name', name)
save_config(self.cfg)
self.log('已选择打印机 %s' % name)
d.destroy()
if on_done:
on_done()
row = tk.Frame(d, bg='#ffffff')
row.grid(row=3, column=0, sticky='ew', padx=16, pady=(4, 12))
b_scan = tk.Button(row, text='列出打印机', font=FONT_MID, bd=0,
bg='#eef1f5', fg='#185fa5', cursor='hand2',
padx=16, pady=8, command=scan)
b_scan.pack(side='left')
b_use = tk.Button(row, text='用这台', font=FONT_BTN, bd=0,
bg='#185fa5', fg='white', cursor='hand2',
padx=24, pady=8, state='disabled', command=use)
b_use.pack(side='right')
tk.Button(row, text='取消', font=FONT_MID, bd=0, bg='#ffffff',
fg='#8a8f98', cursor='hand2', padx=12, pady=8,
command=d.destroy).pack(side='right', padx=(0, 8))
lb.grid(row=1, column=0, sticky='nsew', padx=16)
d.after(120, scan)
# ---- 小窗:服务端与账号 ----
def _conn_settings(self, parent=None, on_done=None):
d = self._dlg('服务端与账号', 560, 440, parent)
tk.Label(d, text='改完要重新登录才生效(顶栏「切换账号」)',
font=FONT_MID, bg='#ffffff', fg='#6b7480', anchor='w').pack(
anchor='w', padx=18, pady=(14, 8))
form = tk.Frame(d, bg='#ffffff')
form.pack(fill='both', expand=True, padx=18)
def field(label, value, secret=False):
tk.Label(form, text=label, font=FONT_MID, bg='#ffffff',
fg='#41505f', anchor='w').pack(fill='x', pady=(6, 0))
var = tk.StringVar(value=str(value))
tk.Entry(form, textvariable=var, font=FONT_MID, relief='solid',
show='*' if secret else '').pack(fill='x', ipady=4)
return var
v_url = field('服务器地址', self._get('server.base_url', ''))
v_user = field('账号', self._get('account.username', ''))
v_pwd = field('密码', self._get('account.password', ''), secret=True)
tk.Label(form, text='登录工位', font=FONT_MID, bg='#ffffff',
fg='#41505f', anchor='w').pack(fill='x', pady=(8, 0))
cur_role = str(self._get('account.role', 'picker'))
v_role = tk.StringVar(
value='分拣工位(拣货·打标签)' if cur_role == 'picker'
else '入库工位(验收·不打标签)')
ttk.Combobox(form, textvariable=v_role, state='readonly',
values=['分拣工位(拣货·打标签)',
'入库工位(验收·不打标签)']).pack(fill='x')
v_mock = tk.IntVar(value=1 if self._get('server.mock', False) else 0)
tk.Checkbutton(form, text='离线模拟(不连服务器,用演示数据)',
variable=v_mock, font=FONT_MID, bg='#ffffff',
fg='#41505f', anchor='w',
activebackground='#ffffff').pack(fill='x', pady=(10, 0))
def save():
self._set('server.base_url', v_url.get().strip())
self._set('account.username', v_user.get().strip())
self._set('account.password', v_pwd.get())
role = 'picker' if v_role.get().startswith('分拣') else 'inspector'
self._set('account.role', role)
self._set('server.mock', bool(v_mock.get()))
self._login_role = role
save_config(self.cfg)
self.log('服务端设置已保存(%s / %s)'
% ('离线模拟' if v_mock.get() else '在线', role))
messagebox.showinfo('已保存',
'已保存。\n请点顶栏「切换账号」重新登录生效。',
parent=d)
d.destroy()
if on_done:
on_done()
row = tk.Frame(d, bg='#ffffff')
row.pack(fill='x', padx=18, pady=12)
tk.Button(row, text='保 存', font=FONT_BTN, bd=0, bg='#0a6cf1',
fg='white', cursor='hand2', padx=28, pady=8,
command=save).pack(side='right')
tk.Button(row, text='取消', font=FONT_MID, bd=0, bg='#ffffff',
fg='#8a8f98', cursor='hand2', padx=12, pady=8,
command=d.destroy).pack(side='right', padx=(0, 8))
# ---- 试打一张标签(简化页与高级页共用)----
def _test_print(self, parent=None):
if self.engine.state != 'IDLE':
messagebox.showwarning('提示', '正在处理货物,等这件完成再试打',
parent=parent or self.root)
return
self.engine.scale.pause()
self.engine.frames.pause_preview()
try:
ok, msg = self.engine.printer.print_picking(
'测试客户', '测试商品', 1.00, 'kg', 'CT-TEST-PRINT')
except Exception as e: # noqa: BLE001
ok, msg = False, str(e)
finally:
try:
self.engine.scale.resume()
self.engine.frames.resume_preview()
except Exception:
pass
self.log(('✔ 试打:' if ok else '✘ 试打失败:') + msg)
if ok:
messagebox.showinfo('试打', '试打指令已发送。',
parent=parent or self.root)
else:
messagebox.showwarning('试打失败', msg,
parent=parent or self.root)
# ---- 小窗:标签纸尺寸(自动读驱动 + 实时预览)----
def _label_setup(self, parent=None, on_done=None):
"""改标签尺寸的唯一入口:改完立刻看到版面,不再盲改盲打。
以前宽高只能在高级设置里改两个数字,改完不知道会变成什么样,
打出来才发现后几行被裁、二维码缺一角。这里直接:
① 从打印机驱动读实际纸张(最准,不用量)
② 画一张等比缩略图,超宽/截断/二维码放不下当场标红
③ 一键试打,好不好看见纸说话
"""
from core.printing import label as LB
d = self._dlg('标签纸设置', 620, 610, parent)
cur_w = LB._num(self._get('printer.width_mm', 50), 50)
cur_h = LB._num(self._get('printer.height_mm', 50), 50)
cur_gap = LB._num(self._get('printer.gap_mm', 2), 2)
cur_dpi = int(LB._num(self._get('printer.dpi', 203), 203))
v_w = tk.StringVar(value=('%g' % cur_w))
v_h = tk.StringVar(value=('%g' % cur_h))
v_gap = tk.StringVar(value=('%g' % cur_gap))
v_dpi = tk.StringVar(value=str(cur_dpi))
top = tk.Frame(d, bg='#ffffff')
top.pack(fill='x', padx=16, pady=(14, 0))
tk.Label(top, text='先点右边这个按钮,程序会去读打印机驱动里'
'实际装的纸张尺寸,不用自己量。',
font=FONT_MID, bg='#ffffff', fg='#6b7480', anchor='w',
justify='left', wraplength=330).pack(side='left')
b_read = tk.Button(top, text='自动读取尺寸', font=FONT_MID, bd=0,
bg='#185fa5', fg='white', cursor='hand2',
padx=14, pady=7, command=lambda: do_read())
b_read.pack(side='right')
# ---- 输入区 ----
form = tk.Frame(d, bg='#ffffff')
form.pack(fill='x', padx=16, pady=(12, 0))
def field(col, name, var, width=8):
tk.Label(form, text=name, font=FONT_MID, bg='#ffffff',
fg='#41505f').grid(row=0, column=col * 2, sticky='w',
padx=(0, 6))
tk.Entry(form, textvariable=var, font=FONT_MID, relief='solid',
width=width).grid(row=0, column=col * 2 + 1, sticky='w',
padx=(0, 16), ipady=3)
field(0, '宽 mm', v_w)
field(1, '高 mm', v_h)
field(2, '间距 mm', v_gap, 6)
tk.Label(form, text='分辨率', font=FONT_MID, bg='#ffffff',
fg='#41505f').grid(row=0, column=6, sticky='w', padx=(0, 6))
ttk.Combobox(form, textvariable=v_dpi, state='readonly', width=6,
values=['203', '300', '600']).grid(row=0, column=7,
sticky='w')
lbl_info = tk.Label(d, text='', font=('Microsoft YaHei', 10),
bg='#ffffff', fg='#7a838f', anchor='w',
justify='left', wraplength=580)
lbl_info.pack(fill='x', padx=16, pady=(8, 0))
def calibrate():
if not messagebox.askyesno(
'校准走纸',
'打印机会空走 2~3 张标签来测间距(这几张是空白的)。\n'
'什么时候该做:换成不同间距的标签纸之后、打出来整体上移/'
'下移、或者隔一张出现空白。\n\n现在就开始?',
parent=d):
return
try:
ok, msg = self.engine.printer.calibrate()
except Exception as e: # noqa: BLE001
ok, msg = False, str(e)
self.log(('✔ 校准走纸:' if ok else '✘ 校准走纸失败:') + msg)
lbl_info.configure(
text=('已发校准指令,看打印机是否走纸。若没反应说明这台不支持'
' GAPDETECT,用打印机面板上的 FEED 键长按 3 秒也一样'
if ok else '校准失败:%s' % msg),
fg='#4b7a3a' if ok else '#a32d2d')
tk.Button(d, text='校准走纸(让打印机自己测标签间距)', font=('Microsoft '
'YaHei', 10), bd=0, bg='#ffffff', fg='#185fa5',
cursor='hand2', anchor='w', command=calibrate).pack(
anchor='w', padx=14, pady=(2, 0))
# ---- 预览画布 ----
cv = tk.Canvas(d, bg='#f7f8fa', height=330, highlightthickness=1,
highlightbackground='#e3e7ee')
cv.pack(fill='x', padx=16, pady=(8, 0))
def draw():
cv.delete('all')
try:
cfg = {'width_mm': float(v_w.get()), 'height_mm': float(v_h.get()),
'gap_mm': float(v_gap.get()), 'dpi': int(v_dpi.get())}
except Exception:
lbl_info.configure(text='宽/高/间距请填数字', fg='#a32d2d')
return
p = LB.plan_label(cfg, '分拣标签',
['客户: 张三水果批发店',
'品名: 农夫山泉饮用天然水 550ml×24',
'数量: 1.00 桶', '日期: 11-04 19:02'],
qr_data='CT2026110400001234')
g = p['geom']
cw = max(cv.winfo_width(), 560)
ch = max(cv.winfo_height(), 320)
s = min((cw - 40.0) / g['w'], (ch - 40.0) / g['h'])
ox = (cw - g['w'] * s) / 2
oy = (ch - g['h'] * s) / 2
cv.create_rectangle(ox, oy, ox + g['w'] * s, oy + g['h'] * s,
fill='white', outline='#c9d2de')
for ln in p['lines']:
x0 = ox + ln['x'] * s
y0 = oy + ln['y'] * s
hh = ln['font'] * s
cv.create_rectangle(x0, y0, x0 + ln['w'] * s, y0 + hh * 0.92,
outline='#dfe5ee')
# 字号必须按像素给(负数),不能给磅值:Windows 显示缩放 125%/150%
# 会把磅值放大一大截,预览里的字比实际打出来宽、看着像压住二维码,
# 现场就不敢按了。按像素画,预览和打印 1:1 对应。
cv.create_text(x0 + 1, y0 + hh * 0.5, text=ln['text'],
anchor='w', fill='#17334f',
font=('Microsoft YaHei', -max(6, int(hh))))
if p['qr']:
q = p['qr']
x0 = ox + q['x'] * s
y0 = oy + q['y'] * s
side = q['size'] * s
cv.create_rectangle(x0, y0, x0 + side, y0 + side,
outline='#333333')
step = side / max(q['modules'], 1)
for r in range(0, q['modules'], 2):
for c in range(0, q['modules'], 2):
if (r * 7 + c * 5) % 3:
cv.create_rectangle(
x0 + c * step, y0 + r * step,
x0 + (c + 1) * step, y0 + (r + 1) * step,
fill='#333333', outline='')
cv.create_text(ox + g['w'] * s / 2, oy + g['h'] * s + 12,
text='%g × %g mm · %d dpi · 字号 %d · %d 行'
% (g['width_mm'], g['height_mm'], g['dpi'],
p['font'], len(p['lines'])),
fill='#8a8f98',
font=('Microsoft YaHei', 9))
msg = ' %s' % ' / '.join(p['warnings']) if p['warnings'] else \
'版面正常:文字和二维码都在纸内。'
lbl_info.configure(text=msg,
fg='#a32d2d' if p['warnings'] else '#4b7a3a')
def on_edit(*_a):
d.after(60, draw)
for var in (v_w, v_h, v_gap, v_dpi):
var.trace_add('write', on_edit)
def do_read():
name = str(self._get('printer.printer_name', '') or '')
if not name:
lbl_info.configure(text='还没选打印机,先去「更换…」选一台',
fg='#a32d2d')
return
b_read.configure(text='读取中…', state='disabled')
def work():
r = LB.read_printer_paper(name)
self.root.after(0, lambda: back(r))
threading.Thread(target=work, daemon=True).start()
def back(r):
b_read.configure(text='自动读取尺寸', state='normal')
if not r.get('ok'):
lbl_info.configure(text='读不到:%s(手填也行,可以拿尺子量)'
% (r.get('note') or '驱动没给尺寸'),
fg='#a32d2d')
return
v_w.set('%g' % r['width_mm'])
v_h.set('%g' % r['height_mm'])
v_gap.set('%g' % cur_gap)
v_dpi.set(str(r['dpi']))
note = r.get('note') or '已按驱动里的纸张填好'
lbl_info.configure(text='驱动纸张 %g×%gmm @%ddpi · %s'
% (r['width_mm'], r['height_mm'],
r['dpi'], note),
fg='#4b7a3a')
draw()
# ---- 底部按钮 ----
foot = tk.Frame(d, bg='#ffffff')
foot.pack(side='bottom', fill='x', padx=16, pady=12)
def commit(then=None):
try:
wv = float(v_w.get())
hv = float(v_h.get())
gv = float(v_gap.get())
except Exception:
messagebox.showwarning('检查输入', '宽/高/间距要填数字(单位 mm)',
parent=d)
return False
if not (15 <= wv <= 110 and 15 <= hv <= 300):
messagebox.showwarning('检查输入',
'宽要 15~110mm、高要 15~300mm',
parent=d)
return False
self._set('printer.width_mm', int(round(wv)) if wv == int(wv) else wv)
self._set('printer.height_mm', int(round(hv)) if hv == int(hv) else hv)
self._set('printer.gap_mm', gv)
self._set('printer.dpi', int(v_dpi.get()))
save_config(self.cfg)
# 让正在跑的打印机实例立刻用新尺寸(不用重启)
try:
self.engine.printer.cfg = self.cfg.get('printer', {})
except Exception:
pass
self.log('标签纸已设为 %g×%gmm 间距 %gmm %ddpi'
% (wv, hv, gv, int(v_dpi.get())))
if then:
then()
return True
def save_only():
if commit():
d.destroy()
if on_done:
on_done()
def save_print():
# 先关窗再试打:模态窗的 grab 会挡住试打的结果弹窗
if commit():
d.destroy()
if on_done:
on_done()
self._test_print(parent or self.root)
tk.Button(foot, text='保存并试打', font=FONT_BTN, bd=0, bg='#0a6cf1',
fg='white', height=2, command=save_print).pack(
side='right', fill='x', expand=True, padx=(8, 0))
tk.Button(foot, text='保存', font=FONT_BTN, bd=0, bg='#eef1f5',
fg='#185fa5', height=2, command=save_only).pack(
side='right', fill='x', expand=True, padx=(0, 0))
tk.Button(foot, text='取消', font=FONT_MID, bd=0, bg='#ffffff',
fg='#8a8f98', cursor='hand2', padx=12, command=d.destroy).pack(
side='right', padx=(0, 8))
d.after(120, draw)
# ------------------------------------------------------------ 高级设置
def _settings_advanced(self):
s = tk.Toplevel(self.root)
s.title('高级设置')
sw = s.winfo_screenwidth()
sh = s.winfo_screenheight()
s.geometry('%dx%d+%d+%d' % (min(560, sw - 60), min(720, sh - 80),
max(0, (sw - 560) // 2), 40))
s.minsize(420, 360)
# ---- 底部固定:保存按钮(始终可见,不被滚动区裁掉)----
footer = tk.Frame(s, bg='#ffffff')
footer.pack(side='bottom', fill='x')
# ---- 滚动区:Canvas + 内嵌 Frame + 竖向滚动条 ----
wrap = tk.Frame(s)
wrap.pack(side='top', fill='both', expand=True)
canvas = tk.Canvas(wrap, highlightthickness=0, bd=0)
vbar = tk.Scrollbar(wrap, orient='vertical', command=canvas.yview,
width=22)
canvas.configure(yscrollcommand=vbar.set)
vbar.pack(side='right', fill='y')
canvas.pack(side='left', fill='both', expand=True)
body = tk.Frame(canvas)
win = canvas.create_window((0, 0), window=body, anchor='nw')
def _sync(_e=None):
canvas.configure(scrollregion=canvas.bbox('all'))
canvas.itemconfigure(win, width=canvas.winfo_width())
body.bind('<Configure>', _sync)
canvas.bind('<Configure>', _sync)
rows = []
tk.Label(body, text='这里是最全的参数。改错会连不上秤或摄像头;'
'只是换设备请用上一页的「更换…」,别动这里。',
font=('Microsoft YaHei', 11), bg='#fff8e6', fg='#8a6d3b',
anchor='w', justify='left', wraplength=470).pack(
fill='x', padx=14, pady=(10, 0))
def add(label, path, secret=False, choice=None):
tk.Label(body, text=label, font=FONT_MID).pack(
anchor='w', padx=14, pady=(6, 0))
v = self._get(path, '')
if isinstance(v, bool):
v = 'true' if v else 'false' # 布尔统一小写回显,保存时可还原
else:
v = str(v)
var = tk.StringVar(value=v)
if choice:
om = tk.OptionMenu(body, var, *choice)
om.pack(fill='x', padx=14)
else:
tk.Entry(body, textvariable=var, font=FONT_MID,
relief='solid',
show='*' if secret else '').pack(
fill='x', padx=14, ipady=3)
rows.append((path, var))
add('服务器地址', 'server.base_url')
add('离线模拟(mock,不开真接口)', 'server.mock',
choice=['true', 'false'])
add('账号', 'account.username')
add('密码', 'account.password', secret=True)
add('工位角色', 'account.role', choice=['picker', 'inspector'])
add('秤串口', 'scale.port')
add('秤波特率', 'scale.baudrate')
add('秤校验位', 'scale.parity', choice=['N', 'E', 'O'])
add('秤数据位', 'scale.bytesize')
add('秤停止位', 'scale.stopbits')
add('秤单位(auto 按帧后缀判断)', 'scale.unit',
choice=['auto', 'kg', 'g', 'lb'])
add('秤帧正则(留空=自动抓第一个数)', 'scale.pattern')
add('秤查询命令(应答式秤才填,如 W\\r\\n)', 'scale.poll_cmd')
add('秤查询间隔(ms)', 'scale.poll_ms')
add('秤模拟模式', 'scale.simulate', choice=['true', 'false'])
add('最小起称重量(kg,低于此值按空秤处理,默认 0.05)',
'flow.min_scale_kg')
add('免称重商品单件重量(kg,0=提交 0 重量;分拣服务端强制要重量时才填)',
'noweigh.default_unit_weight_kg')
add('判稳容差(kg,650ms 内波动超过它就算还在动)',
'flow.stable_delta_kg')
add('听秤的稳定位(ST,能省 0.2~0.3 秒/件)',
'flow.use_scale_stable', choice=['true', 'false'])
add('秤去皮命令(留空=软件去皮;现场用「设置→电子秤→去皮/置零…」自动探测)',
'scale.tare_cmd')
add('秤置零命令(留空=软件清零,如 Z\\r\\n 或 hex:1B 5A)', 'scale.zero_cmd')
add('摄像头模拟模式', 'camera.simulate', choice=['true', 'false'])
add('只允许 USB 摄像头', 'camera.usb_only',
choice=['true', 'false'])
add('摄像头序号', 'camera.index')
add('摄像头宽(0=自动,8MP 为 3264)', 'camera.width')
add('摄像头高(0=自动,8MP 为 2448)', 'camera.height')
add('摄像头后端', 'camera.backend', choice=['auto', 'dshow', 'msmf'])
add('画面缩放倍数(1.0~3.0,1=全幅)', 'camera.zoom')
add('记住上次对好的焦距(下次开机从近处起步)',
'camera.focus_memo', choice=['true', 'false'])
add('抓拍前等对焦收敛', 'camera.focus_wait',
choice=['true', 'false'])
add('对焦等待上限(ms,0=不等)', 'camera.focus_wait_ms')
add('锁定焦距(0~255,留空=自动对焦)', 'camera.focus')
add('坏了自动换设备', 'camera.auto_pick',
choice=['true', 'false'])
add('视觉API厂商', 'vision.provider', choice=['qwen', 'glm', 'doubao',
'custom'])
add('视觉API Key', 'vision.api_key', secret=True)
add('打印机名称', 'printer.printer_name')
add('打印前释放USB(只老USB直连打印机才开)',
'printer.release_usb', choice=['true', 'false'])
add('打印指令类型', 'printer.type', choice=['tspl', 'zpl'])
add('标签二维码兜底字段(留空=只认容器码;临时救急可填 pick_code)',
'printer.qr_fallback')
add('标签宽度(mm)', 'printer.width_mm')
add('标签高度(mm)', 'printer.height_mm')
add('标签间距(mm,0=连续纸/无间隙)', 'printer.gap_mm')
add('打印机分辨率(dpi,203 或 300;认不准就用设置页「标签纸…」自动读)',
'printer.dpi', choice=['203', '300', '600'])
add('待办每行列数(0=按屏宽自动;屏大想多看几行就填 5/6)',
'ui.todo_cols')
add('待办卡显示商品缩略图(服务端暂无商品图,开了大多也空着)',
'ui.todo_thumb', choice=['false', 'true'])
cam_before = json.dumps(self.cfg.get('camera', {}), sort_keys=True,
ensure_ascii=False)
scale_before = json.dumps(self.cfg.get('scale', {}), sort_keys=True,
ensure_ascii=False)
tk.Frame(body, height=8).pack() # 底部留白,避免最后一项贴边
# ---- 滚轮 / 触摸拖动 ----
def _wheel(e):
canvas.yview_scroll(int(-1 * (e.delta / 120)) or
(-1 if e.delta > 0 else 1), 'units')
def _press(e):
canvas.scan_mark(e.x, e.y)
def _drag(e):
canvas.scan_dragto(e.x, e.y, gain=1)
s.bind_all('<MouseWheel>', _wheel)
for w in (canvas, body):
w.bind('<ButtonPress-1>', _press)
w.bind('<B1-Motion>', _drag)
# 触摸拖动:标签/空白区可拖,输入框与下拉框保持原交互
for w in body.winfo_children():
if isinstance(w, (tk.Entry, tk.OptionMenu)):
continue
w.bind('<ButtonPress-1>', _press)
w.bind('<B1-Motion>', _drag)
def _on_close():
try:
s.unbind_all('<MouseWheel>')
except Exception:
pass
s.destroy()
s.protocol('WM_DELETE_WINDOW', _on_close)
tk.Button(footer, text='▲ 上一页', font=FONT_MID, bd=0,
bg='#eef1f5', fg='#5b6472', cursor='hand2',
command=lambda: canvas.yview_scroll(-1, 'pages')).pack(
side='left', padx=(14, 6), pady=10)
tk.Button(footer, text='▼ 下一页', font=FONT_MID, bd=0,
bg='#eef1f5', fg='#5b6472', cursor='hand2',
command=lambda: canvas.yview_scroll(1, 'pages')).pack(
side='left', pady=10)
def do_save():
for path, var in rows:
val = var.get()
if val in ('true', 'True'):
self._set(path, True)
elif val in ('false', 'False'):
self._set(path, False)
else:
self._set(path, val)
for path, typ in [('scale.baudrate', int),
('scale.bytesize', int),
('scale.stopbits', float),
('scale.poll_ms', int),
('camera.index', int),
('printer.width_mm', float),
('printer.height_mm', float),
('printer.gap_mm', float),
('printer.dpi', int),
('ui.todo_cols', int)]:
try:
self._set(path, typ(self._get(path)))
except Exception:
# 填了「50mm」这种带单位的,裸转换必失败;静默留着脏值
# 会让打印时 'SIZE %d mm' 抛 TypeError(点了打印没反应)。
# 这里自动去单位重试,仍不行才回落默认值。
raw = str(self._get(path) or '')
num = raw.lower().replace('mm', '').replace('dpi', '').strip()
try:
self._set(path, typ(num))
except Exception:
self._set(path, 0 if path == 'ui.todo_cols' else
(2 if path.endswith('gap_mm') else
(203 if path.endswith('dpi') else 50)))
save_config(self.cfg)
# 列数/排版类配置改完立即重排,不用等下一次刷新待办
try:
if getattr(self, 'btn_cols', None) is not None:
self.btn_cols.configure(text=self._cols_text())
self._layout_cards()
except Exception:
pass
# 摄像头配置有改动 → 立即热切换,无需重启
cam_msg = ''
cam_after = json.dumps(self.cfg.get('camera', {}), sort_keys=True,
ensure_ascii=False)
if cam_after != cam_before:
if self.engine.state == 'IDLE':
try:
self.engine.frames.reconfigure(self.cfg['camera'])
cam_msg = '摄像头配置已立即生效。'
except Exception as e:
cam_msg = '摄像头热切换失败(%s),重启后生效。' % e
else:
cam_msg = ('流程进行中,摄像头配置已保存,'
'请完成当前货物后在「摄像头 → 更换…」重新选择。')
# 秤配置有改动 → 立即热切换
scale_msg = ''
scale_after = json.dumps(self.cfg.get('scale', {}), sort_keys=True,
ensure_ascii=False)
if scale_after != scale_before:
if self.engine.state == 'IDLE':
try:
self.engine.scale.reconfigure(self.cfg['scale'])
scale_msg = '秤配置已立即生效。'
except Exception as e:
scale_msg = '秤热切换失败(%s),重启后生效。' % e
else:
scale_msg = ('流程进行中,秤配置将在重启后生效。')
messagebox.showinfo(
'已保存', '设置已保存。%s%s\n打印机选择即时生效(每次打印'
'按最新配置执行);其余项(服务器/账号)重启程序后生效。'
% (cam_msg, scale_msg), parent=s)
_on_close()
tk.Button(footer, text='保 存', font=FONT_BTN, bd=0, bg='#0a6cf1',
fg='white', height=2, command=do_save).pack(
side='right', fill='x', expand=True, padx=(6, 14), pady=10)
def _get(self, path, default=''):
cur = self.cfg
for p in path.split('.'):
if isinstance(cur, dict) and p in cur:
cur = cur[p]
else:
return default
return cur
def _set(self, path, value):
parts = path.split('.')
cur = self.cfg
for p in parts[:-1]:
cur = cur.setdefault(p, {})
cur[parts[-1]] = value
def log(self, s):
"""界面只留最近一条(运行日志面板已去掉),完整记录追加到 data/app.log
v1.0.52:落盘改成后台线程(`_log_writer`)。原来在界面线程里
open+write+close,现场机器(i5-4200U + 杀软实时扫描)一次 3~10ms,
一轮流程十几条日志就是上百毫秒,全卡在 _poll 里 —— 那不是 Python
慢,是把磁盘 IO 放在了画界面的线程上。
"""
ts = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
line = '[%s] %s' % (ts, s)
try:
self._logq.put_nowait(line)
except Exception:
pass
try:
txt = str(s)
if not txt.startswith('[dev] '):
self.lbl_last.configure(
text=self._fit_text('最近:' + txt, self._px(536)))
except Exception:
pass
def _log_writer(self):
"""后台落盘:攒一小批再一次写,减少 open/close 次数"""
buf = []
while not getattr(self, '_log_stop', False):
try:
buf.append(self._logq.get(timeout=0.5))
except queue.Empty:
pass
# 取空队列里已经排着的,一次写完
while len(buf) < 200:
try:
buf.append(self._logq.get_nowait())
except queue.Empty:
break
if not buf:
continue
path = getattr(self, '_log_path', None) or os.path.join(
'data', 'app.log')
try:
d = os.path.dirname(path)
if d:
os.makedirs(d, exist_ok=True)
with open(path, 'a', encoding='utf-8') as f:
f.write('\n'.join(buf) + '\n')
except Exception:
pass
buf = []
def flush_log(self):
"""退出前把日志写干净:先让后台线程收尾,剩下没写的自己补上"""
self._log_stop = True
time.sleep(0.15) # 后台线程正手里那批写盘
rest = []
while len(rest) < 500:
try:
rest.append(self._logq.get_nowait())
except queue.Empty:
break
if not rest:
return
try:
path = getattr(self, '_log_path', None) or os.path.join(
'data', 'app.log')
with open(path, 'a', encoding='utf-8') as f:
f.write('\n'.join(rest) + '\n')
except Exception:
pass
def run():
# 高分屏/触摸屏:声明 DPI 感知,避免 Windows 把界面拉伸放大(字发虚)
try:
import ctypes
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2) # 每显示器感知
except Exception:
ctypes.windll.user32.SetProcessDPIAware()
except Exception:
pass
root = tk.Tk()
App(root)
root.mainloop()