Reputation: 1287
First of all, sorry for not using OOP, I just decided to avoid complexity for such a small program. So here's my program (basically, it's an Entry widget that allows a text that only consists of integers whose maximum length is 5):
from tkinter import *
root = Tk()
root.title("Entry Validation")
root.geometry("300x100")
def validation_function(text):
if len(text) <= 5:
try:
text = int(text)
return True
except:
return False
else:
return False
vcmd = root.register(validation_function)
entry = Entry(root, validate='key', validatecommand=(vcmd, "%P"))
entry.pack()
It works normal. But when I make a little change in the body of the validation function, it doesn't work:
def validation_function(text):
try:
text = int(text)
if len(text) <= 5:
return True
else:
return False
except:
return False
I feel the problem is here:
except:
return False
Probably the max length part doesn't go well with try-except... However:
def validation_function(text):
try:
if len(text) <= 5:
return True
else:
return False
except:
return False
works correctly. But there is only the max length part, I also want it to allow only integers. I've done it in the first example, but my question is: why doesn't it work when I change the places of the max length part with the only integers part?
Upvotes: 0
Views: 52
Reputation: 113940
text
is an int
... you cannot call len(int)
... it will raise an exception
try this
def validation_function(text):
try:
int(text)
except:
return False
if len(text) <= 5:
return True
return False
Upvotes: 3