bind(3pm)

πŸ’– bind(3pm) β€” Tk::bind πŸ’–

okay bestie, gather round, because this is the Perl/Tk bind page and it is a lot, but in the best way. it lives in the User Contributed Perl Documentation section of the manual, and it's literally the thing that makes your widgets actually do stuff when you poke them. main character energy fr fr. ✨


✨ NAME ✨

Tk::bind β€” arrange for X events to invoke callbacks

like. that's it. that's the whole job. you say "when this happens, run this code," and Tk goes "say less." πŸ’…


🌸 SYNOPSIS 🌸

Retrieve bindings:

$widget->bind

$widget->bind(tag)

$widget->bind(sequence)

$widget->bind(tag,sequence)

Associate and destroy bindings:

$widget->bind(sequence,callback)

$widget->bind(tag,sequence,callback)

see how the callback just... shows up at the end and everything changes? iconic. πŸ‘‘


πŸ¦‹ DESCRIPTION πŸ¦‹

so the bind method is the matchmaker between callbacks and X events. if you pass a callback, bind will arrange for that callback to be evaluated whenever the event(s) given by sequence happen in the window(s) identified by $widget or tag. match made in heaven. πŸ’–

if callback is an empty string, then the current binding for sequence is destroyed, leaving sequence unbound. (yes, that's the breakup. it's giving no-contact. πŸ₯€)

in all of the cases where a callback argument is provided, bind returns an empty string. nothing. void. the empty string is the vibe.

if sequence is specified without a callback, then the callback currently bound to sequence is returned β€” or undef is returned if there's no binding for sequence. and if you specify neither sequence nor callback, then the return value is a list whose elements are all the sequences for which there exist bindings for tag. it's giving "show me everything you've got." ✨

if no tag is specified, then the bind refers to $widget. if tag is specified, then it's typically a class name, and the bind refers to all instances of the class on the MainWindow associated with $widget.

🚨 okay lowkey important: it is possible for tag to be another "widget object", but this practice is deprecated. bestie. don't. πŸ™ˆ

Perl's ref($object) can be used to get the class name of any object. each window has an associated list of tags, and a binding applies to a particular window if its tag is among those specified for the window. and although the bindtags method may be used to assign an arbitrary set of binding tags to a window, the default binding tags provide the following behavior:

  • if a tag is the name of an internal window, the binding applies to that window.
  • if the tag is the name of a toplevel window, the binding applies to the toplevel window and all its internal windows.
  • if the tag is the name of a class of widgets, such as Tk::Button, the binding applies to all widgets in that class;
  • if tag has the value all, the binding applies to all windows descended from the MainWindow of the application. (the whole tree. the entire bloodline. πŸ‘‘)

🌈 EVENT PATTERNS 🌈

the sequence argument specifies a sequence of one or more event patterns, with optional white space between the patterns. each event pat takes one of three forms. let's go.

form 1 β€” the baby one. in the simplest case it's a single printing ASCII character, like a or [. the character may not be a space character or the character <. this form of pattern matches a KeyPress event for that particular character.

form 2 β€” the glow-up. longer, but way more general. it has this syntax:

'<modifier-modifier-type-detail>'

the entire event pattern is surrounded by angle brackets, and normally needs to be quoted, because angle brackets are special to perl. (perl said "those are mine now." 😭)

inside the angle brackets you've got zero or more modifiers, an event type, and an extra piece of information (detail) identifying a particular button or keysym. any of the fields may be omitted, as long as at least one of type and detail is present. the fields must be separated by white space or dashes.

form 3 β€” the virtual one. this form of pattern specifies a user-defined, named virtual event; see Tk::event for details. it has this syntax:

'<<name>>'

the entire virtual event pattern is surrounded by double angle brackets. inside the angle brackets is the user-defined name of the virtual event. modifiers, such as Shift or Control, may not be combined with a virtual event to modify it β€” no mixing, no remixing, it said what it said. πŸ’…

bindings on a virtual event may be created before the virtual event is defined, and if the definition of a virtual event changes dynamically, all windows bound to that virtual event will respond immediately to the new definition. flexible AND responsive. slay. ✨


πŸ’œ MODIFIERS πŸ’œ

