#BY Weigun http://blog.chinaunix.net/u2/70443/
use strict;
use Gtk2 '-init';
use Glib qw(TRUE FALSE);
use Encode qw(decode);
my $encoding = "gbk";
my $win=Gtk2::Window->new('toplevel');
$win->set_position('center_always');
$win->set_title(decode($encoding, '简单计算器' ));
$win->set_size_request(300,300);
my @btns;#按钮数组
#create button
for (0..9,'+','-','CE','=')
{
push @btns,Gtk2::Button->new($_);
}
#create label
my $label=Gtk2::Label->new('0');
$label->set_justify("right");
#boxes and table
my $vbox=Gtk2::VBox->new(FALSE,4);
my $hbox=Gtk2::HBox->new(FALSE,4);
my $table=Gtk2::Table->new(4,3,FALSE);
#pack in hbox
for my $btn (@btns)
{
my $btn_label=$btn->get_label();
$hbox->add($btn) if $btn_label eq 'CE' or $btn_label eq '=';
}
#pack in table
my ($i,$j)=(0,0);
for my $num_btn (@btns)
{
my $btn_label=$num_btn->get_label();
if($btn_label=~/^[0-9+-]$/)
{
while($i<=2)#控制行
{
while($j<4)#控制列
{
$table->attach_defaults($num_btn,$i, $i+1, $j, $j+1);
last;
}
$i>=2 ?($i=0,++$j) : (++$i);
last;
}
}
}
#pack label,table,hbox in vbox
$vbox->pack_start($label,TRUE,TRUE,0);
$vbox->pack_start($table,TRUE,TRUE,0);
$vbox->pack_start($hbox,TRUE,TRUE,0);
my $text='';#存放计算式
#设置callback
for (@btns)
{
my $btn_lb=$_->get_label();
if($btn_lb=~/^[0-9+-]$/)
{
$_->signal_connect(clicked =>\&btn_clicked);
}
elsif($btn_lb=~/^CE$/)
{
$_->signal_connect(clicked =>\&btn_CE);
}
else
{
$_->signal_connect(clicked =>\&btn_equal);
}
}
$win->signal_connect('delete_event' => sub { Gtk2->main_quit; });
#pack vbox in window
$win->add($vbox);
$win->show_all();
Gtk2->main();
sub btn_clicked
{
my $btn=shift;
$text.=$btn->get_label();
$label->set_text($text);
}
sub btn_CE
{
my $btn=shift;
$text='';
$label->set_text(0);
}
sub btn_equal
{
my $btn=shift;
$text=eval($text);
$text='ERROR' if !defined $text;
$label->set_text($text);
}
|