1

我正在使用由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 并从头开始编写我的整个 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 框架中工作?谁能告诉我一个窍门?:)

4

1 回答 1

2

您的示例存在一些问题。我添加了一些使其可运行:

use IUP ':all';
use strict;
use warnings;
use v5.30;

my @ITEMNAME = ([0,0,foo=>'btn_foo'],
                [0,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

于 2021-01-30T08:54:14.920 回答