Tkinter标签未接收鼠标点击

时间:2015-09-02 19:20:26

标签: python tkinter

我正在尝试关注这篇文章:Clickable Tkinter labels但我必须误解Tkinter小部件层次结构。我将图像存储在Tkinter.Label中,我想检测此图像上鼠标点击的位置。

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'

为什么Frame和/或Label没有显示任何检测鼠标点击的迹象?为什么self.photo_label显示为NoneType,即使图像实际上是显示的,也可能是self.photo_label

1 个答案:

答案 0 :(得分: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个对象。