[英]Tkinter Label not receiving mouse clicks
我正在嘗試遵循此帖子:可單擊的Tkinter標簽,但我一定會誤解Tkinter小部件層次結構。 我將圖像存儲在Tkinter.Label
,我想檢測此圖像上的mouseclicks位置。
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
...
self.image = ImageTk.PhotoImage(image=im)
self.initUI()
def initUI(self):
self.parent.title("Quit button")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
self.photo_label = Tkinter.Label(self, image=self.image).pack()
self.bind("<ButtonPress-1>", self.OnMouseDown)
self.bind("<Button-1>", self.OnMouseDown)
self.bind("<ButtonRelease-1>", self.OnMouseDown)
# Tried the following, but it generates an error described below
# self.photo_label.bind("<ButtonPress-1>", self.OnMouseDown)
# self.photo_label.bind("<Button-1>", self.OnMouseDown)
# self.photo_label.bind("<ButtonRelease-1>", self.OnMouseDown)
def OnMouseDown(self, event):
x = self.parent.winfo_pointerx()
y = self.parent.winfo_pointery()
print "button is being pressed... %s/%s" % (x, y)
當我運行腳本時,我的窗口隨即出現,並顯示所需的圖像,但未打印任何內容,這意味着未檢測到鼠標單擊。 我以為發生這種情況是因為單個小部件應該捕獲鼠標單擊,所以我嘗試了上面注釋掉的代碼:
self.photo_label.bind("<ButtonPress-1>", self.OnMouseDown)
self.photo_label.bind("<Button-1>", self.OnMouseDown)
self.photo_label.bind("<ButtonRelease-1>", self.OnMouseDown)
但這會產生以下錯誤:
self.photo_label.bind("<ButtonPress-1>", self.OnMouseDown)
AttributeError: 'NoneType' object has no attribute 'bind'
為什么“框架”和/或“標簽”沒有顯示任何檢測到鼠標單擊的跡象? 為什么是self.photo_label
顯示為一個NoneType
即使實際上是在顯示的圖像,通過想必self.photo_label
?
下列:
self.photo_label = Tkinter.Label(self, image=self.image).pack()
將您的self.photo_label
引用設置為指向最終返回的內容。 由於諸如pack()
類的幾何管理方法返回None
,因此self.photo_label
指向該對象。
要解決此問題,請勿嘗試將幾何管理方法鏈接到小部件創建上:
self.photo_label = Tkinter.Label(self, image=self.image)
self.photo_label.pack()
self.photo_label
現在指向Label
對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.