Wednesday, 11 September 2013

ttk Entry widget - validate entry - invalid text entry does not cause reverting to previous text

ttk Entry widget - validate entry - invalid text entry does not cause
reverting to previous text

Python 3.1
I'm trying to validate that the string input to a ttk.Entry widget can be
turned into a float. The simple code below shows that the validate
function is successful in its task, and is returning true/false correctly.
I understood it to be the case that if the Entry widget gets 'false' back
from its validatecommand, it should revert to whatever was stored in the
textvariable before the attempted entry happened.
But that's not happening - the new entry appears, even though it's invalid.
Presumably I am missing something foolish...
from tkinter import *
from tkinter.ttk import *
root = Tk()
text = StringVar()
text.set('100.0')
def validate(inp):
print(inp)
if inp in '0123456789.-+':
try:
float(inp)
print('float')
return True
except ValueError:
print('notfloat')
return False
else:
print('notfloat')
return False
vcmd = root.register(validate)
a = Entry(textvariable = text,
validate = 'focusout',
validatecommand = (vcmd,'%P'))
a.pack()
b = Entry()
b.pack()
root.mainloop()

No comments:

Post a Comment