in reply to Perl/TK get the Button's text
(Not to be confused with "high aboveyou" :-))
If you want to do this dynamically, so that it will work even after the button's text has changed, you can either use the -textvar option suggested above, or you can construct the button in two steps.
For example, the first step would be something like:
and in the second step, a subroutine (which takes the button name as an argument) is configured as the command invoked when the button is pressed:my $button = $mw->Button(-text => $label);
$button->configure(-command => [ \&show_button_label, $button ]); -or- $button->configure(-command => sub { show_button_label($button) }) +;
Obviously you can't do this in one step, as $button isn't defined until you have the return value from $mw->Button, and you need to pass $button to the subroutine.
Here's a full example:
#!/usr/bin/perl # Libraries use strict; use warnings; use Tk; # User-defined my @button_labels = (qw( Red Blue Green White Yellow Orange )); # Main program my $mw = new MainWindow(); foreach my $label (@button_labels) { # Note labels are colors, so they can be used for the background my $button = $mw->Button(-text => $label, -bg => $label); $button->configure(-command => [ \&show_button_label, $button ]); $button->pack(-side => "left"); } MainLoop(); # Subroutines sub show_button_label { my ($button) = @_; my $label = $button->cget(-text); print "Label for button '$button' is '$label'\n"; }
|
|---|