Binding to Events

When creating a Button instance, the -command option specifies the callback to invoke when the user presses the Button. The button press must be button 1, because that’s the Button’s documented behavior. As a convenience, the Button constructor automatically creates the link between the button 1 press and our callback using the bind command. If it didn’t, we’d have to do it manually for every Button we create, using syntax similar to this:

$button->bind('<ButtonRelease-1>' => callback);

If nothing else, -command => callback is fewer characters to type, but it also provides consistency, because the Button always reacts to the first button, not whatever button the programmer decided to use.

In the previous bind command, the string <ButtonRelease-1> is know as an event descriptor. It’s composed of two fields enclosed in angle brackets, the event type and the event detail. In the case of a ButtonRelease event type, the detail portion specifies which button we are interested in. The event descriptor in this example is very specific: it invokes the callback only when button 1 is released over the Button widget (as opposed to when it’s pressed). If you watch a Button closely, pressing button 1 only changes the widget’s relief from raised to sunken. If you move the cursor away from the Button, the relief changes back, but the widget’s callback is never invoked.

Event Descriptor Syntax

An event descriptor can be more complex than our first example; it can actually be ...

Get Mastering Perl/Tk now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.