I am new to Perl Tk. I have option menu. In its callback, I want to pass a table object which is created later. As per the selection of the option, I want to render specific data into the table.
Since my optionmenu is created before, how can I send the table object to it?
In the code, I have commented it as 'HOW TO PASS ?
use Tk;
use Tk::Table;
use Tk::NoteBook;
use Tk::Optionmenu;
my $data = { 'Jan' => { 'id' => 1, 'product' => 'new'} , 'Feb' => {'id'=>2,
'product'=> 'latest'} };
&tk_gui();
sub tk_gui {
my $mw = MainWindow->new;
$mw->geometry("500x500");
my $f = $mw->Frame()->pack(-side=>'top');
my ($var, $tvar);
my $opt = $f->Optionmenu(
-options => [[jan =>1], [feb =>2]],
-command => sub {
my @nums = @_;
#HOW TO PASS ?
&show_table_data($nums[0], $table)
},
-variable => \$var,
-textvariable => \$tvar,
)->pack(-side => 'left', -anchor => 'n',);
my $f2 = $mw->Frame()->pack(-side=>'bottom');
my $table = $f2->Table( -columns => 2);
my @col = qw(id product);
foreach my $c (0 .. 1) {
if ($c) {
my $t = $table->Label(-text => 'product');
$table->put(0, $c, $t);
} else {
my $t = $table->Label(-text => 'id');
$table->put(0, $c, $t);
}
}
$table->pack();
MainLoop;
}
sub show_table_data {
my $num = shift;
my $table = shift;
}
Since my optionmenu is created before, how can I send the table object to it?
Just declare the $table
variable before it is used in the callback. Even if the variable has not been defined when the callback is compiled, it will be defined when the callback is called at runtime. Example:
use feature qw(say);
use strict;
use warnings;
use Tk;
use Tk::Table;
use Tk::NoteBook;
use Tk::Optionmenu;
{
tk_gui();
}
sub tk_gui {
my $mw = MainWindow->new;
$mw->geometry("500x500");
my $f = $mw->Frame()->pack(-side=>'top');
my ($var, $tvar);
my $table; # <-- declare the variable here..
my $opt = $f->Optionmenu(
-options => [[jan =>1], [feb =>2]],
-command => sub {
my @nums = @_;
show_table_data($nums[0], $table);
},
-variable => \$var,
-textvariable => \$tvar,
)->pack(-side => 'left', -anchor => 'n',);
my $f2 = $mw->Frame()->pack(-side=>'bottom');
$table = $f2->Table( -columns => 2);
foreach my $c (0 .. 1) {
if ($c) {
my $t = $table->Label(-text => 'product');
$table->put(0, $c, $t);
} else {
my $t = $table->Label(-text => 'id');
$table->put(0, $c, $t);
}
}
$table->pack();
MainLoop;
}
sub show_table_data {
my $num = shift;
my $table = shift;
return if !defined $table;
say "Num = $num";
say "table = $table";
}