我有一个用tkinter编写的GUI,一切正常。我想增强它,以便当用户用鼠标点击某个选项卡时,会执行一个方法。我认为这将是直截了当但我不能让它工作。我的代码是
def f_x():
print('entered this method')
tab4e = ttk.Frame(notebook2,width=C_WIDTH,height=C_TAB_HEIGHT)
tab4e.bind("<Button-1>",f_x())
答案 0 :(得分:5)
当标签更改时,它会发出事件"<<NotebookTabChanged>>"
,您可以将其绑定到:
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)
使用此事件而不是绑定到鼠标单击的好处是无论是什么原因导致标签更改,绑定都会触发。例如,如果您定义快捷键以切换选项卡,则绑定到鼠标不会导致处理程序在用户使用其中一个快捷键时触发。
答案 1 :(得分:2)
你是对的,这很简单,你所做的几乎是正确的,你需要将函数而不是函数的返回值传递给bind
。因此,您需要在f_x
之后删除括号。另一件事是,绑定还会自动将参数传递给名为event
的回调,因此您需要让f_x
接受一个参数。
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()
答案 2 :(得分:0)
现在可以检测TAB Canvas何时通过左键单击鼠标进行聚焦
def fTabSwitched(event):
global notebook2
l_tabText = notebook2.tab(notebook2.select(), "text")
if (l_tabText == 'eee'):
print('lets roll')
tab4a = ttk.Frame(notebook2,width=C_WIDTH,height=C_TAB_HEIGHT)
tab4b = ttk.Frame(notebook2,width=C_WIDTH,height=C_TAB_HEIGHT)
tab4c = ttk.Frame(notebook2,width=C_WIDTH,height=C_TAB_HEIGHT)
tab4d = ttk.Frame(notebook2,width=C_WIDTH,height=C_TAB_HEIGHT)
tab4e = ttk.Frame(notebook2,width=C_WIDTH,height=C_TAB_HEIGHT)
notebook2.add(tab4a,text='aaa')
notebook2.add(tab4b,text='bbb')
notebook2.add(tab4c,text='ccc')
notebook2.add(tab4d,text='ddd')
notebook2.add(tab4e,text='eee')
notebook2.bind("<ButtonRelease-1>",fTabSwitched) # must be release