coderama has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to change the state of a Tk::Button widget based on a variable? I don't see where this is possible out of the box, but my initial thought was to create a timer that evaluates the value of a variable and configures the button based on the value of the variable. Any better ideas? The example below changes the button's state to active when $number equals 1
use Tk; my $number = 0; my $mw = tkinit(); my $button = $mw->Button(-text => 'Button')->pack(-side => 'left'); my $label=$mw->Label(-textvariable=>\$number)->pack(-side=>'left'); my $timer = $mw->repeat(100, sub{ $number = int(rand(5)); if ( $number == 1 ){ $button->configure(-state => 'normal'); } else { $button->configure(-state => 'disabled'); } }); $mw->MainLoop();

Replies are listed 'Best First'.
Re: Change the state of Tk::Button widget based on a variable?
by zentara (Cardinal) on Sep 28, 2011 at 16:51 UTC
    Use Tie::Watch
    #!/usr/bin/perl use warnings; use strict; use Tk; use Tie::Watch; my $mw = MainWindow->new; $mw->fontCreate('big', -weight=>'bold', -size=> 18 ); my $foo='neutrino'; my $watch = Tie::Watch->new(-variable => \$foo, -store => \&store_call +back); my $entry = $mw->Entry(-textvariable => \$foo, -bg => 'white', -font => 'big')->pack; $entry->icursor('end'); $entry->focus; my $testbutton; $testbutton = $mw->Button(-text => 'Foo Watcher', -state => 'disabled', -command => sub{ print "$foo\n"; $testbutton->configure(-state => 'disabled', -bg=>'white', -activebackground => 'white', ); }, -bg => 'white', -font => 'big', )->pack; my $quit = $mw->Button(-text => 'Quit', -command => sub { print "Final value=$foo.\n"; exit; })->pack; # a simple MainLoop; sub store_callback { print "In store_callback, self=$_[0], new_value=$_[1].\n"; $testbutton->configure( -state => 'normal', -bg => 'yellow', -activebackground => 'yellow', ); $_[0]->Store($_[1]); }

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh