【发布时间】:2021-11-22 14:50:12
【问题描述】:
我已经对脚本进行了总结,它只显示了显示我的问题所必需的内容。总之,我想globally将回调函数绑定到app中所有button类型的小部件。
class Frame_1(Frame):
def__init__(self,master, **kwargs):
super().__init__(master, **kwargs)
self.btn_0 = Button(self, text='Press 10')
self.btn_0 .pack() #...
# links that I would like to disappear
# and replace with a global link that only reaches button type widgets
self.btn_0 .bind('<ButtonPress>', self.master.press)
self.btn_0 .bind('<ButtonRelease>', self.master.release)
class Frame_2(Frame):
def__init__(self,master, **kwargs):
super().__init__(master, **kwargs)
self.btn_0 = Button(self, text='Press 10')
self.btn_0 .pack() #....
self.btn_0 .bind('<ButtonPress>', self.master.press)
self.btn_0 .bind('<ButtonRelease>', self.master.release)
class Controller(Frame):
def__init__(self,master, **kwargs):
super().__init__(master, **kwargs)
self.frm1 = Frame_1(self, bg='blue')
self.frm1 .pack()
self.frm2 = Frame_2(self, bg='green')
self.frm2 .pack()
def press(self, e):
print('press')
def release(self, e):
print('release')
root=Tk()
app=Controller(root)
app.pack()
root.mainloop()
【问题讨论】:
-
全球范围内?您将不得不使用 3rd 方库。这回答了你的问题了吗? python tkinter - Bind a "Global" key shortcut which can be triggered from outside the window
-
感谢您的回答,我打算不重复代码
bind ('<ButtonPress>', callback)和bind ('<ButtonRelease>', callback),因为这样做似乎很原始,因为如果有某种方法可以不重复,我想知道的,一直在想bind_class和bind_all,但是不知道怎么应用 -
bind_class适用于特定的小部件类,例如如果将其应用于按钮,则绑定将应用于所有按钮 -
@CoolCloud 但是我应该如何实现呢?如果您能帮我一点忙,我将不胜感激。
-
self.bind_class('Button', '<ButtonPress>',self.master.press)等等...