I am trying to validate the input of an entry widget, so that only digits (0-9) may be entered. If the user presses an invalid key (e.g. a 'j') I want the widget to silently ignore the input.
Here is the code I have tried:
import tkinter as tk
from tkinter import ttk
def on_key_integer(event, var):
""" Ensures that the key pressed is an numeric value 0-9"""
""" user can use any numeric key """
"""If they use a non-numeric key this should be removed silently, as if they had not pressed it """
currentPosition = event.widget.index("insert")
print(f"The value of the variable is: {var.get()}")
print(f"The key '{str(event.char)}' was pressed at position {currentPosition}")
if str(event.char) not in [str(x) for x in range(0,10)]: # builds a list of str versions of numbers 0-9
print("The key pressed is non-numeric")
# delete the character entered
event.widget.delete(currentPosition-1)
root=tk.Tk()
root.title("Dog data entry form")
root.columnconfigure(0,weight=1)
variables=dict()
ttk.Label(root, text = "Dog data entry", font = ("Verdana", 16)).grid()
ttk.Label(root, text="Dog's Age").grid(row=2, column=0, padx=10, sticky="e")
variables["Dog Age"] = tk.StringVar()
variables["Dog Age"].set('')
dog_age=ttk.Entry(root, textvariable=variables["Dog Age"])
dog_age.bind("<Key>", lambda event, v=variables["Dog Age"] : on_key_integer(event, v))
dog_age.grid(row=2, column=1, sticky=(tk.E+tk.W))
dog_age.focus_set()
root.mainloop()
What happens is that the code allows any digits to be retained. If I enter a 'j', or any other invalid character then that character remains, but the previous character is removed (deleted). I tried to delete using currentPosition, rather than currentPosition-1, and nothing is deleted from the entry field. Can anyone explain what is happenning and how I might resolve this.
Thanks in advance (by the way, this is being used as a teaching tool)