【发布时间】: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 显示的?
【问题讨论】: