bind(3tk)

πŸ“¦
version 9.0.4 Β· 3 versions
, in debian trixie, ubuntu questing, ubuntu resolute, ubuntu stonking

✨ bind(3tk) β€” Tk Built-In Commands ✨

okay bestie, welcome to the bind page, you're gonna eat this up πŸ’…


🌸 NAME 🌸

bind β€” the way you make X events run Tcl scripts. that's it, that's the whole vibe πŸŽ€


πŸ¦‹ SYNOPSIS πŸ¦‹

bind tag ?sequence? ?+??script?

πŸ’– INTRODUCTION πŸ’–

so, the bind command is literally the matchmaker between Tcl scripts and X events. here's the tea:

if you give it all three arguments, bind arranges for script β€” a Tcl script, also known as the binding script β€” to be evaluated whenever the event(s) given by sequence happen in the window(s) identified by tag.

now the lil + detail, because it matters:

  • if script starts with a +, it gets appended to whatever binding already exists for sequence 🫢
  • otherwise, script replaces any existing binding. no mercy.
  • if script is an empty string, the current binding for sequence is destroyed, leaving sequence unbound πŸ’€

and in every single one of those cases where you actually hand over a script argument? bind returns an empty string. nothing. silence. iconic behaviour honestly.


if you give a sequence without a script, you get back the script currently bound to that sequence. and if there's no binding for it? you get an empty string. sorry babe 😭

if you give it neither sequence nor script, the return value is a list whose elements are all the sequences for which there exist bindings for tag. a whole roster. ✨


okay so the tag argument decides which window(s) the binding applies to. real simple rules:

  • if tag begins with a dot, like .a.b.c, then it must be the path name for a window.
  • otherwise, it can be any arbitrary string you want.

every window has an associated list of tags, and a binding applies to a particular window if its tag is among those specified for that window. and yeah, bindtags can assign an arbitrary set of binding tags to a window, but the default binding tags give you this behaviour:

  • If a tag is the name of an internal window, the binding applies to that window. πŸͺŸ
  • If the tag is the name of a class of widgets, such as Button, the binding applies to all widgets in that class. πŸ‘‘
  • If the tag is the name of a toplevel window, the binding applies to the toplevel window and all its internal windows. 🌈
  • If tag has the value all, the binding applies to all windows in the application. periodt.

🌟 EVENT PATTERNS 🌟

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

form one β€” the simplest. it's just a single printing ASCII character, like a or [. the character may not be a space character, and it may not be the character <. this form of pattern matches a Key event for that particular character. easy.

form two β€” longer but way more general. syntax goes like this:

<modifier-modifier-type-detail>

the whole event pattern is wrapped in angle brackets. inside those angle brackets you've got zero or more modifiers, an event type, and an extra piece of info (the detail) identifying a particular button or keysym. any of the fields can be omitted, as long as at least one of type and detail is present. and the fields have to be separated by white space or dashes. 🫢

form three β€” for user-defined, named virtual events. syntax:

<<name>>

whole virtual event pattern is wrapped in double angle brackets. inside is the user-defined name of the virtual event. and here's the rule, bestie: modifiers like Shift or Control may not be combined with a virtual event to modify it. nope. πŸ™ˆ

but here's the cute part: bindings on a virtual event can be created before the virtual event is even 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. slay.

also, some widgets (e.g. menu and text) issue virtual events when their internal state is updated in some ways. check the manual page for each widget for the details. πŸ’œ

πŸŽ€ MODIFIERS πŸŽ€

modifiers consist of any of the following values:

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

where more than one value is listed, separated by commas, the values are equivalent. most of the modifiers have the obvious X meanings. for example, Button1 requires that button 1 be depressed when the event occurs.

and now the matching rules, because this is where people get got:

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.


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're 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 lil 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 they 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. so like, <Double-Button-1> is equivalent to <Button-1><Button-1> with the extra time and space requirement. ✨


the Command, Option, Num and Fn modifiers are equivalents of Mod1 up to Mod4; they correspond to Macintosh-specific modifier keys. πŸ“


the Extended modifier is, at present, specific to Windows. it appears on events that are associated with the keys on the "extended keyboard". on a US keyboard, the extended keys include:

  • the Alt and Control keys at the right of the keyboard
  • the cursor keys in the cluster to the left of the numeric pad
  • the NumLock key
  • the Break key
  • the PrintScreen key
  • the / and Enter keys in the numeric keypad

⭐ EVENT TYPES ⭐

the type field may be any of the standard X event types, with a few extra abbreviations. it'll also accept a couple of non-standard X event types that were added to better support the Macintosh and Windows platforms. below is the full list of all the valid types β€” where two names appear together, they're synonyms:

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

