我是否总是必须提供Tkx的-command参数作为匿名子程序?

Zai*_*aid 2 perl subroutine tkx

我发现在指定-commandTkx小部件的参数时,我必须匿名包装已定义的子例程,这有点奇怪.

TkDocs教程的摘录证明了这一点:

my $cb = $frm->new_ttk__button ( -text => "Calculate",
                                 -command => sub {calculate();}  );

sub calculate {
   $meters = int(0.3048*$feet*10000.0+.5)/10000.0 || '';
}
Run Code Online (Sandbox Code Playgroud)

为什么当我写不它的工作-command => &calculate()还是-command => \&calculate()

Mic*_*man 6

你没有正确的语法.您的示例调用子例程(&绕过任何原型)并将返回值(&calculate())或对它的引用(\&calculate())传递给该-command选项.您想要为子程序本身分配一个引用,您可以通过以下方式执行:

-command => \&calculate
Run Code Online (Sandbox Code Playgroud)

请注意缺少尾随括号.另请注意,您无法以这种方式传递参数.如果你想这样做,你需要在匿名子程序中包装调用:

-command => sub { calculate(12) }
Run Code Online (Sandbox Code Playgroud)

或传递选项ARRAY引用而不是CODE引用:

-command => [\&calculate, 12]
Run Code Online (Sandbox Code Playgroud)

如果您使用变量而不是文字值,那么两种形式之间存在细微差别.

-command => sub { calculate($x) }  # creates a closure over $x
-command => [\&calculate, $x]      # makes a copy of $x
Run Code Online (Sandbox Code Playgroud)

使用第一个表单更改$x将在调用命令时可见.在第二种形式下,他们不会; 每次调用都会在创建绑定时看到值.两种形式都很有用; 在决定使用哪个时,你只需要做出正确的判断.