2015-09-02 48 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