Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter difference between <event> and <<event>>

I am having difficulty looking for this on the internet - my search skills aren't up the scratch. I can remember the event names, but I always have to look up what type of angle brackets to use

Some tkinter events are bound with words in <> for example

tab4e.bind("<Button-1>",f_x)

Others are in <<>>, for example

nbook.bind('<<NotebookTabChanged>>', handle_tab_changed)

Is there any reason why some bindings are in <> and others in <<>>?

Even though the examples are given in python, I've added TCL, just in case a TCL coder might know the answer.

like image 514
cup Avatar asked Apr 09 '26 04:04

cup


2 Answers

Bindings that have a single set of brackets are built-in events directly supported by the underlying OS. Examples include <KeyPress>, <ButtonPress-1>, <Configure>, and many more. Most of the built-in events are directly tied to actual physical events such as pressing a mouse button or key on the keyboard.

Bindings with double-brackets are called virtual events. They do not necessarily represent any sort of physical event, and typically (though not always) are unique to specific widgets. For example, <<ListboxSelect>> is only used by the listbox, <<NotebookTabChanged>> is only used by the ttk notebook, and so on.

Virtual events can be triggered by a combination of other events using the event_add widget method, though they can also be generated by calling event_generate.

The tcl/tk man pages includes a list of predefined virtual events.

like image 88
Bryan Oakley Avatar answered Apr 10 '26 17:04

Bryan Oakley


(Keep @Oakley's answer)

Here is an example of a custom event:

from tkinter import *
import random

def button_click():
    num = random.randint(1,10)  # data to pass, state must be integer
    root.event_generate("<<myevent>>", when="tail", state=num)  # add event to end of event queue, pass state (optional)

def myhandler(evt):  # handle custom event
    print('custom event handled', evt.state)

root = Tk()

button = Button(root, text="Click Me!", command=button_click)
root.bind("<<myevent>>", myhandler)  # create custom event and set handler

button.pack() 
root.mainloop()
like image 29
Mike67 Avatar answered Apr 10 '26 17:04

Mike67



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!