我不明白为什么消息框(或 simpledialog)会破坏以下代码的流程。该代码基本上验证了 python 3.5 中的输入框。它检查该字段是否仅包含数值并且它的长度不超过 9 位,但输入框可以为空。向用户添加一条消息,在他们确定之后,允许输入框超过 9 位并接受字母,这当然我不希望它这样做。
from tkinter import *
from tkinter import simpledialog
from tkinter import messagebox
root = Tk()
root.title("Zebra")
root.update_idletasks()
root.geometry("350x200+600+300")
root.config(bg="blue")
def okay(old,new): #,c,d,e,f,g,h):
try:
x = int(new)
except ValueError as ex:
if len(new) == 0:
return True
else:
return False
else:
if len(new) > 9:
messagebox.showerror("Error","Entry is too long")
# When messagebox is removed or commented out all is working ok
# but add below line and BINGO it works again :-)
txtNorm.config(validate='all', vcmd=vcmd)
# New line above as of 08/03/2016 brings validation back.
return False
elif len(new) <=9:
return True
finally:
if len(new) > 9:
return False
pass
def txtNormToggle(event): # When the user double clicks the field to enter or correct a number.
txtNorm.config(state="normal")
def txtNormFinished(a):
txtNorm.config(state="disabled")
root.focus()
vcmd=(root.register(okay),'%s','%P')
txtNorm = Entry(root)
txtNorm.grid(row=1, column=1,padx=(15,15),pady=(15,15), sticky=E+W)
txtNorm.insert(0,"123")
txtNorm.config(state="disabled", justify="center", validate='all', vcmd=vcmd)
txtNorm.bind('<Button>',txtNormToggle)
txtNorm.bind('<Control-z>',txtNormFinished)
txtNorm.bind('<Escape>',txtNormFinished)
txtNorm.bind('<Return>',txtNormFinished)
root.mainloop()
上面没有消息框的内容会阻止用户输入除我想要的数字以外的任何内容,一旦单击确定,使用消息框输入字段允许超过 9 个数字和其他字符
编辑:好的,所以我创建了自己的弹出子窗口并且验证仍然出现在窗口之外,怀疑这与主窗口失去焦点有关,从输入框中杀死验证。请有任何想法。