I need to implement an entry box that accepts only a range of DoubleVar values. I have referenced this question that was asked How to only allow certain parameters within an entry field on Tkinter, but I want the user to be notified (using a change in font colour or anything) while they are entering the values. I've read the documentation but this is something that I haven't come across. I'm new to Tkinter, so please excuse me if this sounds very stupid
Asked
Active
Viewed 351 times
2 Answers
1
You can bind KeyRelease
event of the Entry
to a callback and check whether the input value is valid and within the required range, then update the foreground color of the Entry
accordingly:
import tkinter as tk
root = tk.Tk()
def check_value(entry, min_value, max_value):
try:
value = float(entry.get().strip())
valid = min_value <= value <= max_value
except ValueError:
valid = False
entry.config(fg='black' if valid else 'red')
return valid # in case you want the checking result somewhere else
entry = tk.Entry(root)
entry.pack()
entry.bind('<KeyRelease>', lambda e: check_value(e.widget, 10, 20))
root.mainloop()

acw1668
- 40,144
- 5
- 22
- 34
0
Use the validatecommand
option for the Entry
.
Some code fragments to show how it works:
root = tk.Tk()
vcmd = root.register(is_number)
e = ttk.Entry(pressf, justify='right', validate='key', validatecommand=(vcmd, '%P'))
def is_number(data):
"""Validate the contents of an entry widget as a float."""
if data == '':
return True
try:
rv = float(data)
if rv < 0:
return False
except ValueError:
return False
return True
This basically calls the validation function on every keypress. Only if the validation succeeds is the character added to the entry.
You can find a complete working example here.
Edit
Above is the "canonical" example of a validator. It allows or disallows characters into the Entry
.
But you can also use it in other ways.
For example, you can always return True
, but e.g. change the text color of the Entry
to red if the value is not within the limits you want.

Roland Smith
- 42,427
- 3
- 64
- 94
-
This can't work when trying to validate within a range, which is what the OP is asking for. – Bryan Oakley Apr 01 '20 at 22:16
-
@BryanOakley Validating if a number is within a range is basically just another step after checking that it is a `float`. I don't see why one couldn't do that. – Roland Smith Apr 01 '20 at 22:32
-
Ok, what if the range is between 10 and 20? You can't type `1` because it's not in the range, so you can't type `10` either. If it was prepopulated with 10 and you want to change it to 11, it won't let you backspace over the zero in order to change it to a one. It's a major usability problem to disallow characters in this scenario. – Bryan Oakley Apr 01 '20 at 22:52