Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tkinter left clicks on a TAB in your GUI. How to detect when user has done this

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())
like image 411
Ab Bennett Avatar asked Dec 19 '22 07:12

Ab Bennett


2 Answers

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.

like image 50
Bryan Oakley Avatar answered Dec 21 '22 10:12

Bryan Oakley


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()
like image 28
Taku Avatar answered Dec 21 '22 09:12

Taku