0

How does data validation work with tkinter?

import tkinter as tk

def on_validate(value):
    if value.isnumeric():
        entry.config(bg='red')
    elif value.isalpha():
        entry.config(bg='blue')
    else:
        entry.config(bg='green')
    return True

root = tk.Tk()

entry = tk.Entry(root, validate='key')
entry.config(validatecommand=(entry.register(on_validate), '%P'))
entry.pack()

root.mainloop()

While I can see what the code does, it is not clear how it does it. The on_validate is clear but the following lines are not:

entry = tk.Entry(root, validate='key')
entry.config(validatecommand=(entry.register(on_validate), '%P'))

What is validate='key' and entry.register and %P? I had thought that just a validatecommand=on_validate should be sufficient but there is more code than that.

quantum231
  • 2,420
  • 3
  • 31
  • 53
  • Check if this answer your question please: https://stackoverflow.com/questions/55184324/why-is-calling-register-required-for-tkinter-input-validation/55231273#55231273 – Paweł Kowalski Feb 21 '23 at 23:11

0 Answers0