2015-09-02 51 views
0

我想要關注這篇文章:Clickable Tkinter labels但我必須誤解Tkinter小部件層次結構。我將圖像存儲在Tkinter.Label中,我想要檢測此圖像上的鼠標點擊的位置。Tkinter標籤沒有收到鼠標點擊

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

回答

2

以下:

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對象。

+0

什麼時候我要學習關於返回None的許多類方法的課程?!!?非常感謝! – sunny