modifiers consist of any of the following values:

  • Control
  • Shift
  • Lock
  • Button1, B1
  • Button2, B2
  • Button3, B3
  • Button4, B4
  • Button5, B5
  • Mod1, M1
  • Mod2, M2
  • Mod3, M3
  • Mod4, M4
  • Mod5, M5
  • Meta, M
  • Alt
  • Double
  • Triple
  • Quadruple

where more than one value is listed, separated by commas, the values are equivalent. so don't come at me about B1 vs Button1, they're the same girl. 🫢

most of the modifiers have the obvious X meanings. for example, Button1 requires that button 1 be depressed when the event occurs. for a binding to match a given event, the modifiers in the event must include all of those specified in the event pattern. an event may also contain additional modifiers not specified in the binding.

for example, if button 1 is pressed while the shift and control keys are down, the pattern <Control-Button-1> will match the event, but <Mod1-Button-1> will not.

if no modifiers are specified, then any combination of modifiers may be present in the event. it's giving "i'm not picky." 🌸

Meta and M refer to whichever of the M1 through M5 modifiers is associated with the meta key(s) on the keyboard (keysyms Meta_R and Meta_L). if there are no meta keys, or if they are not associated with any modifiers, then Meta and M will not match any events. similarly, the Alt modifier refers to whichever modifier is associated with the alt key(s) on the keyboard (keysyms Alt_L and Alt_R).

the Double, Triple and Quadruple modifiers are a convenience for specifying double mouse clicks and other repeated events. they cause a particular event pattern to be repeated 2, 3 or 4 times, and also place a time and space requirement on the sequence: for a sequence of events to match a Double, Triple or Quadruple pattern, all of the events must occur close together in time and without substantial mouse motion in between.

for example, <Double-Button-1> is equivalent to <Button-1><Button-1> with the extra time and space requirement. same energy, stricter standards. πŸ’…


πŸŽ€ EVENT TYPES πŸŽ€

the type field may be any of the standard X event types, with a few extra abbreviations. below is the list of all the valid types; where two names appear together, they are synonyms:

  • Activate
  • ButtonPress, Button
  • ButtonRelease
  • Circulate
  • CirculateRequest
  • Colormap
  • Configure
  • ConfigureRequest
  • Create
  • Deactivate
  • Destroy
  • Enter
  • Expose
  • FocusIn
  • FocusOut
  • Gravity
  • KeyPress, Key
  • KeyRelease
  • Leave
  • Map
  • MapRequest
  • Motion
  • MouseWheel
  • Property
  • Reparent
  • ResizeRequest
  • Unmap
  • Visibility

most of the above events have the same fields and behaviors as events in the X Windowing system. you can find more detailed descriptions of these events in any X window programming book. a couple of the events are extensions to the X event system to support features unique to the Macintosh and Windows platforms. we provide a little more detail on these events here. these include:

⭐ Activate / Deactivate

these two events are sent to every sub-window of a toplevel when they change state. in addition to the focus Window, the Macintosh platform and Windows platforms have a notion of an active window (which often has but is not required to have the focus). on the Macintosh, widgets in the active window have a different appearance than widgets in deactive windows.

the Activate event is sent to all the sub-windows in a toplevel when it changes from being deactive to active. likewise, the Deactivate event is sent when the window's state changes from active to deactive.

there are no useful percent substitutions you would make when binding to these events. none. zero. don't go looking. 😭

πŸ“ MouseWheel

some mice on the Windows platform support a mouse wheel which is used for scrolling documents without using the scrollbars. by rolling the wheel, the system will generate MouseWheel events that the application can use to scroll.

like Key events, the event is always routed to the window that currently has focus. when the event is received you can use the %D substitution to get the delta field for the event, which is an integer value of motion that the mouse wheel has moved. the smallest value for which the system will report is defined by the OS. on Windows 95 & 98 machines this value is at least 120 before it is reported. however, higher resolution devices may be available in the future.

the sign of the value determines which direction your widget should scroll: positive values should scroll up and negative values should scroll down. ⬆️⬇️


πŸ”₯ the detail field πŸ”₯

the last part of a long event specification is detail.

in the case of a ButtonPress or ButtonRelease event, it's the number of a button (1-5). if a button number is given, then only an event on that particular button will match; if no button number is given, then an event on any button will match.

🚨 Note: giving a specific button number is different than specifying a button modifier. in the first case, it refers to a button being pressed or released, while in the second it refers to some other button that is already depressed when the matching event occurs. two completely different situations bestie, don't confuse them. πŸ’€

