在tk perl接口中从子例程传递变量

问题描述

我正在使用perl Tk界面,我想要一个按钮test_1,单击此按钮后,我希望将变量$ varchoice定义为test_1。如果我按下按钮test_2,则变量$ varchoice应该定义为test_2。

之前是我尝试完成此操作的代码段:

$budget_frame->Button(-text => 'test_1',-command => sub{$varchoice=budget_plot_1()})->pack(-side => "left");
$budget_frame->Button(-text => 'test_2',-command => sub{$varchoice=budget_plot_2()})->pack(-side => "left");

sub budget_plot_1()
{
    print "plotting 1\n";
    my $var=1;
    return $var;
}

sub budget_plot_2()
{
    print "plotting 2\n";
    my $var=2;
    return $var;
}

如何调整此代码以获得所需的结果?

解决方法

您的程序似乎运行正常。这是我如何测试的示例:

use feature qw(say);
use strict;
use warnings;
use Tk;

my $budget_frame = MainWindow->new(-title=>"Button test");
my $varchoice;

$budget_frame->Button(
    -text => 'test_1',-command => sub{ $varchoice = budget_plot_1() }
)->pack(-side => "left");
$budget_frame->Button(
    -text => 'test_2',-command => sub{ $varchoice = budget_plot_2() }
)->pack(-side => "left");
MainLoop;
say "Value of \$varchoice = $varchoice";

sub budget_plot_1()
{
    print "plotting 1\n";
    return "test_1";
}

sub budget_plot_2()
{
    print "plotting 2\n";
    return "test_2";
}

输出

Value of $varchoice = test_1

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...