Reputation: 43
So I have a few entry fields where users are required to input the figures they require.
I have created a validation rule to prevent people from entering anything other than digits, and I inserted a default value of 0 just for the sake of the calculation.
The issue is that now the fields wont allow the figures in it to be cleared before entering any further digits, for example if the fields has a '0' in it, you would have to type 0123 and then delete the 0 to get 123, and if you wanted to change 123 you could only delete the 2 and the 3, you would have to type it and then delete the initial figure again.
Anyone know why this is happening?
vcmd = (root.register(self.validate),
'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
def validate(self, action, index, value_if_allowed,
prior_value, text, validation_type, trigger_type, widget_name):
if text in '0123456789.-+*':
try:
float(value_if_allowed)
return True
except ValueError:
return False
else:
return False
I look forward to your responses, I will regularly refresh this page for the next 6 hours until I come to a conclusion!
Lewis
Upvotes: 0
Views: 364
Reputation: 385880
It is happening because ""
isn't a valid float in python.
The solution is simple: if you want to allow an empty string, test for an empty string, and return True if the string is empty:
def validate(...):
if (value_if_allowed == ""):
return True
...
Upvotes: 3
Reputation: 1759
The problem is that you can't convert a empty string to a float.
If you want to empty the entry, your value_if_allowed
refers to ""
. This passes the if
comparison but fails in the try
clause.
You can add a simple test like this inside the existing if
clause:
if not value_if_allowed:
return True
By the way, it does not make sense to allow ".-+*"
as strings, as they would fail the convertation to float, too.
Upvotes: 3