基于循环使用perl TK制作按钮列表

Making a list of buttons in using perl TK based ona loop

我在数组中有一个项目循环,如下所示:

("Hugo", "Gilbert", "Linda", "Katrina")

我想做的是设计一个 perl Tk 脚本,允许我根据数组中的内容创建一些单选按钮,如下所示:

<> Hugo
<> Gilbert
<> Linda
<> Katrina

当我点击每个按钮时,如果我点击了 Hugo,我应该会收到一条弹出消息说 "You selected Hugo"。

下面是我试图完成此操作的代码片段:

#!/usr/bin/perl -w
# 
use Tk;
use strict;

my $mw = MainWindow->new;
$mw->geometry("200x500");
$mw->title("Button Test");


my @items = ("Hugo", "Gilbert", "Linda", "Katrina");

foreach my $item(@items) {
    print "$item\n";
    $mw->Radiobutton(-text => "$item", -command => \&button1_sub)->pack();
}


sub button1_sub {
  my $button=@_;
  $mw->messageBox(-message => "$button Pushed", -type => "ok");
}
MainLoop;

我没有从这段代码中得到想要的结果。如何调整代码以获得上述结果?

两期:

  1. 这一行

    my $button = @_;
    

    是标量赋值,它在标量上下文中评估 @_ 数组,即将其大小分配给 $button。如您所见,它为 0,即数组为空 - sub 没有任何参数。

  2. 如上所述,您需要向回调传递一个参数。有两种可能的方式:

    # Array syntax
    $mw->Radiobutton(-text => $item,
                     -command => [\&button1_sub, $item]
    

    # Subroutine syntax
    $mw->Radiobutton(-text => $item,
                     -command => sub { button1_sub($item) }
    

如您所见,我从 "$item" 中删除了双引号。这里是多余的,可以直接使用变量

例如

#!/usr/bin/perl
use warnings;
use strict;

use Tk;

my $mw = MainWindow->new;
$mw->geometry('200x500');
$mw->title('Button Test');

my @items = qw( Hugo Gilbert Linda Katrina );

for my $item (@items) {
    $mw->Radiobutton(-text    => $item,
                     -command => [\&button1_sub, $item]
    )->pack;
}

sub button1_sub {
  my ($button) = @_;
  $mw->messageBox(-message => "$button Pushed",
                  -type    => 'ok');
}
MainLoop();