Perl/Tk saves your favourite tools

Main
back: Tk canvas
next: Tk bind -1

(source) Entry uses a tie to capture the value of the variable. A change to the variable from the program will cause the tied Entry-widget to update the value on the screen.

The -command defines a callback. Callbacks are used to respond to user-actions, in this case the user who is pushing the button. Callbacks are hard to program exactly right; you have to understand Perl very well to distinguish between different formulations:


-command => $c->move($l, $x, $y)
The move command is called on the moment that the options for the button is collected: when the button is generated. The line will appear on the screen in its moved position (remember that the window will not be drawn before MainLoop is reached).
Pushing the button will result in an error, because the result of move will not be a valid callback (you hope).

-command => [ 'move', $l, $x, $y ]
The definition of callbacks says that this will be translated into: $button->move($l, $x, $y) when the button is pushed. This not correct, because you need to call move on canvas. In most case where you write a callback, this notation is useful, but not in this case.

Next to that, keep in mind that the values of $l, $x, and $y are substituted on the moment of definition: the line will always move over (15, 10).

-command => [ 'move', $c, $l, $x, $y ]
This doesn't help much: the move will still be called on a button, but it is not a defined operation for a button.

-command => [ $c, 'move', $l, $x, $y ]
If this callback was used in a bind, which will be discussed later, than this would be a valid choice: bind looks if the first argument of the list is an object. If so, it calls the method on that object. Mind however, that we are still moving over a constant (15,10).

-command => [ sub {$c->move($l, @_)}, $x, $y ]
In this case, the move will always be over (15, 10), but $l will be used with the value on moment of the call.

Perl keeps the value of a variable alive as long as it can be accessed, even when the variable is a my and you leave the enclosing code-block (for instance the subroutine). Each my $l will result in a distinct variable.

-command => sub {$c->move($l, $x, $y)}
The last example finally achieves our goal: call the subroutine when the button is pushed. The move uses the actual values stored in $l, $x, and $y

-command => [ sub {$_[0]->move($_[1], $x, $y)}, $c, $l ]
An even better notation. In this case, I can reuse $c and $l for creating more objects. Both are shown to be constants. Of course, this is equivalent with:
   -command => [ sub { my ($c, $l) = @_;
                       $c->move($l, $x, $y)}
               , $c, $l ]

 
Tk canvas Tk bind -1

Created by Mark Overmeer with PPresenter on 11 juli 2001.