Python tkinter validate issue Python tkinter validate issue tkinter tkinter

Python tkinter validate issue


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.