我正在开发一个类,它通过在一个框架中嵌入多个小部件来支持多字体按钮。现在,我试图处理调用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()
最后一个技巧是绑定到框架和按钮。因此,绑定到
self
和self.b
。 为什么?嗯,你必须绑定到框架上,以防你点击了框架中不在按钮下的部分。如果您单击按钮本身(即,不在框架的一部分),则必须绑定到按钮。 因此,两个绑定对于正确的解决方案是必要的您的
ButtonF
是从tk.Frame
继承的。当您这样做时:您绑定到的是框架,而不是框架内的按钮(其主控设置为
root
)要获得预期的行为,必须将绑定传递给按钮:
相关问题 更多 >
编程相关推荐