Tkinter validation of Entry widgets in Python

Viewed 65

I want to know how the inputs to an entry widget in tkinter is validated so as to accommodate only one digit and (+/-) symbols. This widget is going to accept charge of the atom from the user. Add in this code below:

class Onlyonedigit(ttk.Entry):
    def __init__(self, parent, *args, **kwargs):
      super().__init__(parent, *args, **kwargs)
      self.configure(
        validate='all',
        validatecommand=(self.register(self.validate_digit), '%P'),
        )
    def validate_digit(self, input):
      if input.isdigit():
        return True
      else:
        return False
1 Answers

1. Solution Steps


  1. Import tkinter module
import tkinter
  1. Import tkinter submodules
from tkinter import * # (*) Asterisk symbol means import everything
  1. Define the callback function
def callback(input):
   if input.isdigit():
       print(input)
       return True
                       
   elif input is "":
       print(input)
       return True

   else:
       print(input)
       return False

Explanation:

The callback function checks the input in the Entry widget for valid entry. If the entry is valid it returns True else False. In this example, the input entered through the keyboard is checked for numeric type. If the input is numeric type then the callback function returns true. For deletion operation the callback function returns true as input is “” . However for any non- numeric input the callback function returns false.

  1. Creating the parent window
root=Tk()
  1. Creating Entry widget
e=Entry(root)
  1. Specify the position of Entry widget within the parent window
e.place(x=50, y=50)
  1. Register the callback function
reg=root.register(callback)
  1. Call the callback function to validate the input in Entry widget
e.config(validate="key", validatecommand=(reg, '%P'))

Final step : Run the application

root.mainloop()

Hope it works. Source : Python Tkinter - Validating Entry Widget -GeeksforGeeks

2. Complete code:


import tkinter
from tkinter import *


def callback(input):
    
    if input.isdigit():
        print(input)
        return True
                        
    elif input is "":
        print(input)
        return True

    else:
        print(input)
        return False
                        
root = Tk()

e = Entry(root)
e.place(x = 50, y = 50)
reg = root.register(callback)

e.config(validate ="key",
        validatecommand =(reg, '% P'))

root.mainloop()
Related