【问题标题】:tkinter left clicks on a TAB in your GUI. How to detect when user has done thistkinter 左键单击 GUI 中的选项卡。如何检测用户何时执行此操作
【发布时间】:2017-10-20 20:35:36
【问题描述】:

我有一个用 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())

【问题讨论】:

    标签: python function tkinter tabs execute


    【解决方案1】:

    你是对的,这很简单,你所做的几乎是正确的,你需要将函数而不是函数的返回值传递给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()
    

    【讨论】:

    • @Ab Bennett 来自review,该编辑没有对答案进行任何改进,如果您不想要 cmets,请在复制后自行删除。它们是为了暗示所有(将要)阅读本文的人。
    • 这适用于当用户在进入 TAB 画布后左键单击时执行。我想要的是在他们左键单击 TAB 本身进入选项卡 Canvas 时执行一个功能。我希望这是有道理的。感谢我的代码错误
    • 这个问题不涉及击键。当用户左键单击 gui 中的 TAB 以使其聚焦时,我想要执行一个函数。我/你的代码只有在用户鼠标左键单击 TAB 画布本身时才会执行。事后
    • @AbBennett 你可以绑定做notebook2.bind(...),并将tac4e = ttk.Frame(...)的创建放入回调f_x,当用户点击notebook2事物时创建它(我不'不知道它是什么,因为你从来没有告诉我们)。请添加更多相关代码。这个问题正在变成X Y problem
    • 请注意,如果用户使用键盘切换选项卡,或者如果选项卡从代码的其他部分以编程方式更改,则不会调用绑定函数。
    【解决方案2】:

    这现在可以检测何时通过鼠标左键单击 TAB 画布成为焦点

    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
    

    【讨论】:

    • 请注意,如果用户使用键盘切换选项卡,或者如果选项卡从代码的其他部分以编程方式更改,则不会调用绑定函数。
    【解决方案3】:

    当标签更改时,它会发出"&lt;&lt;NotebookTabChanged&gt;&gt;",您可以绑定到:

    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)
    

    使用此事件而不是绑定到鼠标单击的好处是,无论是什么导致选项卡更改,绑定都会触发。例如,如果您定义了切换选项卡的快捷键,那么如果用户使用这些快捷键之一,绑定到鼠标不会导致您的处理程序触发。

    【讨论】:

      猜你喜欢
      • 2014-08-19
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多