Tkinter Designer

← tkinter how-to

How do I validate a tkinter Entry (numbers only, maximum length)?

Give the Entry validate="key" and a validatecommand. Tk calls your function before every edit, with the text as it would be afterwards, and the edit only happens if the function returns True:

import tkinter as tk

root = tk.Tk()

def only_digits(new_text):
    # Return True to accept the edit, False to reject it
    return new_text == "" or new_text.isdigit()

check = root.register(only_digits)
age = tk.Entry(root, validate="key", validatecommand=(check, "%P"))
age.pack(padx=20, pady=20)

root.mainloop()

What register and %P are doing

Tk cannot call a Python function directly, so root.register() wraps it and returns a command name Tk can call. The strings after it say what to pass in. %P is the text as it would be if the edit went through, which is nearly always what you want. %S is just the text being typed or deleted, and %d is "1" for an insert and "0" for a delete.

Allow the empty string, or the user cannot delete the last character. Key validation also applies to entry.insert() from your own code, and a paste is accepted or rejected as a whole.

Numbers with decimals and a minus sign

Testing with float() works, except while the number is half typed: "-" and "." are not numbers yet, and rejecting them makes negative and decimal values impossible to enter. Let those partial forms through and check the finished value when you use it.

def is_number(new_text):
    if new_text in ("", "-", ".", "-."):
        return True             # half-typed numbers float() would reject
    try:
        float(new_text)
        return True
    except ValueError:
        return False

A maximum length

Check the length of %P. A paste that would go past the limit is rejected entirely rather than cut short, which is usually less confusing than silently losing the end of it.

def max_ten(new_text):
    return len(new_text) <= 10

Validation that stops working

If the function returns anything other than True or False (a forgotten return gives None) or raises an exception, Tk rejects that edit and then turns validation off for good. The Entry accepts anything from then on, and the only clue is a traceback in the terminal or entry.cget("validate") reporting none. Make every path return a boolean.

Setting the text through a StringVar does the same: var.set() is not validated, and it switches validation off as well. Turn it back on straight afterwards.

var.set("abc")                      # not checked, and validation is now off
entry.configure(validate="key")     # turn it back on

Checking when the user leaves the field

Some things cannot be judged keystroke by keystroke: an email address is invalid until it is finished. validate="focusout" runs the check when the field loses focus, and invalidcommand runs when it fails. That is the place to show a message rather than block typing.

def check_email(new_text):
    return "@" in new_text

def complain():
    error.configure(text="That doesn't look like an email address")

email = tk.Entry(root, validate="focusout",
                 validatecommand=(root.register(check_email), "%P"),
                 invalidcommand=complain)

In CustomTkinter and ttkbootstrap

CTkEntry accepts the same validate and validatecommand options. The catch is placeholder_text: CustomTkinter writes the placeholder into the field as ordinary text, a digits-only check rejects it, and the placeholder silently disappears. Let the placeholder through.

ttkbootstrap has ready-made checks in ttkbootstrap.validation. They mark the field invalid with a red border when it loses focus, rather than blocking typing, unless you pass when="key".

def digits_or_placeholder(new_text):
    return new_text in ("", "Age") or new_text.isdigit()

age = ctk.CTkEntry(root, placeholder_text="Age", validate="key",
                   validatecommand=(root.register(digits_or_placeholder), "%P"))

# ttkbootstrap
from ttkbootstrap.validation import add_numeric_validation, add_range_validation
add_range_validation(age_entry, 1, 120)            # red border if out of range
add_numeric_validation(qty_entry, when="key")      # block non-numbers as typed

Doing it without the lookup

The designer has no validation setting yet. The starter checks the value when a button is clicked, which it can do. For checking as the user types, write the check function as a method in the designer, which keeps it, then add the configure(validate=..., validatecommand=...) line to the exported file. If you import that file back, the designer warns you that it cannot keep that one line.

This example is ready to open: change it on the canvas and watch the Python update.

Open this example in the designer →

Related questions