It's because you're passing a copy of the variable to your rutine subroutine, rather than a reference to it.
Try this instead:
#!/usr/bin/perl -w + use Tk; use strict; + my $mw = MainWindow->new; + my $var=0; + my $button_A = $mw->Button( -text => ' Button A', -command =>[\&rutine, \$var, ]);# $button_A->pack; + my $button_B = $mw->Button( -text => ' ++ ', -command => sub{$var++; print "\$var is $var!\n";}); $button_B->pack; + my $button_C = $mw->Button( -text => ' -- ', -command => sub{$var--; print"\$var is $var!\n";}); $button_C->pack; + MainLoop; + + sub rutine { my ($pvar)=@_; + print "\$pvar => $$pvar\n"; + }
Update: To elaborate a bit...
When you create the anonymous subroutine -command => sub{$var++; print "\$var is $var!\n";}); for the "++" button (and the similar one for "--"), you were still in the same lexical scope of the original my $var=0; a few lines above, so it's not modifying the value of "$var" until it's called.
But in your original code, [-command =>[\&rutine, $var, ]); is taking a "snapshot" of the value of "$var" and using that value instead of the current value.
Another way to fix it would be to simply use an anonymous subroutine (and use your original rutine subroutine) which would correctly use the current value of "$var" when invoked:
my $button_A = $mw->Button( -text => ' Button A', # -command =>[\&rutine, \$var, ]);# -command => sub{ rutine($var) }); $button_A->pack; # ... sub rutine { my ($var)=@_; + print "\$var => $var\n"; + }
In reply to Re: Fundamental tk-problem
by liverpole
in thread Fundamental tk-problem
by tamaguchi
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |