TKX: Creating buttons via for loop assistance requested

Posted by scriptboy on 2013-01-24 02:44

use Tkx;
my $MainWindow = Tkx::widget->new(".");
Tkx::grid_columnconfigure( ".", 0, -weight => 1);
Tkx::grid_rowconfigure(".", 0, -weight => 1);

### Create Frames ###
Tkx::grid(Tkx::ttk__frame(".f1f", -padding => "0 0 0 4", -relief => 'flat',-borderwidth=>5), -row => 0, -column => 1, -sticky => "nwes");
Tkx::grid( Tkx::ttk__label(".f1f.status", -text => "Listing",-relief=>'raised',-font=>r24,-background => "aquamarine4"), -row=> 0, -column=> 0, -columnspan=>4, -sticky => "we");

for ($Item=1;$Item<5;$Item++) {
Tkx::grid( Tkx::ttk__label(".f1f.linenumber{$Item}", -text => "# $Item",-relief=>'flat',-width=> 4,-font=>r24,-background => "$LineColor"), -row=> $Item, -column=> 1, -sticky => "w");
Tkx::grid( Tkx::ttk__label(".f1f.check{$Item}", -text => "Click here for $Item",-relief=>'flat',-width=> 30,-font=>r24,-background => "$LineColor"), -row=> $Item, -column=> 2, -sticky => "w");
Tkx::ttk__button(".f1f.gobutton{$Item}", -text => "Fix", -command => sub {DisplayMsg($Item);} );
Tkx::grid(".f1f.gobutton{$Item}", -row => $Item, -column => 3,-sticky => "we",-columnspan=>1);

}
Tkx::MainLoop();
exit;

sub DisplayMsg {
@Msg=@_;
Tkx::tk___messageBox(
-parent => $MainWindow,
-icon => "info",
-title => "Results",
-message => "You pressed: @Msg",
);
Tkx::update();
}

jukari | Wed, 2013-02-27 03:37

I am at work right now so I don't have Perl installed.... but I had a similiar problem I had to come up with a way to maintain the varible assigned to a checkbox... here is the code I used.

FYI: Always use strict.

my $check_box = $line_split[0]; #assigned a specific name
my $checkbox = $current_open_window->new_ttk__checkbutton(-textvariable=>$line_counter);
$checkbox->configure(-variable => \$check_box, -onvalue => "ON", -offvalue => "OFF",-textvariable=>$line_counter,-command=>[
sub{
my $line_number = $checkbox->configure(-textvariable); #uses the -text varible to retrieve the checkbox number... there were hundreds...
update_value_sync($line_number,$check_box);
}]);
$checkbox->g_grid(-row => $counter, -column =>51,-sticky =>"w",rowspan => 5);

Hope this helps...

jfthuong | Mon, 2015-01-05 18:57

The buttons in the loop call the subroutine instead of a reference to the subroutine.

The line 13 shall therefore be modified as follows:
Tkx::ttk__button(".f1f.gobutton{$Item}", -text => "Fix", -command => [\&DisplayMsg, $Item] );

Note: it is a bit strange to use @Msg=@_ instead of $Msg=shift in the subroutine while there is only one argument.