if a button number is given then type may be omitted: it will default to ButtonPress. for example, the specifier <1> is equivalent to <ButtonPress-1>.

if the event type is KeyPress or KeyRelease, then detail may be specified in the form of an X keysym. keysyms are textual specifications for particular keys on the keyboard; they include all the alphanumeric ASCII characters (e.g. a'' is the keysym for the ASCII character a''), plus descriptions for non-alphanumeric characters (comma'' is the keysym for the comma character), plus descriptions for all the non-ASCII keys on the keyboard (Shift_L'' is the keysym for the left shift key, and ``F1'' is the keysym for the F1 function key, if it exists).

the complete list of keysyms is not presented here; it is available in other X documentation and may vary from system to system. if necessary, you can use the K notation described below to print out the keysym name for a particular key. πŸ”

if a keysym detail is given, then the type field may be omitted; it will default to KeyPress. for example, <Control-comma> is equivalent to <Control-KeyPress-comma>.

πŸ’– BINDING CALLBACKS AND SUBSTITUTIONS πŸ’–

okay so bestie, that callback argument you hand to bind? It's a perl/Tk callback, and it fires every single time the event sequence you specified happens. (If you wanna know all the shapes a callback can take, go read Tk::callbacks, she explains it better than I ever could.) πŸ’…

The callback gets tied to the same MainWindow that's associated with the $widget you called bind on, and it runs exactly as if it had been called from MainLoop. Cute, right? ✨

Now here's the spicy part: if your callback has any Ev(%) calls in it, then each one of those "nested" Ev(%) "callbacks" gets evaluated at the moment the event happens, and whatever they spit out becomes the arguments passed to the main callback. What actually gets substituted depends on the character after the %, and the whole list is right below. Unless it says otherwise, the replacement string is the numeric (decimal) value of that field from the current event.

Perl/Tk has enhanced this mechanism slightly compared to the comparable Tcl/Tk mechanism. The enhancements are not yet all reflected in the list below. πŸ‘€

⚠️ Some of these substitutions only work for certain event types. If you use one for an event type it doesn't belong to, the value substituted is undefined β€” and no, that is not the same as undef! 😭 Not a vibe. Don't do it.

  • '#' β€” the number of the last client request processed by the server (the serial field from the event). Valid for all event types. πŸŽ€
  • 'a' β€” the above field from the event, formatted as a hexadecimal number. Valid only for Configure events.
  • 'b' β€” the number of the button that was pressed or released. Valid only for ButtonPress and ButtonRelease events.
  • 'c' β€” the count field from the event. Valid only for Expose events.
  • 'd' β€” the detail field from the event. The 'd' gets replaced by a string identifying the detail. For Enter, Leave, FocusIn, and FocusOut events, that string will be one of these:
NotifyAncestor          NotifyNonlinearVirtual
NotifyDetailNone        NotifyPointer
NotifyInferior          NotifyPointerRoot
NotifyNonlinear         NotifyVirtual

And for ConfigureRequest events, it'll be one of these:

Above                   Opposite
Below                   None
BottomIf                TopIf

