我不确定您是否应该这样做,但是您可以附加一个invalidcommand
处理程序,该处理程序将对条目进行操作,就好像一切都很好。
示例脚本:
import Tkinter as tk
def onvalidate(d,i,P,s,S,v,V,W):
# only lowercase is valid
valid = (P.lower() == P)
# set red background if invalid
newcolor = 'red' if not valid else default_color
root.nametowidget(W).configure(background=newcolor)
return valid
def oninvalid(d,i,P,s,S,v,V,W):
#called if widget is invalid
widget = root.nametowidget(W)
# S is the character that *would* have been
# inserted or deleted, but won't because it is invalid
# So we do it ourselves
if S:
if d=='0':
widget.delete(i, len(S))
elif d=='1':
widget.insert(i, S)
# Changing the text clears the 'validate' value
# so we have to reset it
widget.after_idle(lambda W,v: root.nametowidget(W).configure(validate=v), W, v)
root = tk.Tk()
valhook = (root.register(onvalidate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
invhook = (root.register(oninvalid), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
entry = tk.Entry(root, validate="key", validatecommand=valhook, invalidcommand=invhook)
default_color = entry.cget('background')
entry.pack()
root.mainloop()
这将创建一个条目,如果无效则具有红色背景,否则将具有白色背景,但即使条目无效,文本仍将被插入或删除。