如何在Tkx中使用checkbutton打印所选值

时间:2011-12-04 02:34:04

标签: perl tk

我正在使用Tkx模块创建一个填充了@list文本值的窗口。然后我用一个检查按钮选择一个或多个。我想在按下“确定”按钮后打印已经选择的按钮,但不知道如何将变量传递给'OK' - 命令=> sub {}。感谢。

use autodie;
use strict;
use warnings;
use Tkx;

my $mw = Tkx::widget->new( "." );
$mw->g_wm_title( "Listbox" );
$mw->m_configure( -background => "#191919" );

my $width = '700';
my $height = '500';

Tkx::update('idletasks'); 
$width  ||= Tkx::winfo('reqwidth',  $mw); 
$height ||= Tkx::winfo('reqheight', $mw); 

my $x = int((Tkx::winfo('screenwidth',  $mw) / 2) - ($width / 2)); 
my $y = int((Tkx::winfo('screenheight', $mw) / 2) - ($height / 2)); 

$mw->g_wm_geometry($width . "x" . $height . "+" . $x . "+" . $y);

my @list = ('TEXT1', 'TEXT2', 'TEXT3', 'TEXT4', 'TEXT5');

for my $list (@list) {
    my $cb = $mw->new_ttk__checkbutton(
        -text => $list,
        -onvalue => 1,
        -offvalue => 0,
    );
    $cb->g_pack(
        -anchor=>'w',
        -side=>'top',
        -fill => 'x'
    );
 }

 my $ok = $mw->new_button(
    -text => "OK",
    -command => sub {       
        print "Selected Values";
        Tkx::after(500, sub { $mw->g_destroy });
    },
);

$ok->g_pack(
   -anchor=>'c',
   -side=>'bottom',
);

Tkx::MainLoop();

1 个答案:

答案 0 :(得分:0)

如果您只想查找选中的复选框:

my $settings;
for my $list (@list) {
    my $cb = $mw->new_ttk__checkbutton(
        -text => $list,
        -onvalue => 1,
        -offvalue => 0,
        -variable => \$settings->{checkbuttons}->{$list},
    );
    $cb->g_pack(
        -anchor=>'w',
        -side=>'top',
        -fill => 'x'
    );
 }

 my $ok = $mw->new_button(
    -text => "OK",
    -command => sub {       
        print "Selected Values: [";

        print join( ", ", grep { $settings->{checkbuttons}->{$_} } @list ), "]\n";
        Tkx::after(500, sub { $mw->g_destroy });
    },
);