Python 如何基于框架绑定到类对象内的右键单击事件

Python 如何基于框架绑定到类对象内的右键单击事件,python,class,inheritance,tkinter,Python,Class,Inheritance,Tkinter,我正在开发一个类,它通过在一个框架中嵌入多个小部件来支持多字体按钮。现在,我试图处理调用bind()方法的类实例,但无法使其工作。我认为该类只会从框架继承bind()方法,但在这个实例中它似乎不起作用。当我右键单击第二个按钮(类实例)时,我没有得到打印的语句。我做错了什么? 复制问题的样本: import tkinter as tk class ButtonF(tk.Frame): def __init__(self, master=None, **options):

我正在开发一个类,它通过在一个框架中嵌入多个小部件来支持多字体按钮。现在,我试图处理调用
bind()
方法的类实例,但无法使其工作。我认为该类只会从框架继承
bind()
方法,但在这个实例中它似乎不起作用。当我右键单击第二个按钮(类实例)时,我没有得到打印的语句。我做错了什么? 复制问题的样本:

import tkinter as tk

class ButtonF(tk.Frame):

    def __init__(self, master=None, **options):
        self.command = options.pop('command', None)
        text = options.pop('text', '')
        tk.Frame.__init__(self, master, **options)
        self.b = tk.Button(master, text=text, command=self.command)
        self.bind('<Button-1>', self._click)
        self.bind('<ButtonRelease-1>', self._release)
        self.b.pack()

    def _click(self):
        self.config(relief=tk.SUNKEN)
        if self.command:
            self.command()

    def _release(self):
        self.config(relief=tk.RAISED)

    def bind(self, *a, **kw):
        tk.Frame.bind(self, *a, **kw)

if __name__ == '__main__':
    root = tk.Tk()
    root.title('Frame Button')
    root.but1 = tk.Button(root, text='Button 1 (Regular)', command=lambda *a:print('Button 1 Click!'))
    root.but1.pack(side=tk.LEFT)
    root.but2 = ButtonF(root, text='Button 2 (ButtonF)', command=lambda *a:print('Button 2 Click!')) # 
    root.but2.pack(side=tk.LEFT)
    root.but1.bind('<Button-3>', lambda *a: print('Button 1 Right-Click!'))
    root.but2.bind('<Button-3>', lambda *a: print('Button 2 Right-Click!')) #### THIS DOESN'T WORK ####
    root.mainloop()
将tkinter作为tk导入
类按钮(tk.框架):
def _;初始化_;(self,master=None,**选项):
self.command=options.pop('command',None)
text=options.pop('text','')
tk.Frame.\uuuuu init\uuuuu(self,master,**选项)
self.b=tk.Button(master,text=text,command=self.command)
self.bind(“”,self.\u单击)
自我绑定(“”,自我释放)
self.b.pack()
def_单击(自身):
self.config(relief=tk.sinken)
如果自我命令:
self.command()
def_释放(自):
self.config(relief=tk.RAISED)
def绑定(自身,*a,**kw):
传统框架绑定(自,*a,**kw)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
root=tk.tk()
root.title('框架按钮')
root.but1=tk.Button(root,text='Button 1(常规)',command=lambda*a:print('Button 1 Click!'))
根.但1.包(侧=左侧)
root.but2=ButtonF(root,text='Button 2(ButtonF'),command=lambda*a:print('Button 2 Click!'))#
root.but2.pack(侧=tk.LEFT)
root.but1.bind(“”,lambda*a:print('Button 1 Right Click!'))
root.but2.bind(“”,lambda*a:print('Button 2 Right Click!'))#####这不起作用####
root.mainloop()

您的
按钮f
继承自
tk.Frame
。当您这样做时:

root.but2.bind('<Button-3>', lambda *a: print('Button 2 Right-Click!'))

最后一个技巧是绑定到框架和按钮。因此,绑定到
self
self.b
。 为什么?嗯,你必须绑定到框架上,以防你点击了框架中不在按钮下的部分。如果您单击按钮本身(即,不在框架的一部分),则必须绑定到按钮。 因此,两个绑定对于正确的解决方案是必要的

def bind(self, *a, **kw):
    tk.Frame.bind(self.b, *a, **kw)