我不明白为什么messagebox(或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()
上面没有消息框会阻止用户输入除了数字之外的任何内容,我想要的是,一旦点击OK就会输入消息框,输入字段允许超过9位和其他字符
编辑:确定所以我创建了自己的弹出子窗口并且验证仍然在窗口外,怀疑它是从主窗口失去焦点而导致从输入框中删除验证。请任何想法。
答案 0 :(得分:0)
我已将验证添加回(okay)函数中的输入框,它不会向我解释为什么会发生验证丢失。代码现在可以运行我想要的方式