我正在perl / tk中构建一个项目,该项目将允许启动计时器来跟踪项目工作。我对于如何将按钮的命令存储为子例程但带有参数而停顿了。由于带有参数的子例程正在执行,因此结果将存储为命令。
我如何将带有参数的子例程存储在哈希中,以便仅在按下按钮时才执行。
#create buttons but dont pack them on the frame yet
my $info = $mw->Button( -text => "Good", -command => \&info_popup );
my $warning = $mw->Button( -text => "Caution", -command => \&warning_popup );
my $error = $mw->Button( -text => "Bad", -command => \&error_popup );
my $close = $mw->Button( -text => "Close", -command => \&close );
my $project1 = $mw->Button( -text => "project1", -command => \&start_timer("project1"));
my $project2 = $mw->Button( -text => "project2", -command => \&start_timer("project2"));
sub start_timer {
my $project = shift;
print "starting the timer for: $project\n";
}
我怀疑我尝试的事情将无法实现,因此将对如何实现适合此标准的解决方案提供帮助,即按按钮将调用具有该按钮特定参数的子例程。
使用TK时,oreilly袖珍指南说
Perl / Tk回调回调是标量,可以是代码引用,也可以是方法名称(字符串)。这两种样式均可通过传递数组引用,第一个元素为代码引用或方法名以及后续元素子例程参数来获取参数。\&subroutine [\&subroutine?,args?] sub {...} [sub {...}?,args?]'methodName'['methodName'?,args?]请注意,绑定回调隐式传递给绑定的小部件引用作为参数列表的第一个参数。有关相关信息,请参阅“绑定和虚拟事件”部分。
我使用下面的代码对此进行了测试,它可以按预期工作
#create buttons but dont pack them on the frame yet
my $info = $mw->Button( -text => "Good", -command => \&info_popup );
my $warning = $mw->Button( -text => "Caution", -command => \&warning_popup );
my $error = $mw->Button( -text => "Bad", -command => \&error_popup );
my $close = $mw->Button( -text => "Close", -command => \&close );
my $project1 = $mw->Button( -text => "project1", -command => [\&start_timer,"project1"]);
my $project2 = $mw->Button( -text => "project2", -command => [\&start_timer,"project2"]);
sub start_timer {
my $project = shift;
print "starting the timer for: $project\n";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句