[英]How to bind callback functions globally to a widget type in tkinter?
我以這樣一種方式總結了腳本,它只顯示了顯示我的問題所必需的內容。 簡而言之,我想將回調函數globally
綁定到應用程序中的所有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()
以這種方式嘗試:你試圖稱呼“自我”。 此時你需要一個 object 參考。 但你沒有那個。 公共對象仍然可以集成到class。
from tkinter import *
def press( event):
print('press')
def release( event):
print('release')
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>', press)
self.btn_0.bind('<ButtonRelease>', 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>', press)
self.btn_0.bind('<ButtonRelease>', release)
class Controller(Frame):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
global press, release
self.frm1 = Frame_1(self, bg='blue')
self.frm1.pack()
self.frm2 = Frame_2(self, bg='green')
self.frm2.pack()
root = Tk()
app = Controller(root)
app.pack()
root.mainloop()
Tkinter 提供了一個bind_class
方法,允許您綁定到一個小部件 class 而不是單個小部件。 在您的情況下, class 將是Button
。
您的代碼可能如下所示:
root=Tk()
app=Controller(root)
root.bind_class("Button", "<ButtonPress-1>", app.press)
root.bind_class("Button", "<ButtonRelease-1>", app.release)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.