event(n)

πŸŽ€ event(n) πŸŽ€

okay bestie, this one lives in the Tk Built-In Commands manual, and it's genuinely the backbone of how Tk handles window system events. it's long, so buckle up πŸ’–


✨ SYNOPSIS ✨

event option ?arg ...?

🌸 DESCRIPTION 🌸

so the event command is basically your little toolkit for dealing with window system events β€” the real ones, the fake ones, the "what even is an event" ones. it gives you several facilities: defining virtual events and synthesizing events (yes, you can just make an event happen, main character energy fr fr πŸ‘‘).

the command has several different forms, and which one you get is determined by the first argument. here's everything that's currently supported:

  • event add <<virtual>> sequence ?sequence ...? β€” this one associates the virtual event virtual with the physical event sequence(s) you pass in the sequence arguments, so that the virtual event triggers whenever any one of those sequences occurs. Virtual can be any string value, and sequence can have any of the values allowed for the sequence argument to the bind command. and if virtual is already defined? no worries, the new physical event sequences just add to the existing sequences for that event. slay, additive πŸ’…
  • event delete <<virtual>> ?sequence sequence ...? β€” the breakup form. it deletes each of the sequences from those associated with the virtual event given by virtual. Virtual can be any string value, and sequence can have any of the values allowed for the sequence argument to the bind command. any sequences not currently associated with virtual are just ignored (no drama, they weren't invited anyway πŸ™ˆ). and if you pass no sequence argument at all, then all physical event sequences are removed for virtual, so that virtual event will simply never trigger again. it's giving "we're done here" πŸ’€
  • event generate window event ?option value option value ...? β€” the iconic one. synthetic events, no cap. it generates a window event and arranges for it to be processed just as if it had come from the window system β€” the whole app is fooled, it ate πŸ“. Window gives the path name of the window for which the event will be generated; it may also be an identifier (such as the one returned by winfo id) as long as it's for a window in the current application. Event provides a basic description of the event, like <Shift-Button-2> or <<Paste>>. if Window is empty, the whole screen is meant, and coordinates are relative to the screen. Event may have any of the forms allowed for the sequence argument of the bind command, except that it has to consist of a single event pattern β€” not a sequence, bestie, one (1) pattern only. option-value pairs can specify additional attributes of the event, like the x and y mouse position β€” see EVENT FIELDS below for the full tea πŸ«–. if the -when option isn't specified, the event is processed immediately: all of the handlers for the event will complete before the event generate command returns. if -when is specified, then it decides when the event gets processed. certain events β€” key events, looking at you πŸ‘€ β€” require that the window has focus to receive the event properly.
  • event info ?<<virtual>>? β€” the gossip form. returns information about virtual events. if the <<virtual>> argument is omitted, the return value is a list of all the virtual events currently defined. if <<virtual>> is specified, the return value is a list whose elements are the physical event sequences currently defined for that given virtual event; and if the virtual event isn't defined, you get an empty string back (ghosted 😭).
⚠️ note that virtual events that are not bound to physical event sequences are not returned by event info. literally they will not show up, iykyk.

okay that's the core of it and we're barely warmed up β€” the rest of this page is coming, don't you dare close the tab 🌈

✨ EVENT FIELDS ✨

okay bestie, these are the options supported for the event generate command, and they line up exactly with the % expansions you’re allowed to use in binding scripts for bind. cute, right? πŸ’…

  • -above window β€” sets the above field for the event. window can be a window path name or an integer window id. Valid for Configure events. Corresponds to the %a substitution for binding scripts. πŸͺŸ
  • -borderwidth size β€” size has to be a screen distance, and it sets the border_width field for the event. Valid for Configure events. Corresponds to the %B substitution for binding scripts. ✨
  • -button number β€” number has to be an integer, and it sets the detail field for a Button or ButtonRelease event, overriding any button number provided in the base event argument. Corresponds to the %b substitution for binding scripts. πŸ–±οΈ
  • -count number β€” number has to be an integer, and it sets the count field for the event. Valid for Expose events. Corresponds to the %c substitution for binding scripts. πŸ”’
  • -data string β€” string can be any value, and it sets the user_data field for the event. Only valid for virtual events. Corresponds to the %d substitution for virtual events in binding scripts. πŸ’Ύ
  • -delta number β€” number has to be an integer, and it sets the delta field for the MouseWheel event. The delta refers to the direction and magnitude the mouse wheel was rotated. Note that the value is not a screen distance β€” it’s units of motion in the mouse wheel. Typically these values are multiples of 120. For example, 120 should scroll the text widget up 4 lines and -240 would scroll the text widget down 8 lines. Of course, other widgets may define different behaviors for mouse wheel motion. This field corresponds to the %D substitution for binding scripts. 🎑
  • -detail detail β€” detail sets the detail field for the event and must be one of the following: NotifyAncestor, NotifyNonlinearVirtual, NotifyDetailNone, NotifyPointer, NotifyInferior, NotifyPointerRoot, NotifyNonlinear, NotifyVirtual. Valid for Enter, Leave, FocusIn and FocusOut events. Corresponds to the %d substitution for binding scripts. πŸŒ€
  • -focus boolean β€” boolean has to be a boolean value, and it sets the focus field for the event. Valid for Enter and Leave events. Corresponds to the %f substitution for binding scripts. 🎯
  • -height size β€” size has to be a screen distance, and it sets the height field for the event. Valid for Configure events. Corresponds to the %h substitution for binding scripts. πŸ“
  • -keycode number β€” number has to be an integer, and it sets the keycode field for the event. Valid for Key and KeyRelease events. Corresponds to the %k substitution for binding scripts. ⌨️
  • -keysym name β€” name has to be the name of a valid keysym, such as g, space, or Return; its corresponding keycode value is used as the keycode field for the event, overriding any detail specified in the base event argument. Valid for Key and KeyRelease events. Corresponds to the %K substitution for binding scripts. 🫢
  • -mode notify β€” notify sets the mode field for the event and must be one of NotifyNormal, NotifyGrab, NotifyUngrab, or NotifyWhileGrabbed. Valid for Enter, Leave, FocusIn, and FocusOut events. Corresponds to the %m substitution for binding scripts. πŸ””
  • -override boolean β€” boolean has to be a boolean value, and it sets the override_redirect field for the event. Valid for Map, Reparent, and Configure events. Corresponds to the %o substitution for binding scripts. πŸšͺ
  • -place where β€” where sets the place field for the event; it must be either PlaceOnTop or PlaceOnBottom. Valid for Circulate events. Corresponds to the %p substitution for binding scripts. πŸ—οΈ
  • -root window β€” window has to be either a window path name or an integer window identifier, and it sets the root field for the event. Valid for Key, KeyRelease, Button, ButtonRelease, Enter, Leave, and Motion events. Corresponds to the %R substitution for binding scripts. 🌳
  • -rootx coord β€” coord has to be a screen distance, and it sets the x_root field for the event. Valid for Key, KeyRelease, Button, ButtonRelease, Enter, Leave, and Motion events. Corresponds to the %X substitution for binding scripts. πŸ“
  • -rooty coord β€” coord has to be a screen distance, and it sets the y_root field for the event. Valid for Key, KeyRelease, Button, ButtonRelease, Enter, Leave, and Motion events. Corresponds to the %Y substitution for binding scripts. πŸ“Œ
  • -sendevent boolean β€” boolean has to be a boolean value, and it sets the send_event field for the event. Valid for all events. Corresponds to the %E substitution for binding scripts. πŸ“¨
  • -serial number β€” number has to be an integer, and it sets the serial field for the event. Valid for all events. Corresponds to the %# substitution for binding scripts. πŸ”’
  • -state state β€” state sets the state field for the event. For Key, KeyRelease, Buttons, ButtonRelease, Enter, Leave, and Motion events it must be an integer value. For Visibility events it must be one of VisibilityUnobscured, VisibilityPartiallyObscured, or VisibilityFullyObscured. This option overrides any modifiers such as Meta or Control specified in the base event. Corresponds to the %s substitution for binding scripts. 🧠
  • -subwindow window β€” window sets the subwindow field for the event, either as a path name for a Tk widget or as an integer window identifier. Valid for Key, KeyRelease, Button, ButtonRelease, Enter, Leave, and Motion events. Similar to %S substitution for binding scripts. πŸͺŸ
  • -time integer β€” integer has to be an integer value, and it sets the time field for the event. Additionally, the special value current is allowed; this value will be substituted by the current event time. Valid for Key, KeyRelease, Button, ButtonRelease, Enter, Leave, Motion, and Property events. Corresponds to the %t substitution for binding scripts. ⏰
  • -warp boolean β€” boolean has to be a boolean value, and it specifies whether the screen pointer should be warped as well. Valid for Key, KeyRelease, Button, ButtonRelease, and Motion events. The pointer will only warp to a window if it is mapped. πŸŒ€
  • -width size β€” size has to be a screen distance, and it sets the width field for the event. Valid for Configure events. Corresponds to the %w substitution for binding scripts. πŸ“
  • -when when β€” when determines when the event will be processed; it must have one of the following values:
    • now β€” process the event immediately, before the command returns. This also happens if the -when option is omitted. ⚑
    • tail β€” place the event on Tcl’s event queue behind any events already queued for this application. πŸšΆβ€β™€οΈ
    • head β€” place the event at the front of Tcl’s event queue, so that it will be handled before any other events already queued. πŸ‘‘
    • mark β€” place the event at the front of Tcl’s event queue but behind any other events already queued with -when mark. This option is useful when generating a series of events that should be processed in order but at the front of the queue. πŸŽ€
  • -x coord β€” coord has to be a screen distance, and it sets the x field for the event. Valid for Key, KeyRelease, Button, ButtonRelease, Motion, Enter, Leave, Expose, Configure, Gravity, and Reparent events. Corresponds to the %x substitution for binding scripts. If Window is empty the coordinate is relative to the screen, and this option corresponds to the %X substitution for binding scripts. ➑️
  • -y coord β€” coord has to be a screen distance, and it sets the y field for the event. Valid for Key, KeyRelease, Button, ButtonRelease, Motion, Enter, Leave, Expose, Configure, Gravity, and Reparent events. Corresponds to the %y substitution for binding scripts. If Window is empty the coordinate is relative to the screen, and this option corresponds to the %Y substitution for binding scripts. ⬇️

Any options that are not specified when generating an event are filled with the value 0, except for serial, which is filled with the next X event serial number. and that’s the default vibe πŸ’–

✨ PREDEFINED VIRTUAL EVENTS ✨

ok so Tk comes with a whole pre-loaded stash of virtual events, no cap πŸ’… Here's the first batch β€” these exist purely for notification vibes:

  • <<AltUnderlined>> β€” this one gets sent to a widget to let it know that the letter it underlined (you know, the accelerator indicator it set up with the -underline option) got pressed together with the Alt key. The usual slay response? Either focus into the widget (or some related widget), or just invoke the widget. periodt.
  • <<Invoke>> β€” you can send this to certain widgets (like button, listbox, menu) as a whole alternative to <space>. iconic behavior tbh.
  • <<ListboxSelect>> β€” fires at a listbox the moment the set of selected item(s) inside it gets updated. πŸ¦‹
  • <<MenuSelect>> β€” sent to a menu when the currently selected item in that menu changes. It's literally built for context-sensitive help systems, iykyk.
  • <<Modified>> β€” sent to a text widget when the contents of the widget are changed. bestie's little "something moved" ping πŸ’–
  • <<Selection>> β€” sent to a text widget when the selection in the widget is changed.
  • <<ThemeChanged>> β€” sent to all widgets when the ttk theme changed. The ttk widgets literally listen for this event and redisplay themselves when it fires. The legacy widgets? They ignore this event entirely πŸ™ˆ
  • <<TkWorldChanged>> β€” this event is sent to all widgets when a font is changed, for example by the use of [font configure]. The user_data field (%d) will have the value "FontChanged". For other system wide changes, this event gets sent to all widgets, and the user_data field will indicate the cause of the change. NOTE: all tk and ttk widgets already handle this event internally ✨
  • <<TraverseIn>> β€” sent to a widget when the focus enters the widget because of a user-driven β€œtab to widget” action. main character entrance energy πŸŽ€
  • <<TraverseOut>> β€” sent to a widget when the focus leaves the widget because of a user-driven β€œtab to widget” action. bye bestie πŸ‘‹
  • <<UndoStack>> β€” sent to a text widget when its undo stack or redo stack becomes empty or unempty. yes, "unempty" is a word now, we don't make the rules πŸ’€
  • <<WidgetViewSync>> β€” sent to a text widget when its internal data become obsolete, and again when those internal data are back in sync with the widget view. The detail field (the %d substitution) is either true (widget is in sync) or false (it is not). vibe check passed or failed, basically 🌈

ok and then there's a whole second family of virtual events, and these ones exist for the purpose of unifying bindings across multiple platforms 🫢 Users expect them to behave in the following way:

  • <<Clear>> β€” delete the currently selected widget contents. yeet it πŸ—‘οΈ
  • <<Copy>> β€” copy the currently selected widget contents to the clipboard.
  • <<Cut>> β€” move the currently selected widget contents to the clipboard.
  • <<LineEnd>> β€” move to the end of the line in the current widget while deselecting any selected contents.
  • <<LineStart>> β€” move to the start of the line in the current widget while deselecting any selected contents.
  • <<NextChar>> β€” move to the next item (i.e., visible character) in the current widget while deselecting any selected contents.
  • <<NextLine>> β€” move to the next line in the current widget while deselecting any selected contents.
  • <<NextPara>> β€” move to the next paragraph in the current widget while deselecting any selected contents.
  • <<NextWord>> β€” move to the next group of items (i.e., visible word) in the current widget while deselecting any selected contents.
  • <<Paste>> β€” replace the currently selected widget contents with the contents of the clipboard. the classic πŸ’…
  • <<PasteSelection>> β€” insert the contents of the selection at the mouse location. (This event has meaningful %x and %y substitutions β€” so yeah, it actually knows where your cursor is πŸ–±οΈ)
  • <<PrevChar>> β€” move to the previous item (i.e., visible character) in the current widget while deselecting any selected contents.
  • <<PrevLine>> β€” move to the previous line in the current widget while deselecting any selected contents.
  • <<PrevPara>> β€” move to the previous paragraph in the current widget while deselecting any selected contents.
  • <<PrevWindow>> β€” traverse to the previous window.
  • <<PrevWord>> β€” move to the previous group of items (i.e., visible word) in the current widget while deselecting any selected contents.
  • <<Redo>> β€” redo one undone action. the comeback tour πŸ”₯
  • <<SelectAll>> β€” set the range of selected contents to the complete widget. ctrl-a supremacy.
  • <<SelectLineEnd>> β€” move to the end of the line in the current widget while extending the range of selected contents.
  • <<SelectLineStart>> β€” move to the start of the line in the current widget while extending the range of selected contents.
  • <<SelectNextChar>> β€” move to the next item (i.e., visible character) in the current widget while extending the range of selected contents.
  • <<SelectNextLine>> β€” move to the next line in the current widget while extending the range of selected contents.
  • <<SelectNextPara>> β€” move to the next paragraph in the current widget while extending the range of selected contents.
  • <<SelectNextWord>> β€” move to the next group of items (i.e., visible word) in the current widget while extending the range of selected contents.
  • <<SelectNone>> β€” reset the range of selected contents to be empty. de-select, un-highlight, done 🧚
  • <<SelectPrevChar>> β€” move to the previous item (i.e., visible character) in the current widget while extending the range of selected contents.
  • <<SelectPrevLine>> β€” move to the previous line in the current widget while extending the range of selected contents.
  • <<SelectPrevPara>> β€” move to the previous paragraph in the current widget while extending the range of selected contents.
  • <<SelectPrevWord>> β€” move to the previous group of items (i.e., visible word) in the current widget while extending the range of selected contents.
  • <<ToggleSelection>> β€” toggle the selection. flip it and reverse it ⭐
  • <<Undo>> β€” undo the last action. the single most important keybind in existence, ngl 😭

🌸 EXAMPLES 🌸

MAPPING KEYS TO VIRTUAL EVENTS

ok so for a virtual event binding to actually trigger, two things gotta happen. First: the virtual event must be defined with the event add command. Second: a binding must be created for that virtual event with the bind command. Both. not one, both. πŸ’–

Consider the following virtual event definitions:

event add <<Paste>> <Control-y>
event add <<Paste>> <Button-2>
event add <<Save>> <Control-X><Control-S>
event add <<Save>> <Shift-F12>
if {[tk windowingsystem] eq "aqua"} {
    event add <<Save>> <Command-s>
}

And in the bind command, a virtual event can be bound like any other builtin event type, like this:

bind Entry <<Paste>> {%W insert [selection get]}

The double angle brackets are how you specify that a virtual event is being bound β€” << >>, that's the giveaway πŸ‘‘ If the user types Control-y or presses button 2, or if a <<Paste>> virtual event is synthesized with event generate, then the <<Paste>> binding will be invoked. slay.

Now here's a little plot twist 🫢 If a virtual binding has the exact same sequence as a separate physical binding, then the physical binding will take precedence. Consider this:

event add <<Paste>> <Control-y> <Meta-Control-y>
bind Entry <Control-y> {puts Control-y}
bind Entry <<Paste>> {puts Paste}

When the user types Control-y, the <Control-y> binding will be invoked β€” because a physical event is considered more specific than a virtual event, all other things being equal. BUT when the user types Meta-Control-y, the <<Paste>> binding will be invoked, because the Meta modifier in the physical pattern associated with the virtual binding is more specific than the <Control-y> sequence for the physical event. see how that flips? literal main character energy from the Meta modifier πŸ’…

Also very important: bindings on a virtual event may be created before the virtual event exists. Like, the virtual event never actually needs to be defined β€” for instance, on platforms where that specific virtual event would be meaningless or ungeneratable. it's giving "manifesting" tbh ✨

And when a definition of a virtual event changes at run time, all windows will respond immediately to the new definition. Starting from the preceding example, if this code is executed:

bind Entry <Control-y> {}
event add <<Paste>> <F6>

then the behavior will change in two ways. First, the shadowed <<Paste>> binding will emerge β€” typing Control-y will no longer invoke the <Control-y> binding, but instead invoke the virtual event <<Paste>>. Second, pressing the F6 key will now also invoke the <<Paste>> binding. two-for-one glow-up πŸ”₯

MOVING THE MOUSE POINTER

Sometimes it is genuinely useful to be able to really move the mouse pointer. For example, if you have some software that's capable of demonstrating directly to the user how to use the program. To do this, you need to β€œwarp” the mouse around by using event generate, like this:

for {set xy 0} {$xy < 200} {incr xy} {
    event generate . <Motion> -x $xy -y $xy -warp 1
    update
    after 50
}
⚠️ ok but listen β€” it is usually considered bad style to move the mouse pointer for the user, because it removes control from them. So use this technique with caution, bestie. Also note that it is not guaranteed to function on all platforms. 🫢

πŸ‘€ SEE ALSO πŸ‘€

  • bind(n) β€” go read that one next, it's the whole other half of this story πŸ’œ

πŸŽ€ KEYWORDS πŸŽ€

event, binding, define, handle, virtual event


and that's the whole page, you made it!! πŸ¦‹βœ¨ this little icon came from Tk 8.3, the event(n) page, dated back in the day β€” go forth and bind responsibly, mwah πŸ’‹πŸŒΈ

πŸ“¦ where this page comes from