most of the above events have the same fields and behaviours 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 them are extensions to the X event system, added to support features unique to the Macintosh and Windows platforms. we're giving you a lil more detail on those ones right here:

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 Deactive event is sent when the window's state changes from active to deactive. and ngl, there are no useful percent substitutions you'd make when binding to these events. πŸ™ˆ

MouseWheel β€” many contemporary mice include a mouse wheel, used for scrolling documents without touching the scrollbars. by rolling the wheel, the system generates MouseWheel events that the application can use to scroll. the event is routed to the window currently under the mouse pointer. when the event is received you can use the %D substitution to get the delta field for the event, which is an integer value describing how the mouse wheel has moved. the smallest value for which the system will report is defined by the OS. the sign of the value determines which direction your widget should scroll: positive values should scroll up, negative values should scroll down. 🫢

horizontal scrolling uses Shift-MouseWheel events, with a positive %D delta substitution indicating left scrolling and negative indicating right scrolling. horizontal scrolling events are generated by tilt wheels on some mice. horizontal scrolling can also be emulated by holding Shift and scrolling vertically. ✨

TouchpadScroll β€” on some platforms (currently Windows and macOS) there's support for high-resolution scrolling devices, such as touchpads. this is provided via TouchpadScroll events. these events store two 16 bit delta values in the integer provided by the %D substitution. the X delta is in the high order 16 bits and the Y delta is in the low order 16 bits. these values can be unpacked by using the tk::PreciseScrollDeltas utility procedure. for example:

lassign [tk::PreciseScrollDeltas %D] deltaX deltaY

the $# substitution is a counter for TouchpadScroll events, which can be used by widgets that only support scrolling by units to ignore some portion of the events.

KeyPress, KeyRelease β€” the KeyPress and KeyRelease events are generated whenever a key is pressed or released. KeyPress and KeyRelease

Key, KeyRelease β€” the Key and KeyRelease events are generated whenever a key is pressed or released. Key and KeyRelease events are sent to the window which currently has the keyboard focus. ⌨️

Button, ButtonRelease, Motion πŸ’†β€β™€οΈ

Button and ButtonRelease events? They pop off when the user presses or releases a mouse button, respectively. And Motion events are generated <em>whenever</em> the pointer moves, bestie. All three are normally sent to the window that contains the pointer. Simple. Clean. Iconic.

But here's the tea πŸ«–: when a mouse button gets pressed, the window containing the pointer automatically obtains a temporary pointer grab. Which means all the subsequent Button, ButtonRelease and Motion events get sent to that window β€” no matter which window the pointer is actually over β€” right up until all the buttons have been released. It's giving "this window is the main character now". πŸ‘‘

Configure ✨

A Configure event gets sent to a window whenever its size, position, or border width changes. And <em>sometimes</em> when it has changed position in the stacking order too. Lowkey mysterious, highkey useful.

Map, Unmap πŸ—ΊοΈ

Map and Unmap events are generated whenever the mapping state of a window changes. That's the whole vibe.

So here's how windows are born: they're created in the unmapped state. Top-level windows become mapped when they transition to the normal state, and they're unmapped in the withdrawn and iconic states. Other windows become mapped when they get placed under the control of a geometry manager β€” think pack or grid, the usual suspects. πŸŽ€

A window is only viewable if it <em>and all of its ancestors</em> are mapped. Ancestors included, no exceptions, periodt. And note this: geometry managers typically don't map their children until they've been mapped themselves, and they unmap all their children when they become unmapped. So in Tk, Map and Unmap events are basically telling you whether or not a window is viewable. iykyk. πŸ‘€

Visibility 🫣

A window is said to be obscured when another window above it in the stacking order fully or partially overlaps it. Visibility events are generated whenever a window's obscurity state changes, and the state field (%s) tells you the new state. That's it, that's the whole event.

Expose 🎨

An Expose event is generated whenever all or part of a window should be redrawn β€” like when a window is first mapped, or when it becomes unobscured and needs to show its face again. ✨

Good news though: client applications normally do <em>not</em> need to handle Expose events, because Tk handles them internally. Not your problem, bestie. Tk's got it. πŸ’…

Destroy πŸ’€

A Destroy event is delivered to a window when it gets destroyed. RIP to that window fr fr. πŸͺ¦

But listen β€” when the Destroy event is delivered to a widget, that widget is in a β€œhalf-dead” state. Like, the widget still exists, but any operation that involves it may return invalid results, or just straight up return an error. It's giving haunted house energy. Be careful with it. 😭

