从 tk perl 接口中的子程序传递变量

Passing variable from subroutine in tk perl interface

我正在使用 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