<p>每当更新<code>inputid</code>时,可以使用<code>after()</code>来安排超时任务。您需要在条形码扫描仪每次更新<code>inputid</code>之间选择足够长的超时时间。如果<code>inputid</code>在计划的超时之前再次更新,则需要取消上一个超时任务并重新计划另一个超时任务</p>
<p>如果超时任务被触发,您可以在超时回调中执行人脸识别,但建议使用线程来执行,因为这可能是一项耗时的任务,将阻塞<code>tkinter</code>主循环</p>
<p>以下是一个例子:</p>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
import random
import threading
import time
def compareimage(id):
face.config(text='Checking ...', image=tk.PhotoImage())
face.update_idletasks()
# simulate the face recognition task
time.sleep(5)
# show the result image
face.image = tk.PhotoImage(file='result.png')
face.config(text=id, image=face.image)
ids.set('')
def text_completed(ids):
print('timed out')
id = ids.get()
if len(id) > 8:
print('id:', id)
threading.Thread(target=compareimage, args=(id,), daemon=True).start()
def text_changed(ids):
global timeout_id
if timeout_id:
# cancel previous scheduled task
root.after_cancel(timeout_id)
if len(ids.get()) > 0:
# schedule a timeout task, adjust the delay to suit your real situation
timeout_id = root.after(1000, text_completed, ids)
# simulate barcode reader input
def scan_id(n=10):
if n > 0:
inputid.insert('end', random.choice('1234567890'))
inputid.after(50, scan_id, n-1)
timeout_id = None
root = tk.Tk()
tk.Label(root, text='Employee Attandance', font='Helvetica 32 bold').pack()
ids = tk.StringVar(value='')
ids.trace('w', lambda *args: text_changed(ids))
inputid = tk.Entry(root, font='Helvetica 20 bold', textvariable=ids, width=12)
inputid.pack()
face = tk.Label(root, text='', image=tk.PhotoImage(), compound='top', width=600, height=400)
face.pack()
tk.Button(root, text='Scan ID', command=lambda: scan_id(random.randrange(9,11))).pack()
root.mainloop()
</code></pre>
<p>请注意,按钮<code>Scan ID</code>用于模拟条形码阅读器</p>