Ab *_*ett 1 python tabs tkinter function execute
我有一个用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())
Run Code Online (Sandbox Code Playgroud)
当选项卡更改时,它将发出事件"<<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)
Run Code Online (Sandbox Code Playgroud)
使用此事件而不是绑定到鼠标单击的好处是,无论什么原因导致选项卡更改,绑定都会触发。例如,如果您定义了用于切换选项卡的快捷键,则如果用户使用这些快捷键之一,则绑定到鼠标不会触发处理程序。
你是对的,这非常简单,你所做的几乎是正确的,你需要将函数而不是函数的返回值传递给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()
Run Code Online (Sandbox Code Playgroud)