For events other than those, the substituted string is undefined. (And psst β€” note that this is not the same as the Detail part of the sequence you use to specify the event. Different thing entirely, bestie. πŸ™ˆ)

  • 'f' β€” the focus field from the event (0 or 1). Valid only for Enter and Leave events.
  • 'h' β€” the height field from the event. Valid only for Configure, ConfigureRequest, Create, Expose, and ResizeRequest events.
  • 'i' β€” the window field from the event, represented as a hexadecimal integer.
  • 'k' β€” the keycode field from the event. Valid only for KeyPress and KeyRelease events.
  • 'm' β€” the mode field from the event. The substituted string is one of NotifyNormal, NotifyGrab, NotifyUngrab, or NotifyWhileGrabbed. Valid only for Enter, FocusIn, FocusOut, and Leave events.
  • 'o' β€” the override_redirect field from the event. Valid only for Map, Reparent, and Configure events.
  • 'p' β€” the place field from the event, substituted as one of the strings PlaceOnTop or PlaceOnBottom. Valid only for Circulate and CirculateRequest events.
  • 's' β€” the state field from the event. For ButtonPress, ButtonRelease, Enter, KeyPress, KeyRelease, Leave, and Motion events, a decimal string is substituted. For Visibility, one of the strings VisibilityUnobscured, VisibilityPartiallyObscured, and VisibilityFullyObscured is substituted instead. 🌈
  • 't' β€” the time field from the event. Valid only for events that contain a time field.
  • 'w' β€” the width field from the event. Valid only for Configure, ConfigueRequest, Create, Expose, and ResizeREquest events.
  • 'x' β€” the x field from the event. Valid only for events containing an x field.
  • 'y' β€” the y field from the event. Valid only for events containing a y field.
  • '@' β€” the string "@x,y" where x and y are as above. Valid only for events containing x and y fields. This format is used my methods of Tk::Text and similar widgets.
  • 'A' β€” substitutes the UNICODE character corresponding to the event, or the empty string if the event doesn't correspond to a UNICODE character (e.g. the shift key was pressed). XmbLookupString does all the work of translating from the event to a UNICODE character. Valid only for KeyPress and KeyRelease events. πŸ¦‹
  • 'B' β€” the border_width field from the event. Valid only for Configure, ConfigureRequest and Create events.
  • 'D' β€” this reports the delta value of a MouseWheel event. The delta value represents the rotation units the mouse wheel has been moved. On Windows 95 & 98 systems the smallest value for the delta is 120. Future systems may support higher resolution values for the delta. The sign of the value represents the direction the mouse wheel was scrolled. πŸ”₯
  • 'E' β€” the send_event field from the event. Valid for all event types.
  • 'K' β€” the keysym corresponding to the event, substituted as a textual string. Valid only for KeyPress and KeyRelease events.
  • 'N' β€” the keysym corresponding to the event, substituted as a decimal number. Valid only for KeyPress and KeyRelease events.
  • 'R' β€” the root window identifier from the event. Valid only for events containing a root field.
  • 'S' β€” the subwindow window identifier from the event, as an object if it is one, otherwise as a hexadecimal number. Valid only for events containing a subwindow field.
  • 'T' β€” the type field from the event. Valid for all event types.
  • 'W' β€” the window to which the event was reported (the $widget field from the event) β€” as a perl/Tk object. Valid for all event types. πŸ‘‘
  • 'X' β€” the x_root field from the event. If a virtual-root window manager is being used then the substituted value is the corresponding x-coordinate in the virtual root. Valid only for ButtonPress, ButtonRelease, KeyPress, KeyRelease, and Motion events.
  • 'Y' β€” the y_root field from the event. If a virtual-root window manager is being used then the substituted value is the corresponding y-coordinate in the virtual root. Valid only for ButtonPress, ButtonRelease, KeyPress, KeyRelease, and Motion events.

🌸 MULTIPLE MATCHES 🌸

So like… it is genuinely possible for several bindings to match one single X event. And when that happens, things get interesting. πŸ’…

If those bindings are associated with different tag's, then each of them gets executed, in order. By default the order goes:

  1. a class binding first,
  2. then a binding for the widget,
  3. then a binding for its toplevel,
  4. and then an all binding.

And if you want to mess with that? The bindtags method is literally right there β€” use it to change the order for a particular window, or to associate additional binding tags with the window. Slay. ✨

return and Tk->break can be used inside a callback to control the processing of matching callbacks:

  • If return is invoked, the current callback terminates, but Tk keeps going and processes callbacks associated with other tag's. Politely stepping aside, iconic behaviour. πŸŽ€
  • If Tk->break is invoked within a callback, then that callback terminates and no other callbacks will be invoked for the event. Full stop. Periodt.

