I have a GUI written in tkinter and all works fine. I want to enhance it so that when a user left clicks on a certain tab with the mouse, a method is executed. I thought this would be straight forward but I can't get it working. My code is
def f_x():
print('entered this method')
tab4e = ttk.Frame(notebook2,width=C_WIDTH,height=C_TAB_HEIGHT)
tab4e.bind("<Button-1>",f_x())
When the tab changes, it emits the event "<<NotebookTabChanged>>"
, which you can bind to:
def handle_tab_changed(event):
selection = event.widget.select()
tab = event.widget.tab(selection, "text")
print("text:", tab)
notebook = ttk.Notebook(...)
...
notebook.bind("<<NotebookTabChanged>>", handle_tab_changed)
The benefit of using this event rather than binding to a mouse click is that the binding will fire no matter what causes the tab to change. For example, if you define shortcut keys to switch tabs, binding to the mouse won't cause your handler to fire if the user uses one of those shortcut keys.
You were right, this is pretty straight forward, what you did was almost correct, you need to pass the function not the return value of the function to bind
. So you will need to get rid of the parentheses after f_x
. Another thing is, the bind also automatically pass an argument to the callback called event
, so you will need to let f_x
accept an argument.
def f_x(event): # accept the event arg
print('entered this method')
tab4e = ttk.Frame(notebook2,width=C_WIDTH,height=C_TAB_HEIGHT)
tab4e.bind("<Button-1>",f_x) # not f_x()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With