Dialogue boxes At times you may wish to confirm with a user that the requested action is really the one she/he wants. A common example of this is in saving a file, and the user enters a file name which already exists - does the user want to overwrite this file? A dialogue box is a common way to allow a user to confirm this. The basic syntax is my $dialog = $mw->Dialog( [ option => value ] );
Some basic options are -title => value
This gives the text to appear in the title bar for the dialog box. -text => value
This is the message to appear in the top portion of the dialog box. -bitmap => value
If this is non-empty, it specifies a bitmap to display in the top portion of the dialog, to the left of the text. If empty, then no bitmap is displayed in the dialog. -default_button => value
This is the text label string of the button that displays the default value. -buttons => list reference
This gives a reference to a list of button label strings. Each string specifies the text to display in a button, in order from left to right. The use of the dialogue box is different than the widgets considered so far in this chapter, in that it is invoked when the action of another widget calls for it. The answer received from the dialogue can be retrieved via my $answer = $dialog->Show(-global);
In this, -global, if specified, results in a global (rather than a local) grab being done. An example of the use of a dialogue box follows.
#!perl
# file dialog.pl
use Tk;
use strict;
use warnings;
my $message = 'nothing yet ...';
my $mw = MainWindow->new;
$mw->title('Dialog');
my $label = $mw->Label(-textvariable => \$message);
my $save = $mw->Button(-text => 'Press to save!',
-command => \&dialog);
my $exit = $mw->Button(-text => 'Exit',
-command => [$mw => 'destroy']);
$exit->pack(-side => 'bottom');
$save->pack(-side=>'top');
$label->pack(-side => 'top');
MainLoop;
sub dialog {
use Tk::Dialog;
my $dialog = $mw->Dialog(-text => 'Save File?',
-bitmap => 'question',
-title => 'Save File Dialog',
-default_button => 'Yes',
-buttons => [qw/Yes No Cancel/]);
my $answer = $dialog->Show();
$message = qq{You pressed '$answer'};
}
In this example, when the user presses the ``Press to save!'' button, a dialogue box will pop up, asking for confirmation. The value selected will subsequently be reflected in the label appearing in the main window. The dialogue box appears in the figure below.
Figure 3.23: Example of a dialogue box
圖片參考:
http://theory.uwinnipeg.ca/perltk/widgets/dialog.png