FocusIn, FocusOut 🎯

FocusIn and FocusOut events are generated whenever the keyboard focus changes. A FocusOut event is sent to the <em>old</em> focus window, and a FocusIn event is sent to the <em>new</em> one. Passing the crown, basically. πŸ‘‘

Also β€” and this part is sneaky β€” if the old and new focus windows don't share a common parent, then β€œvirtual crossing” focus events get sent to the intermediate windows in the hierarchy. So a FocusIn event means the target window or one of its descendants has acquired the focus. And a FocusOut event means the focus has been changed to a window outside the target window's hierarchy. So much clearer now, right? πŸ¦‹

The keyboard focus can be changed explicitly by calling focus, or implicitly by the window manager. Both are valid. Both are valid.

Enter, Leave πŸšͺ

An Enter event is sent to a window when the pointer enters that window, and a Leave event is sent when the pointer leaves it. Come in, go out, slay. ✨

But heads up: if there's a pointer grab in effect, then Enter and Leave events are only delivered to the window owning the grab. Everyone else is left on read. πŸ™ˆ

And same as before β€” when the pointer moves between two windows, Enter and Leave β€œvirtual crossing” events are sent to intermediate windows in the hierarchy, in exactly the same manner as for FocusIn and FocusOut events. Consistency? We love to see it. πŸ’–

Property 🏷️

A Property event is sent to a window whenever an X property belonging to that window is changed or deleted. But β€” and this is the important bit β€” Property events are <em>not</em> normally delivered to Tk applications, because the Tk core handles them. Not your business, not your problem. πŸŽ€

Colormap 🌈

A Colormap event is generated whenever the colormap associated with a window has been changed, installed, or uninstalled. Three whole situations, all of them count.

Widgets may be assigned a private colormap by specifying a -colormap option, and the window manager is the one responsible for installing and uninstalling colormaps as necessary. Not you. The window manager. Let it do its job. πŸ’…

And just so you know: Tk provides no useful details for this event type. That's not me being shady, that's literally what the docs say. 🫢

MapRequest, CirculateRequest, ResizeRequest, ConfigureRequest, Create πŸ‘»

These events are <em>not</em> normally delivered to Tk applications. They're included here for completeness, so that it's actually possible to write X11 window managers in Tk. Yes, in Tk. People do that. Respect. πŸ‘‘

(These events are only delivered when a client has selected SubstructureRedirectMask on a window; the Tk core does not use this mask.)

Gravity, Reparent, Circulate πŸ”„

Gravity and Reparent are <em>not</em> normally delivered to Tk applications either. Included for completeness. That's the whole note. πŸ¦‹

A Circulate event indicates that the window has moved to the top or to the bottom of the stacking order as a result of an XCirculateSubwindows protocol request. But note this carefully, bestie:

  • The stacking order may be changed for other reasons which do <em>not</em> generate a Circulate event.
  • Tk does not use XCirculateSubwindows() internally.

So this event type is included only for completeness. There is no reliable way to track changes to a window's position in the stacking order. None. Don't try it. 😭


πŸ’– EVENT DETAILS πŸ’–

Okay so the last part of a long event specification is the detail. Let's break it down by type, because the rules are different depending on what you're matching. πŸŽ€

If the event is a Button or ButtonRelease event, then the detail is the number of a button, from 1 to 9. If a button number is given, then only an event on that particular button will match. If <em>no</em> button number is given, then an event on any button will match. Flexible. We love options. ✨

Note: giving a specific button number is different from specifying a button modifier. In the first case, it refers to a button being pressed or released. In the second case, it refers to some <em>other</em> button that is already depressed when the matching event occurs. Two totally different things, do not confuse them. πŸ™ˆ

Also, if a button number is given, then the type may be omitted β€” it will default to Button. So for example, the specifier <1> is equivalent to <Button-1>. Short and sweet. πŸ’…

Now, if the event type is Key or KeyRelease, then the detail may be specified in the form of an X keysym. Keysyms are textual specifications for particular keys on the keyboard. What's in there?

  • 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 β€” e.g. β€œ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 <em>not</em> presented here. It lives in other X documentation, and heads up β€” it may vary from system to system. 🌸

If you need it, you can use the %K notation described below to print out the keysym name for a particular key. And if a keysym detail is given, then the type field may be omitted β€” it will default to Key. For example, <Control-comma> is equivalent to <Control-Key-comma>. πŸ¦‹

✨ BINDING SCRIPTS AND SUBSTITUTIONS ✨

okay so bestie, when you pass a script argument to bind, that's your binding script πŸ’– and it gets run every single time the event sequence you set up actually happens. It runs in the same interpreter where the bind command was executed, and it runs at global level β€” meaning only global variables are accessible. No local-variable shenanigans, iykyk.

