Entry

In a number of cases it is impractical for an application to provide a prescribed set of possible answers to some question. What is your name? What is your email address? The entry widget allows the user to enter some text in a (single line) textfield box. The syntax for its use is
my $entry = $mw->Entry( [ option => value ] );
Some basic options are As well, there are two common methods We give two examples. In the first,
#!perl
# file entry.pl
use Tk;
use strict;
use warnings;
my $entry_value = 'not given';
my $message = "Your name is $entry_value";
my $mw = MainWindow->new;
$mw->title('Entry');
my $label = $mw->Label(-textvariable => \$message);
my $enter = $mw->Label(-text => 'Enter your name');
my $name = $mw->Entry(-width => 30);
$name->insert('end', $entry_value);
my $show = $mw->Button(-text => 'Show name',
                       -command => \&display);
my $exit = $mw->Button(-text => 'Exit',
                      -command => [$mw => 'destroy']);
$label->pack;
$enter->pack;
$name->pack;
$show->pack;
$exit->pack;
MainLoop;
sub display {
  $entry_value = $name->get();
  $message = "Your name is $entry_value";
  $name->delete(0, 'end');
  $name->insert('end', $entry_value);
}


which is illustrated below,

Figure 3.13: Example of an entry widget
Image entry

the $show button, when clicked, will call the display subroutine. This routine will fetch the current value of the $name entry widget, update the $message string with that value, and then clear the entered text with the delete method. The insert method is then used to place in the entry box the value just entered. The $message string is subsequently used as the text for the $label label.

In the second example,

#!perl
# file entry1.pl
use Tk;
use strict;
use warnings;
my $entry_value = 'not given';
my $message = "Your name is $entry_value";
my $mw = MainWindow->new;
$mw->title('Scale');
my $label = $mw->Label(-textvariable => \$message);
my $enter = $mw->Label(-text => 'Enter your name');
my $name = $mw->Entry(-width => 30,
                      -textvariable => \$entry_value);
my $show = $mw->Button(-text => 'Show name',
                       -command => \&display);
my $exit = $mw->Button(-text => 'Exit',
                      -command => [$mw => 'destroy']);
$label->pack;
$enter->pack;
$name->pack;
$show->pack;
$exit->pack;
MainLoop;
sub display {
  $message = "Your name is $entry_value";
}
which appears below,

Figure 3.14: Another example of an entry widget
Image entry1

the value entered by the user in the entry box is associated with the $entry_value variable. This variable is then used in the display routine, called when the $show button is clicked, to update the $message string used in the $label label.

Randy Kobes 2003-11-17