Python Forum

Full Version: Entry Validation in tkinter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there..

I want to know how the inputs to an entry widget in tkinter is validated so as to accommodate only digits 0-20. This widget is going to accept marks of students (minimum is 0 and maximum is 20) from the user.

Thanks in advance!
Any validation must be written by you.
The entry widget provided by tkinter is a raw widget and will accept anything that is entered.
Which makes sense, as it's not known what the target use will be until a user decides what is or isn't allowed.
What have you tried so far?
(Oct-27-2020, 04:06 PM)Larz60+ Wrote: [ -> ]Any validation must be written by you.
The entry widget provided by tkinter is a raw widget and will accept anything that is entered.
Which makes sense, as it's not known what the target use will be until a user decides what is or isn't allowed.
What have you tried so far?

I wrote the following function to validate the Entry widget. It only accepts numbers. But I want to allow numbers between 0 and 20 only. How to achieve this?

# function to validate mark entry
def only_numbers(char):
    return char.isdigit()
validation = root.register(only_numbers)

#text box to enter marks
t2=Entry(root,validate="key", validatecommand=(validation, '%S'))
t2.pack()
please show enough (or all) code so that it can be run.

Basically:
  • create an event callback when data entered in widget.
    (do this on widget creation with command=callback_name, or in bind command)
  • if any of the following occurr: Fail, clear widget, show error message (using tkinter.messagebox), return without setting value
    • Not a digit
    • accumulated digits > 20
    • Number of digits > 2
  • if ok set value and exit event


Please note;, In event callback, you must keep track number of digits entered as an entry widget creates an event each time a value is entered.
here's an example on stack overflow validation example