If script contains any % characters, then it does not get executed directly. Instead, a new script is generated by replacing each % and the character following it with information from the current event. The replacement depends on the character after the %, as defined in the list below. Unless otherwise indicated, the replacement string is the decimal value of the given field from the current event. Some substitutions are only valid for certain event types; if you use them for other types, the value substituted is undefined. 😭

  • %% β€” Replaced with a single percent.
  • %# β€” 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. Indicates the sibling window immediately below the receiving window in the stacking order, or 0 if the receiving window is at the bottom.
  • %b β€” The number of the button that was pressed or released. Valid only for Button and ButtonRelease events.
  • %c β€” The count field from the event. Valid only for Expose events. Indicates that there are count pending Expose events which have not yet been delivered to the window.
  • %d β€” The detail or user_data field from the event. The %d is replaced by a string identifying the detail. For Enter, Leave, FocusIn, and FocusOut events, the string will be one of: NotifyAncestor, NotifyNonlinearVirtual, NotifyDetailNone, NotifyPointer, NotifyInferior, NotifyPointerRoot, NotifyNonlinear, or NotifyVirtual. For ConfigureRequest events, the string will be one of: Above, Opposite, Below, None, BottomIf, or TopIf. For virtual events, the string will be whatever value is stored in the user_data field when the event was created (typically with event generate), or the empty string if the field is NULL. Virtual events corresponding to key sequence presses (see event add for details) set the user_data to NULL. For events other than these, the substituted string is undefined.
  • %f β€” The focus field from the event (0 or 1). Valid only for Enter and Leave events. 1 if the receiving window is the focus window or a descendant of the focus window, 0 otherwise.
  • %h β€” The height field from the event. Valid for the Configure, ConfigureRequest, Create, ResizeRequest, and Expose events. Indicates the new or requested height of the window.
  • %i β€” The window field from the event, represented as a hexadecimal integer. Valid for all event types.
  • %k β€” The keycode field from the event. Valid only for Key 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 Button, ButtonRelease, Enter, Key, KeyRelease, Leave, and Motion events, a decimal string is substituted. For Visibility, one of the strings VisibilityUnobscured, VisibilityPartiallyObscured, and VisibilityFullyObscured is substituted. For Property events, substituted with either the string NewValue (indicating that the property has been created or modified) or Delete (indicating that the property has been removed).
  • %t β€” The time field from the event. This is the X server timestamp (typically the time since the last server reset) in milliseconds, when the event occurred. Valid for most events.
  • %w β€” The width field from the event. Indicates the new or requested width of the window. Valid only for Configure, ConfigureRequest, Create, ResizeRequest, and Expose events.
  • %x, %y β€” The x and y fields from the event. For Button, ButtonRelease, Motion, Key, KeyRelease, and MouseWheel events, %x and %y indicate the position of the mouse pointer relative to the receiving window. For key events on the Macintosh these are the coordinates of the mouse at the moment when an X11 KeyEvent is sent to Tk, which could be slightly later than the time of the physical press or release. For Enter and Leave events, the position where the mouse pointer crossed the window, relative to the receiving window. For Configure and Create requests, the x and y coordinates of the window relative to its parent window.
  • %A β€” Substitutes the UNICODE character corresponding to the event, or the empty string if the event does not correspond to a UNICODE character (e.g. the shift key was pressed). On X11, XmbLookupString (or XLookupString when input method support is turned off) does all the work of translating from the event to a UNICODE character. On X11, valid only for Key event. On Windows and macOS/aqua, valid only for Key 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. 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. 0 indicates that this is a β€œnormal” event, 1 indicates that it is a β€œsynthetic” event generated by SendEvent.
  • %K β€” The keysym corresponding to the event, substituted as a textual string. Valid only for Key and KeyRelease events.
  • %M β€” The number of script-based binding patterns matched so far for the event. Valid for all event types.
  • %N β€” The keysym corresponding to the event, substituted as a decimal number. Valid only for Key and KeyRelease events.
  • %P β€” The name of the property being updated or deleted (which may be converted to an XAtom using winfo atom.) Valid only for Property 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, formatted 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 path name of the window to which the event was reported (the window field from the event). Valid for all event types.
  • %X, %Y β€” The x_root and y_root fields from the event. If a virtual-root window manager is being used then the substituted values are the corresponding x-coordinate and y-coordinate in the virtual root. Valid only for Button, ButtonRelease, Enter, Key, KeyRelease, Leave and Motion events. Same meaning as %x and %y, except relative to the (virtual) root window.

