Answering an older question here, but I was having an extremely similar problem and wound up finding a decent solution. @Bryan Oakley's answer is useful, but doesn't provide an example, which is what I aim to do here.
After importing Tkinter
or tkinter
(depending on your Python version) as tk
, first define the initial validation command:
val_cmd = (master.register(self.validate), '%P') # master is root in thie case.
Next, whenever you have an entry box needing validation, I found this to be a nice way to write it out:
self.entry = tk.Entry(your_frame_of_choice)
self.entry.insert('end', 100) # Inserts 100 as an initial value.
self.entry.config(validate='key', validatecommand=val_cmd)
This inserts a value before the validation begins. I originally had something like self.entry = tk.Entry(your_frame_of_choice, validate='key', validatecommand=val_cmd)
, but various iterations of the validation function that I toyed with rejected the insert code if the validation came before the insert
. The one listed below doesn't care, but I've kept the entry
code this way as I find it more aesthetically pleasing.
Finally, the actual function:
def validate(self, input_text):
if not input_text:
return True
try:
float(input_text)
return True
except ValueError:
return False
This checks for floats
, but you could easily change it to ints
, as you prefer. And, most importantly, it allows you to delete and write over any highlighted text in the entry box.
I'm sure the initial problem is long gone, but I hope someone in the future finds this to be helpful!