【问题标题】:Tkinter Label not receiving mouse clicksTkinter 标签未收到鼠标点击
【发布时间】:2015-09-02 19:20:25
【问题描述】:

我正在尝试关注这篇文章: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 显示的?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    以下内容:

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

    【讨论】:

    • 我什么时候才能学习关于返回 None 的许多类方法的课程?!!?非常感谢!
    猜你喜欢
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多