The replacement string for a %-replacement is formatted as a proper Tcl list element. This means that spaces or special characters such as $ and { may be preceded by backslashes. This guarantees that the string will be passed through the Tcl parser when the binding script is evaluated. Most replacements are numbers or well-defined strings such as Above; for these replacements no special formatting is ever necessary. The most common case where reformatting occurs is for the %A substitution. For example, if script is

insert %A

and the character typed is an open square bracket, then the script actually executed will be

insert \[

This will cause the insert to receive the original replacement string (open square bracket) as its first argument. If the extra backslash had not been added, Tcl would not have been able to parse the script correctly.

πŸ’– MULTIPLE MATCHES πŸ’–

Okay so bestie, imagine this: several bindings can all match the same X event. It's giving popular. πŸ’…

If those bindings are tied to different tag's, then every single one of them gets executed, in order. By default, the order is: the binding for the widget first, then a class binding, then a binding for its toplevel, and then an all binding. That's the default vibe.

The bindtags command is your bestie here β€” you can use it to change this order for a particular window, or to associate additional binding tags with the window. Slay.

Now, inside a binding script, you've got continue and break to control how matching scripts get processed. If continue is invoked within a binding script, then this binding script β€” including all other "+" appended scripts β€” is terminated, but Tk will keep processing binding scripts associated with other tag's. If break is invoked within a binding script, then that script terminates and no other scripts will be invoked for the event. Periodt.

Also, within a script called from the binding script, return -code ok may be used to continue processing (including "+" appended scripts), or return -code break may be used to stop processing all other binding scripts. Iconic.

If more than one binding matches a particular event and they have the same tag, then the most specific binding is chosen and its script is evaluated. The following tests are applied, in order, to determine which of several matching sequences is more specific:

  • (a) an event pattern that specifies a specific button or key is more specific than one that does not;
  • (b) a sequence with the most highest-ordered patterns (in term of highest repetition count) is more specific than a sequence with less highest-ordered patterns;
  • (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. If these tests fail to determine a winner, then the most recently registered sequence is the winner. That's the tiebreaker, bestie.

Now here's a spicy 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:

event add <<Paste>> <Control-y>
event add <<Paste>> <Button-2>
event add <<Scroll>> <Button-2>
bind Entry <<Paste>> {puts Paste}
bind Entry <<Scroll>> {puts 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, but exactly which one gets invoked is undefined. Not me trying to predict that. πŸ’€

If an X event does not match any of the existing bindings, then the event is ignored. An unbound event is not considered to be an error. So no stress.


🌸 MULTI-EVENT SEQUENCES AND IGNORED EVENTS 🌸

When a sequence specified in a bind command contains more than one event pattern, then its script is executed whenever the recent events (leading up to and including the current event) match the given sequence. It's giving "remember the last few moves".

This means, for example, that if button 1 is clicked repeatedly the sequence <Double-Button-1> will match each button press but the first. Yes, every press after the first one.

If extraneous events that would prevent a match occur in the middle of an event sequence then the extraneous events are ignored β€” unless they are Key or Button events. For example, <Double-Button-1> will match a sequence of presses of button 1, even though there will be ButtonRelease events (and possibly Motion events) between the Button events. They just don't matter for the match.

Furthermore, a Key event may be preceded by any number of other Key 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. It's giving "modifier keys don't ruin the vibe".

Finally, if several Motion events occur in a row, only the last one is used for purposes of matching binding sequences. So don't worry about the whole trail, just the final position. πŸ’…


😭 ERRORS 😭

If an error occurs in executing the script for a binding then the bgerror mechanism is used to report the error. The bgerror command will be executed at global level (outside the context of any Tcl procedure). So yeah, it's not hiding inside some procedure, it's out there in the open.


✨ EXAMPLES ✨

Arrange for a string describing the motion of the mouse to be printed out when the mouse is double-clicked:

bind . <Double-1> {
    puts "hi from (%x,%y)"
}

A little GUI that displays what the keysym name of the last key pressed is:

set keysym "Press any key"
pack [label .l -textvariable keysym -padx 2m -pady 1m]
bind . <Key> {
    set keysym "You pressed %K"
}

🫢 SEE ALSO 🫢


πŸ‘‘ KEYWORDS πŸ‘‘

binding, event


Okay bestie, that's the whole bind(3tk) page! Source: Tk, version 8.0, page bind(3tk). The footer didn't show me a date, so I'm not inventing one β€” but you know I'd tell you if it did. Bye bestie, go bind something iconic! πŸ’–βœ¨πŸ¦‹

πŸ“¦ where this page comes from