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.

Example

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

Output

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.

raja
Published on 16-Apr-2021 06:52:22
Advertisements