Tkinter Entry组件validatecommand事件仅触发一次 如何重置实现重复校验
问题原因
Tkinter的Entry校验机制要求validatecommand绑定的回调函数必须返回布尔值:
- 回调返回
True时,当前输入生效,校验机制保持启用 - 回调返回
False时,当前输入被拦截(输入类校验场景),校验机制保持启用 - 回调没有显式返回值(默认返回None)或返回非布尔值时,Tkinter会自动将Entry的
validate属性置为NONE,直接禁用后续所有校验触发,这是校验仅执行一次的核心原因。
解决方案
1. 调整回调函数,必须显式返回布尔值
你当前的isOkay函数仅执行了数据库查询逻辑,没有设置返回值,补加返回语句即可:
def isOkay(root, why, where, barcode, name): if (barcode != ''): lookupFromBarcodeSql = "select Manufacturer, Brand, Model, Submodel, Size from Drives where Submodel = %s and Manufacturer = 'Seagate' and Brand != '' and Brand is not null and Model != '' and Model is not null and Submodel != '';" lookupFromBarcodeParams = (barcode.strip(),) myCursor.execute(lookupFromBarcodeSql, lookupFromBarcodeParams) lookupResults = myCursor.fetchall() for result in lookupResults: print(result[0] + " " + result[1] + " " + result[2] + " " + result[4]) # 必须显式返回布尔值,不需要拦截用户输入直接返回True即可 return True
2. 手动重置校验的方法
如果后续业务场景需要手动重置已禁用的校验,直接重新配置Entry的validate属性即可:
# 按需在需要重置校验的位置执行该行代码 lidBarCode.config(validate="focusout")
内容的提问来源于stack exchange,提问作者Tristan
相关产品推荐
相关产品推荐