(Tk->break is implemented via perl's die with a special value which is "caught" by the perl/Tk "glue" code. Sneaky but valid. 😌)

Now, if more than one binding matches a particular event and they have the same tag, then the most specific binding is chosen and its callback is evaluated. Here's the test order to figure out which matching sequence is more specific:

  • (a) an event pattern that specifies a specific button or key is more specific than one that doesn't;
  • (b) a longer sequence (in terms of number of events matched) is more specific than a shorter sequence;
  • (c) if the modifiers specified in one pattern are a subset of the modifiers in another pattern, then the pattern with more modifiers is more specific.
  • (d) a virtual event whose physical pattern matches the sequence is less specific than the same physical pattern that is not associated with a virtual event.
  • (e) given a sequence that matches two or more virtual events, one of the virtual events will be chosen, but the order is undefined.
😭 If the matching sequences contain more than one event, then tests (c)-(e) are applied in order from the most recent event to the least recent event in the sequences. And if these tests still fail to determine a winner? Then the most recently registered sequence wins. Coin flip energy but make it deterministic.

And here's a truly unhinged one: if there are two (or more) virtual events that are both triggered by the same sequence, and both of those virtual events are bound to the same window tag, then only one of the virtual events will be triggered β€” and it will be picked at random:

$widget->eventAdd('<<Paste>>' => '<Control-y>');
$widget->eventAdd('<<Paste>>' => '<Button-2>');
$widget->eventAdd <<Scroll>>' => '<Button-2>');
$widget->bind('Tk::Entry','<<Paste>>',sub { print 'Paste'});
$widget->bind('Tk::Entry','<<Scroll>>', sub {print 'Scroll'});

If the user types Control-y, the <<Paste>> binding will be invoked. But if the user presses button 2, then one of either the <<Paste>> or the <<Scroll>> bindings will be invoked β€” and exactly which one gets invoked is undefined. πŸ’€ Bestie, that's just how it is.

And if an X event does not match any of the existing bindings? The event is simply ignored. An unbound event is not considered to be an error. Relax, you're fine. 🫢


πŸ¦‹ MULTI-EVENT SEQUENCES AND IGNORED EVENTS πŸ¦‹

When a sequence you specified in a bind method contains more than one event pattern, then its callback is executed whenever the recent events (leading up to and including the current event) match the given sequence.

So for example: if button 1 is clicked repeatedly, the sequence <Double-ButtonPress-1> will match each button press but the first. Yeah. 🀯

Now, if extraneous events that would prevent a match occur in the middle of an event sequence, then those extraneous events are ignored β€” unless they are KeyPress or ButtonPress events. For example, <Double-ButtonPress-1> will match a sequence of presses of button 1, even though there will be ButtonRelease events (and possibly Motion events) between the ButtonPress events. See, it's chill like that. ✨

Furthermore, a KeyPress event may be preceded by any number of other KeyPress events for modifier keys without the modifier keys preventing a match. For example, the event sequence aB will match a press of the a key, a release of the a key, a press of the Shift key, and a press of the b key: the press of Shift is ignored because it is a modifier key. Modifier keys really said "not me participating." πŸ™ˆ

Finally β€” and this one is lowkey important β€” if several Motion events occur in a row, only the last one is used for purposes of matching binding sequences. 🎯


πŸ’œ ERRORS πŸ’œ

If an error occurs while executing the callback for a binding, then the Tk::Error mechanism is used to report the error. And that Tk::Error mechanism will be executed at the same call level, and associated with the same MainWindow, as as the callback was invoked. πŸ’–

🚨 CAVEATS 🚨

okay bestie, listen up, this one is actually important and it has bitten literally everyone at least once πŸ’€

So like, for the Canvas widget specifically, the call to bind has to be fully qualified. Fully. Qualified. No shortcuts, no vibes-based hoping it works.

Why?? Because Canvas already has its own bind method β€” one that binds individual canvas tags, not events. So if you just call bind all willy-nilly on a canvas, you're not talking to Tk::bind at all, you're talking to the canvas-tag one. Rude, honestly. πŸ™ˆ

The fix, and I need you to write this down:

$canvas->Tk::bind

That's it. That's the whole thing. You prefix it with Tk:: and suddenly the right method shows up to the party. Namespace slay. πŸ’…

fr fr do not skip this. If your canvas bindings are acting possessed and nothing fires the way you expect, it's probably this. It's always this. 😭

🌈 SEE ALSO 🌈

go read these next, they're the supporting cast and they ate:

  • Tk::Error
  • Tk::callbacks
  • Tk::bindtags

πŸ”‘ KEYWORDS πŸ”‘

Event, binding

that's the whole vibe, that's the whole page ✨


and that's a wrap on bind(3pm)!! πŸŽ€ thank you for coming to my ted talk, you're now legally a binding expert, no cap πŸ‘‘

this absolute icon of a page ships with perl v5.40.1, dated 2025-04-13, and it's the bind(3pm) page itself πŸ’–

go forth and bind responsibly, bestie πŸ¦‹πŸŒΈ

πŸ“¦ where this page comes from