in reply to Tk Bind scalar
You can cheat by using a hidden (unmapped) widget which watches its bound variable. The likeliest victim would probably be a Tk::Entry.
sub watch_variable { my( $mainwindow, $scalarref, $coderef ) = @_; $mainwindow->Entry( -textvariable => $scalarref, -validate => 'all', -validatecommand => sub { $coderef->( $_[0] ); 1 }, ); }
Here's a little demo program:
use Tk; use strict; use warnings; my $mw = new MainWindow; my $var; watch_variable( $mw, \$var, sub { warn "val = $_[0]\n" } ); $mw->Button( -text => "Incr", -command => sub { $var++ } )->pack; $mw->Button( -text => "Set 5", -command => sub { $var = 5 } )->pack; $mw->Button( -text => "Exit", -command => sub { exit } )->pack; MainLoop; sub watch_variable { my( $mainwindow, $scalarref, $coderef ) = @_; $mainwindow->Entry( -textvariable => $scalarref, -validate => 'all', -validatecommand => sub { $coderef->( $_[0] ); 1 }, ); }
Note that the callback is only called when the value of the variable is changed, which is not necessarily every time it is assigned to.
Also note that if the variable has a defined value at the time you call watch_variable (i.e., technically, at the time you tell the Entry widget to watch it), you will get a callback on it immediately, since it is detected as a change from the initial value, which is undef.
I think both of these may be the desired behaviors... depending on your app.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Tk Bind scalar
by skywalker (Beadle) on Feb 20, 2009 at 20:25 UTC | |
by jdporter (Paladin) on Feb 20, 2009 at 21:25 UTC | |
by zentara (Cardinal) on Feb 20, 2009 at 21:31 UTC | |
by jdporter (Paladin) on Feb 20, 2009 at 21:37 UTC | |
by zentara (Cardinal) on Feb 20, 2009 at 21:50 UTC | |
| |
by zentara (Cardinal) on Feb 20, 2009 at 21:20 UTC |