Files
Ubuntu 4966345424 feat(1.0.75): 同步秤端 v1.0.75 源码(UI 抖动修复 + 严格入库/分拣样本)
来自 入库分拣工作站_源代码_v1.0.75:点商品名抖动的中间帧修复、ui/osk/tablet 调整、严格入库校验、分拣场景样本(review_queue station=picking);版本/安装包/说明同步 1.0.75。注意:本版 confirm_before_submit 恒 True、submit_on_remove 恒 False,1.0.71 的 inbound_auto_submit 账号开关被移除;models/cls 与 data/ 未入库。EXE 由用户侧打包分发,本次只推源码。
2026-12-03 16:26:17 +08:00

654 lines
24 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 -*-
"""内置触摸软键盘(不依赖 Windows 触摸键盘服务)。
同一套键盘两个视图,顶栏一键来回切:
· ABC 英文 + 数字(账号 / 密码 / 参数)
· 手写 中文手写(搜索框),写完自动识别;旁边照样有退格、清空
现场问题:工控机上 `TabTip.exe` 进程常驻,但窗口永远不显示
(`ITipInvocation.Toggle` 和 `ShowWindow` 都唤不起来),`osk.exe` 从普通
权限进程启动会直接 WinError 740;本机也没有 Tablet PC 的手写 COM。
所以自绘:点了一定出现,按键直接写进目标输入框,手写自己采笔画交给视觉
模型读字(见 core/handwrite.py)。
每个输入框可以带 `_kb_mode`('abc' / 'hand'),点进去就按它的默认视图弹出。
"""
import queue
import threading
import tkinter as tk
# 每行键位:数字行覆盖账号/密码/称重场景,字母区带常用符号
ROW_NUM = list('1234567890-=')
ROW_Q = list('qwertyuiop')
ROW_A = list('asdfghjkl')
ROW_Z = list('zxcvbnm') + ['.', '_', '@']
BG = '#dbe3ee'
KEY_BG = '#ffffff'
KEY_FG = '#17334f'
FN_BG = '#e8eef7'
OK_BG = '#185fa5'
INK = '#17334f'
H_ABC = 322 # 键盘高度(逻辑值,实际按缩放算)
H_HAND = 352
class SoftKeyboard:
"""贴在主窗口底部的屏幕键盘(单例,由 App 持有)。"""
def __init__(self, parent, app, scale=1.0):
self.parent = parent
self.app = app
self.S = max(0.7, min(2.0, scale or 1.0))
self.target = None # 当前写入目标(Entry / Text)
self.shift = False
self.mode = 'abc'
self._built = False
# 手写状态
self._strokes = []
self._cur = None
self._recognizing = False
self._hand_job = None
self._candidates = []
self._finish_after_recog = False
self._hand_q = queue.Queue()
self.win = tk.Toplevel(parent)
self.win.withdraw()
self.win.overrideredirect(True)
self.win.configure(bg=BG)
try:
self.win.attributes('-topmost', True)
except Exception:
pass
self._build()
self.win.bind('<Escape>', lambda e: self.hide())
# ---------------------------------------------------------------- 构建
def _px(self, n):
return max(1, int(round(n * self.S)))
def _fs(self, size, bold=True):
return ('Microsoft YaHei', max(11, int(round(size * self.S))),
'bold' if bold else 'normal')
def _key(self, row, text, cmd, bg=KEY_BG, fg=KEY_FG, size=15):
b = tk.Button(row, text=text, command=cmd, bd=0, bg=bg, fg=fg,
activebackground='#cfe0f5', activeforeground=fg,
font=self._fs(size), cursor='hand2', takefocus=0)
b.pack(side='left', fill='both', expand=True, padx=2, pady=2)
return b
def _line(self, parent, h):
f = tk.Frame(parent, bg=BG, height=int(h * self.S))
f.pack(fill='x')
f.pack_propagate(False)
return f
def _build(self):
px = self._px
# ---- 顶部条:说明 + 模式切换 + 收起 ----
bar = tk.Frame(self.win, bg='#c9d6e6', height=px(40))
bar.pack(fill='x')
bar.pack_propagate(False)
self.lbl_tip = tk.Label(bar, text='屏幕键盘', font=self._fs(11),
bg='#c9d6e6', fg='#41505f', anchor='w')
self.lbl_tip.pack(side='left', padx=px(12))
tk.Button(bar, text='收起 ⌄', font=self._fs(11), bd=0, bg='#c9d6e6',
fg='#41505f', activebackground='#b8c8dd', cursor='hand2',
takefocus=0, command=self.hide).pack(side='right',
padx=px(6))
# 同一套键盘的两个视图,随时切,不会把键盘弄丢
self.btn_mode = tk.Button(bar, text='✍ 手写', font=self._fs(11),
bd=0, bg='#dbe7f6', fg='#185fa5',
activebackground='#c8daf0', cursor='hand2',
takefocus=0, padx=px(10),
command=self._toggle_mode)
self.btn_mode.pack(side='right', padx=px(4))
# 登录页专用:打完密码不用收键盘,直接点这里登录
self.btn_go = tk.Button(bar, text='登 录 →', font=self._fs(11),
bd=0, bg='#0f6e56', fg='white',
activebackground='#0b5544',
activeforeground='white', cursor='hand2',
takefocus=0, padx=px(12),
command=self._go_login)
self.body = tk.Frame(self.win, bg=BG)
self.body.pack(fill='both', expand=True)
self.view_abc = tk.Frame(self.body, bg=BG)
self.view_hand = tk.Frame(self.body, bg=BG)
self._build_abc(self.view_abc)
self._build_hand(self.view_hand)
self.view_abc.pack(fill='both', expand=True)
self._built = True
self._refresh_case()
def _build_abc(self, parent):
r = self._line(parent, 54)
for ch in ROW_NUM:
self._key(r, ch, lambda c=ch: self._tap(c))
r = self._line(parent, 54)
for ch in ROW_Q:
self._key(r, ch, lambda c=ch: self._tap(c))
r = self._line(parent, 54)
for ch in ROW_A:
self._key(r, ch, lambda c=ch: self._tap(c))
r = self._line(parent, 54)
self.btn_shift = self._key(r, '⇧', self._toggle_shift, bg=FN_BG)
for ch in ROW_Z:
self._key(r, ch, lambda c=ch: self._tap(c))
r = self._line(parent, 54)
self._key(r, '空格', lambda: self._tap(' '), bg=FN_BG, size=13)
self._key(r, '⌫ 退格', self._backspace, bg=FN_BG, size=13)
self._key(r, '清空', self._clear, bg=FN_BG, size=13)
self._key(r, '下一个', self._next_field, bg=FN_BG, size=13)
self._key(r, '完成 ✓', self.hide, bg=OK_BG, fg='white', size=14)
def _build_hand(self, parent):
px = self._px
# 底部功能行(手写时退格/清空照样能用)
bar = tk.Frame(parent, bg=BG)
bar.pack(side='bottom', fill='x', padx=px(6), pady=(0, px(4)))
self._key(bar, '⌫ 退格', self._backspace, bg=FN_BG, size=13)
self._key(bar, '清空重写', self._hand_clear, bg=FN_BG, size=13)
self._key(bar, '重新识别', lambda: self._hand_recognize(force=True),
bg=FN_BG, size=13)
self._key(bar, '完成 ✓', self._hand_finish, bg=OK_BG, fg='white',
size=14)
wrap = tk.Frame(parent, bg=BG)
wrap.pack(fill='both', expand=True, padx=px(6), pady=(px(2), 0))
# 右侧:识别候选
side = tk.Frame(wrap, bg='#eef3fa', width=px(248))
side.pack(side='right', fill='y', padx=(px(8), px(2)))
side.pack_propagate(False)
tk.Label(side, text='识别结果 · 点一下填入', font=self._fs(10),
bg='#eef3fa', fg='#41505f', anchor='w').pack(
anchor='w', padx=px(10), pady=(px(6), px(2)))
self.cand_box = tk.Frame(side, bg='#eef3fa')
self.cand_box.pack(fill='both', expand=True, padx=px(6))
self.cand_tip = tk.Label(side, text='写完停一下自动识别',
font=self._fs(9, False), bg='#eef3fa',
fg='#8a94a3', anchor='w', justify='left',
wraplength=px(222))
self.cand_tip.pack(side='bottom', fill='x', padx=px(10), pady=px(4))
# 左侧:手写板
left = tk.Frame(wrap, bg=BG)
left.pack(side='left', fill='both', expand=True)
self.cv = tk.Canvas(left, bg='#ffffff', highlightthickness=2,
highlightbackground='#b9c7d8', cursor='pencil')
self.cv.pack(fill='both', expand=True, padx=px(2), pady=px(2))
self.cv.bind('<ButtonPress-1>', self._pen_down)
self.cv.bind('<B1-Motion>', self._pen_move)
self.cv.bind('<ButtonRelease-1>', self._pen_up)
self.cv.bind('<Configure>', self._hand_bg)
# ---------------------------------------------------------------- 视图
def set_mode(self, mode):
mode = 'hand' if str(mode or '').lower().startswith('hand') else 'abc'
self.mode = mode
try:
if mode == 'hand':
self.view_abc.pack_forget()
self.view_hand.pack(fill='both', expand=True)
self.btn_mode.configure(text='⌨ ABC 键盘')
else:
self.view_hand.pack_forget()
self.view_abc.pack(fill='both', expand=True)
self.btn_mode.configure(text='✍ 手写')
self._place()
self._update_tip()
except Exception:
pass
def _toggle_mode(self):
self.set_mode('abc' if self.mode == 'hand' else 'hand')
# ---------------------------------------------------------------- 显示
def alive(self):
try:
return bool(self.win.winfo_exists())
except Exception:
return False
def show(self, target=None, mode=None):
if target is not None:
self.target = target
if self.target is None:
self.target = self.app._current_input()
if mode is None:
mode = getattr(self.target, '_kb_mode', 'abc') \
if self.target is not None else 'abc'
self.set_mode(mode)
self._detach_grab()
try:
self.win.deiconify()
self.win.lift()
self.win.attributes('-topmost', True)
except Exception:
pass
self._refresh_case()
# 登录页才显示"登录"快捷键(主界面没有这个动作)
try:
if (not getattr(self.app, 'ready', True)) \
and getattr(self.app, 'ent_pwd', None) is not None:
self.btn_go.pack(side='right', padx=self._px(6))
else:
self.btn_go.pack_forget()
except Exception:
pass
self._update_tip()
def _detach_grab(self):
"""对话框开了 grab_set 时,键盘点不动(事件全被模态窗口吞掉)。
打开键盘前把 grab 摘下来,收起时再还回去——对话框是程序自己的,
让出这一小会儿没有副作用。
"""
try:
g = self.win.grab_current()
if g is not None and g is not self.win:
self._prev_grab = g
g.grab_release()
except Exception:
pass
def _restore_grab(self):
g = getattr(self, '_prev_grab', None)
self._prev_grab = None
try:
if g is not None and g.winfo_exists():
g.grab_set()
except Exception:
pass
def is_visible(self):
try:
return bool(self.win.winfo_exists() and self.win.winfo_viewable())
except Exception:
return False
def hide(self):
self._cancel_hand_job()
self._finish_after_recog = False
try:
self.win.withdraw()
except Exception:
pass
self._restore_grab()
# 收起后把焦点还给输入框,方便外接键盘继续输入
try:
if self.target is not None and self.target.winfo_exists():
self.target.focus_set()
except Exception:
pass
def _update_tip(self):
name = ''
try:
if self.target is not None:
name = getattr(self.target, '_field_label', '') or ''
except Exception:
name = ''
base = '手写键盘' if self.mode == 'hand' else '屏幕键盘'
if name:
base += ' · 输入到「%s」' % name
try:
self.lbl_tip.configure(text=base, fg='#41505f')
except Exception:
pass
def _place(self):
p = self.parent
try:
pw, ph = p.winfo_width(), p.winfo_height()
rx, ry = p.winfo_rootx(), p.winfo_rooty()
if pw < 200 or ph < 200: # 还没完成布局
pw, ph = p.winfo_screenwidth(), p.winfo_screenheight()
rx = ry = 0
except Exception:
pw, ph, rx, ry = 1440, 900, 0, 0
w = max(760, min(pw - 16, int(1240 * self.S)))
h = int((H_HAND if self.mode == 'hand' else H_ABC) * self.S)
x = rx + (pw - w) // 2
y = ry + ph - h - 6
# 别压住正在输入的那个框:默认贴窗口底,压住就挪到框下面/上面
try:
t = self.target
if t is not None and t.winfo_exists():
t_top = t.winfo_rooty()
t_bot = t_top + t.winfo_height()
sh = self.win.winfo_screenheight()
if t_bot + 4 > y and t_top < y + h:
below, above = t_bot + 8, t_top - h - 8
if below + h <= sh - 8:
y = below
elif above >= 0:
y = above
except Exception:
pass
self.win.geometry('%dx%d+%d+%d' % (w, h, x, max(0, y)))
# ---------------------------------------------------------------- 输入
def _t(self):
t = self.target
try:
ok = t is not None and t.winfo_exists()
except Exception:
ok = False
if not ok:
# 没指定目标时跟着"最后点过的输入框"走,先点框再按键也能输入
t = self.app._current_input()
self.target = t
return t
def _is_text(self, w):
try:
return w.winfo_class() == 'Text'
except Exception:
return False
def _prepare_target(self, t):
"""写入/删字前若目标框正挂着灰色占位提示,先清掉占位,避免字插到占位前面。"""
try:
if (t is getattr(self.app, 'ent_search', None)
and getattr(self.app, '_search_ph_on', False)):
self.app._search_focus_in()
except Exception:
pass
def _tap(self, ch):
t = self._t()
if t is None:
return
self._prepare_target(t)
c = ch.upper() if self.shift and ch.isalpha() else ch
try:
if not self._is_text(t):
# Entry:有选中就先替换掉
try:
if t.selection_present():
t.delete('sel.first', 'sel.last')
except Exception:
pass
t.insert('insert', c)
except Exception:
return
if self.shift:
self.shift = False
self._refresh_case()
def _backspace(self):
t = self._t()
if t is None:
return
self._prepare_target(t)
try:
if not self._is_text(t):
if t.selection_present():
t.delete('sel.first', 'sel.last')
return
i = t.index('insert')
if i > 0:
t.delete(i - 1, i)
else:
t.delete('insert-1c', 'insert')
except Exception:
pass
def _clear(self):
t = self._t()
if t is None:
return
self._prepare_target(t)
try:
if self._is_text(t):
t.delete('1.0', 'end')
else:
t.delete(0, 'end')
except Exception:
pass
def _next_field(self):
t = self._t()
if t is None:
return
try:
nxt = t.tk_focusNext()
if nxt is not None and nxt.winfo_class() in ('Entry', 'TEntry',
'Text'):
self.target = nxt
nxt.focus_set()
self.show(nxt)
except Exception:
pass
def _toggle_shift(self):
self.shift = not self.shift
self._refresh_case()
def _refresh_case(self):
try:
self.btn_shift.configure(
bg='#185fa5' if self.shift else FN_BG,
fg='white' if self.shift else KEY_FG)
except Exception:
pass
# 字母键大小写跟着变,触摸屏看得见当前状态
try:
for row in self.view_abc.winfo_children():
for b in row.winfo_children():
txt = b.cget('text')
if len(txt) == 1 and txt.isalpha():
b.configure(text=txt.upper() if self.shift
else txt.lower())
except Exception:
pass
def _go_login(self):
"""登录页:收起键盘并直接提交登录。"""
self.hide()
try:
self.app._do_login()
except Exception:
pass
# ---------------------------------------------------------------- 手写
def _hand_hints(self):
"""把当前待办的商品名当提示词,手写命中率能高不少。"""
try:
rows = getattr(self.app, '_all_rows', None) or []
names = []
for r in rows[:80]:
n = str(r.get('item_name') or '').strip()
if n and n not in names:
names.append(n)
return names[:40]
except Exception:
return None
def _hand_bg(self, e=None):
try:
w = e.width if e is not None else self.cv.winfo_width()
h = e.height if e is not None else self.cv.winfo_height()
except Exception:
return
try:
self.cv.delete('bg')
self.cv.create_line(w / 2, 10, w / 2, h - 10, fill='#eef2f7',
width=2, tags='bg')
if not self._strokes:
self.cv.create_text(w / 2, h / 2, text='在这里手写中文',
fill='#c3ccd8', font=self._fs(16),
tags='bg')
self.cv.tag_lower('bg')
except Exception:
pass
def _pen_down(self, e):
self._cancel_hand_job()
self._finish_after_recog = False
self._candidates = []
self._cur = [(e.x, e.y)]
self._strokes.append(self._cur)
try:
self.cv.delete('bg')
r = max(2, self._px(3))
self.cv.create_oval(e.x - r, e.y - r, e.x + r, e.y + r,
fill=INK, outline=INK, tags='ink')
except Exception:
pass
self._set_cand_tip('写字中…')
def _pen_move(self, e):
if not self._cur:
return
x0, y0 = self._cur[-1]
self._cur.append((e.x, e.y))
try:
self.cv.create_line(x0, y0, e.x, e.y, fill=INK,
width=max(3, self._px(4)),
capstyle='round', tags='ink')
except Exception:
pass
def _pen_up(self, e):
self._cur = None
if self._strokes:
self._cancel_hand_job()
self._hand_job = self.win.after(900, self._hand_recognize)
def _cancel_hand_job(self):
if self._hand_job is not None:
try:
self.win.after_cancel(self._hand_job)
except Exception:
pass
self._hand_job = None
def _set_cand_tip(self, text, color='#8a94a3'):
try:
self.cand_tip.configure(text=text, fg=color)
except Exception:
pass
def _hand_recognize(self, force=False):
self._hand_job = None
if self._recognizing or not self._strokes:
return
self._recognizing = True
self._set_cand_tip('识别中…', '#185fa5')
# 笔画拷一份给线程,避免用户此时继续写导致数据打架
strokes = [[tuple(p) for p in s] for s in self._strokes]
size = (self.cv.winfo_width(), self.cv.winfo_height())
hints = self._hand_hints()
cfg = getattr(self.app, 'cfg', {}) or {}
def work():
try:
import core.handwrite as hw
res = hw.recognize(strokes, size, cfg, hints=hints)
self._hand_q.put(('ok', res))
except Exception as ex: # noqa: BLE001
self._hand_q.put(('err', str(ex)))
threading.Thread(target=work, daemon=True).start()
self._poll_hand()
def _poll_hand(self):
"""识别结果只能在主线程碰界面:后台线程写队列,这里 poll。"""
try:
kind, data = self._hand_q.get_nowait()
except queue.Empty:
try:
self.win.after(120, self._poll_hand)
except Exception:
pass
return
self._recognizing = False
finish = self._finish_after_recog
self._finish_after_recog = False
if kind == 'err':
self._set_cand_tip('识别失败:%s\n可点「重新识别」,或切 ABC 键盘'
% str(data)[:60], '#a32d2d')
return
items = [x for x in (data or []) if x]
if not items:
self._set_cand_tip('没认出来,擦掉重写一次', '#a32d2d')
return
self._show_candidates(items)
if finish:
self._pick(items[0])
self.hide()
def _show_candidates(self, items):
self._candidates = list(items or [])
try:
for w in self.cand_box.winfo_children():
w.destroy()
for it in self._candidates:
b = tk.Button(self.cand_box, text=it, font=self._fs(15),
bd=0, bg='#ffffff', fg='#17334f',
activebackground='#cfe0f5', cursor='hand2',
takefocus=0,
command=lambda s=it: self._pick(s))
b.pack(fill='x', pady=self._px(3), ipady=self._px(5))
except Exception:
return
self._set_cand_tip('点一下或点「完成」填进输入框')
def _hand_finish(self):
"""手写视图点「完成 ✓」:若有未提交的识别结果则自动填入首候选,再收起。"""
if self._candidates:
self._pick(self._candidates[0])
self.hide()
return
if self._strokes:
self._finish_after_recog = True
self._cancel_hand_job()
if not self._recognizing:
self._hand_recognize(force=True)
return
self.hide()
def _pick(self, text):
t = self._t()
if t is None:
self._set_cand_tip('没有输入框可写,先点一下输入框', '#a32d2d')
return
self._prepare_target(t)
try:
if not self._is_text(t):
try:
if t.selection_present():
t.delete('sel.first', 'sel.last')
except Exception:
pass
t.insert('insert', text)
except Exception:
return
self._hand_clear()
self._set_cand_tip('已填入「%s」,接着写或收起键盘' % text, '#0f6e56')
def _hand_clear(self):
self._cancel_hand_job()
self._finish_after_recog = False
self._strokes = []
self._cur = None
self._candidates = []
try:
self.cv.delete('ink')
except Exception:
pass
try:
for w in self.cand_box.winfo_children():
w.destroy()
except Exception:
pass
self._set_cand_tip('写完停一下自动识别')
self._hand_bg()