How to interactively validate an Entry widget content in tkinter?

TkinterServer Side ProgrammingProgramming

Validating the content is a necessary part of any featured application where we allow only the required data to be processed. An Entry Widget in tkinter is used to display single line text Input. However, we can validate the Entry widget to accept only digits or alphabets.

Let us first create an Entry widget that accepts only digits input. So initially, we will create an Entry widget and using register(callback) function, we will call to validate the Entry widget which validates whenever a key is stroked. It returns a string that can be used to call a function. Then, calling the callback function to validate the entry widget as,

entrywidget.config(validate="key", validatecommand=(callback,'%d'))

Validatecommand supports other values such as, %d, %i, %W, %P, %s, %v, etc.


#Import the required library
from tkinter import *
#Create an instance of tkinter frame or window
win = Tk()
def callback(input):
   if input.isdigit():
      return True
   elif input=="":
      return True
      return False
#Create an entry widget
entry= Entry(win)
fun= win.register(callback)
entry.config(validate="key", validatecommand=(fun, '%P'))


Running the above code will display a window that contains an Entry widget which accepts only digits and prints the key strokes on the console.

In the output screen, enter any character. You will find that you can enter only digits, thus the entry widget is validated.

Updated on 16-Apr-2021 06:52:46