问题描述
我正在使用由 kmx 实现的 Perl IUP 模块,我喜欢它,因为它易于使用且外观还不错。
我需要从列表中创建一个带有多个按钮的框架框(比如 40-50)。我可以在遍历数组的 for 循环中轻松创建它(双数组,包含每行的“名称”和值) `
my @ChildsSetOfButtons=();
foreach $array (@ITEMNAME)
{
$tempButton = IUP::Button->new( TITLE=>$array->[2],SIZE=>"50x20",FONTSTYLE=>'bold',FONTSIZE=>"10");
$tempButton->ACTION( sub {selOrder($array->[3]); });
}
push(@ChildsSetOfButtons,$tempButton);
my $tableOfButton = IUP::Frame->new( TITLE=>"Items",child=>
IUP::GridBox->new( child=> [@ChildsSetOfButtons],NUMDIV=>4,ORIENTATION=>"HORIZONTAL"),MARGIN=>"5x5",EXPANDCHILDREN =>"YES",GAPLIN=>10,GAPCOL=>10);
按钮以漂亮的网格精美地出现在 GUI 中。现在我的问题是,如何从每个 Button 操作发送单独的唯一值? 我知道这些值在创建按钮时是静态链接的。
但不知何故,这个类似的实现我可以让它在 PerlTK 中工作,自从我开始使用这个 IUP,我不想回到 TKperl 并开始从 sratch 开始编写我的整个 GUI。 `
foreach my $array (@ITEMNAME)
{
$fr2->Button(-text=>$array->[2],-padx => 6,-font => ['arial','10','normal'],-foreground => 'blue',-command => [\&writeUARTDirect,$array->[3]],)->pack(-side=>'bottom');
}
` 我怎样才能让它在 perl-IUP 框架中工作?谁能告诉我一个窍门? :)
解决方法
您的示例存在一些问题。我添加了一点以使其可运行:
use IUP ':all';
use strict;
use warnings;
use v5.30;
my @ITEMNAME = ([0,foo=>'btn_foo'],[0,bar=>'btn_bar']
);
my @ChildsSetOfButtons=();
foreach my $array (@ITEMNAME)
{
my $tempButton = IUP::Button->new(
TITLE=>$array->[2],SIZE=>"50x20",FONTSTYLE=>'bold',FONTSIZE=>"10");
# alternative: copied value
# my $value = $array->[3];
# $tempButton->ACTION( sub {selOrder($value); });
$tempButton->ACTION( sub {selOrder($array->[3]); });
push(@ChildsSetOfButtons,$tempButton);
}
my $tableOfButton = IUP::Frame->new(
TITLE=>"Items",child=>
IUP::GridBox->new( child=> [@ChildsSetOfButtons],NUMDIV=>4,ORIENTATION=>"HORIZONTAL"),MARGIN=>"5x5",EXPANDCHILDREN =>"YES",GAPLIN=>10,GAPCOL=>10);
my $dlg = IUP::Dialog->new( TITLE=>"Test Dialog",MARGIN=>"10x10",child=> $tableOfButton,);
# Do you want changes like these being reflected in the callback?
$ITEMNAME[1]->[3] = 'another_value';
$ITEMNAME[0] = [];
$dlg->Show;
IUP->MainLoop;
sub selOrder{
my $val = shift;
say "you pressed $val";
}
我添加了 strict
并使您的变量词法化。您正在循环中创建按钮,但 push
语句在循环之外。所以您的按钮没有添加到 @ChildsSetOfButtons
。
您的回调子引用 $array->[3]
,它是 @ITEMNAME
的别名,如果更改 @ITEMNAME
中的值,这可能会导致意外的副作用。
您可以通过将值复制到循环内的词法变量中并在回调中使用它来避免这种情况。这样你就可以得到一个值与 @ITEMNAME
分离的闭包。