perl - 我可以将带参数的子例程存储在哈希中吗?

标签 perl tk-toolkit

我正在 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 pocket 指南显示

Perl/Tk Callbacks A callback is a scalar, either a code reference or a method name as a string. Either of these styles can take parameters by passing an array reference, with the first element the code reference or method name, and subsequent elements subroutine parameters. \&subroutine [\&subroutine ?, args?] sub {...} [sub {...} ?, args?] ’methodName’ [’methodName’ ?, args?] Note that bind callbacks are implicitly passed the bound widget reference as the first argument of the parameter list. Refer to the section Bindings and Virtual Events for related information.

我使用下面的代码对此进行了测试,它按预期工作

#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";
}

关于perl - 我可以将带参数的子例程存储在哈希中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30445361/

相关文章:

arrays - 一行多次弹出

perl - 使用 Perl 拆分 float

perl - 使用 perl HTTP::Daemon 的 HTTP 服务器 - 只能在服务器运行的同一台计算机上工作

perl - cpan 忽略 makepl_arg 和 mbuild_arg

arrays - 返回数组列表

python - 带有 tk 的窗口以获取文本

linux - 打开愿望而不窃取焦点

xml - 在 perl 的子程序中声明全局变量

linux - 调用键盘按键,通过 proc - tcl 中的过程(函数)

python 3.x tkinter,将来自 opencv cv2 的帧集成到 tkinter 窗口中