I'm trying to create a Tk::Entry widget in my program that will accept a floating point value with two decimal places of precision, with a range of -10.00 to 10.00.
The way I'd prefer this to work is something like this:
While the user is typing in the Entry widget, pretty much anything is allowed, as long as it matches regex /^-?\d+\.?\d+$/
But as soon as the user leaves the Entry widget and it loses focus, any number that is out of range (< -10 or > 10) gets rejected, and numbers get formated to sprintf %.2f
My conundrum is that the Tk documentation goes to great pains to stress that you shouldn't use validation in an Entry widget to change the text variable. But that's exactly what I'm trying to do with it! If the user has typed a value that I consider out of range or invalid, I want to change it! How do I change it without changing it?
Here's some code to give an idea of how I'm floundering around with this. Please let me know what I should be doing here:
my $fctrEntry = $mw->Entry(
-textvariable => \$factor,
-validate => 'focus',
-validatecommand => \&validate,
#-invalidcommand => \&invalidate,
-insertbackground => 'cyan',
-selectforeground => 'white',
-selectbackground => 'DarkRed',
-highlightcolor => 'cyan',
-background => 'black',
-foreground => 'white')->grid(
-row => $chartrow[2] + 2,
-column => 32,
-columnspan => 3,
-sticky => 'new');
sub validate {
my $val = shift;
$val ||= "1.00";
if ($val !~ /^-?\d{1,2}\.\d\d$/ or $val < -10 or $val > 10) {
print "Bad! ";
return 0;
} else {
print "Good! ";
return 1;
}
}
sub invalidate {
$factor = sprintf("%.2f", $_[0]);
print "Validate! $factor ";
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.