我是否总是必须为 Tkx 的 -command 参数提供匿名子例程? [英] Do I always have to provide Tkx's -command argument an anonymous subroutine?

查看:31
本文介绍了我是否总是必须为 Tkx 的 -command 参数提供匿名子例程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I find it a bit weird that I have to wrap defined subroutines anonymously when specifying the -command argument for Tkx widgets.

摘自 TkDocs 教程 演示了这一点:

An excerpt from a TkDocs tutorial demonstrates this:

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

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

为什么我写-command =>时不起作用?&calculate()-command =>\&calculate()?

推荐答案

您的语法不太正确.您的示例调用子例程(& 绕过任何原型)并传递返回值(&calculate())或对其的引用(\&calculate()) 到 -command 选项.您想为子程序本身分配一个引用,您可以通过以下方式进行:

You don't have the syntax quite right. Your examples call the subroutine (the & bypasses any prototypes) and passes either the return value (&calculate()) or a reference to it (\&calculate()) to the -command option. You want to assign a reference to the subroutine itself, which you can do via:

-command => \&calculate

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

Note the lack of trailing parentheses. Also note that you can't pass arguments this way. If you want to do that you need to either wrap the call in an anonymous subroutine:

-command => sub { calculate(12) }

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

or pass the option an ARRAY reference instead of a CODE reference:

-command => [\&calculate, 12]

如果您使用变量而不是文字值,这两种形式之间存在细微差别,这一点很重要.

There's a subtle difference between the two forms that's important if you use a variable instead of a literal value.

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

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

Using the first form changes to $x will be visible when the command is invoked. Under the second form they won't be; each invocation will see the value at the moment the binding was created. Both forms are useful; you just need to exercise good judgment when deciding which to use.

这篇关于我是否总是必须为 Tkx 的 -command 参数提供匿名子例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