PurpleHaze
PurpleHaze

Reputation: 21

Python tkinter validate issue

I have the following code snippet.

def validateEntries():
    x1 = entry1.get()
    if len(int(x1)) > 5:
        return False
    
entry1 = Entry(window, validate='all', validatecommand=validateEntries)

Any ideas why the condition does not work?

The following error does occur:

invalid literal for int() with base 10:

Upvotes: 1

Views: 57

Answers (1)

Henry
Henry

Reputation: 3944

At the moment, you are validating anything that happens to the Entry widget, including clicking on it. Therefore when you click on the Entry it calls validateEntries. The value of the empty Entry is "". This can't be converted to a number, so you get an error. Instead, use validate commands like this:

def validateEntries(x1, action):
    if action == "1": #Insertion
        try:
            int(x1) # Attempt to convert to an integer
        except:
            return False # If that fails, return False
        else:
            print(int(x1))
            if int(x1) <= 5: # If it succeeds, try validation like before
                return True
    else:
        return True # Allow backspace
    return False # If no other value is returned, return False
    

window = Tk()
vcmd = (window.register(validateEntries), "%P", "%d")
entry1 = Entry(window, validate='key', validatecommand=vcmd)

A lot of this code is based off of this answer which explains validate commands very well. I've changed it so the validate command is only called on key press and created a command which takes the value of the entry is the edit is allowed and the action (insert/delete) and passed it to validateEntries. This is explained better in the linked answer.
The validation itself has changed. Your validation didn't work if the contents of the Entry were not an integer. Now it uses a try/except statement to check if it is an integer, then checks it's value. It also checks the action and only validates on insertion, so using backspace does not get blocked. Now the validation works as expected.

Upvotes: 1

Related Questions