tkinter The Tkinter Entry Widget Adding validation to an Entry widget


To restrict the characters that can be typed into an entry widget, only numbers for instance, a validate command can be added to the entry. A validate command is a function that return True if the change is accepted, False otherwise. This function will be called each time the content of the entry is modified. Various arguments can be passed to this function, like the type of change (insertion, deletion), the inserted text, ...

def only_numbers(char):
    return char.isdigit()

validation = parent.register(only_numbers)
entry = Entry(parent, validate="key", validatecommand=(validation, '%S'))

The validate option determines the type of event that triggers the validation, here, it's any keystroke in the entry. The '%S' in the validatecommand option means that the inserted or deleted character is passed in argument to the only_numbers function. The full list of possibilities can be found here.