我发现这个整齐的代码here使用Tkinter来显示一系列图像。我扩展了代码以使用' z'和' x'用于浏览图像的按键和' q'退出。此外,我希望能够单击各个帧并获取我单击的位置的图像坐标。虽然键盘交互工作正常,但鼠标单击事件不会被触发。我想知道为什么会这样,因为击键击中就好了。
这是我的代码:
#!/usr/bin/env python
from Tkinter import *
import Image, ImageTk
import os, sys
class Clicker:
def __init__(self, master, filelist):
self.top = master
self.files = filelist
self.index = 0
#display first image
filename = filelist[0]
if not os.path.exists(filename):
print "Unable to find %s" % filename
self.top.quit()
self.title = Label(text=os.path.basename(filename))
self.title.pack()
im = Image.open(filename)
self.tkimage = ImageTk.PhotoImage(im, palette=256)
self.lbl = Label(master, image=self.tkimage)
self.lbl.pack(side='top')
# the button frame
fr = Frame(master)
fr.pack(side='top', expand=1, fill='both')
back = Button(fr, text="back", command=lambda : self.nextframe(-1))
back.grid(row=0, column=0, sticky="w", padx=4, pady=4)
self.ilabel = Label(fr, text="image number: %d/%d" %
(self.index+1, len(self.files)))
self.ilabel.grid(row=0, column=1, sticky="e", pady=4)
self.evar = IntVar()
self.evar.set(1)
next = Button(fr, text="next", command=lambda : self.nextframe(1))
next.grid(row=0, column=3, sticky="e", padx=4, pady=4)
# events
fr.focus_set()
fr.bind("<Key>", self.key)
fr.bind("<Button 1>", self.left_click)
def left_click(self, event):
print (event.x,event.y)
def key(self, event):
if event.char == 'z':
# previous frame
self.nextframe(-1)
elif event.char == 'x':
# next frame
self.nextframe(1)
elif event.char == 'q':
# quit
self.top.quit()
def getImage(self, filename):
im = Image.open(filename)
return im
def nextframe(self,i=1, imgnum=-1):
if imgnum == -1:
self.index += i
else:
self.index = imgnum - 1
if self.index >= len(self.files):
self.index = 0
elif self.index < 0:
self.index = len(self.files) - 1
filename = self.files[self.index]
if not os.path.exists(filename):
print "Unable to find %s" % filename
self.top.quit()
self.title.configure(text=os.path.basename(filename))
self.evar.set(self.index+1)
self.ilabel.configure(text="image number: %d/%d" %
(self.index+1, len(self.files)))
im = self.getImage(filename)
self.tkimage.paste(im)
def getimgnum(self, event=None):
self.nextframe(imgnum=self.evar.get())
# --------------------------------------------------------------------
if __name__ == "__main__":
if not sys.argv[1:]:
print "Usage: click.py images*"
sys.exit()
filelist = sys.argv[1:]
root = Tk()
app = Clicker(root, filelist)
root.mainloop()
代码应该适用于任何图像集,所有图像都必须具有相同的尺寸。
编辑:有趣的是,我可以在键击上获得光标位置,但不能点击鼠标。
答案 0 :(得分:0)
似乎我自己找到了答案:
如果我用Frame
替换Canvas
,我可以触发鼠标点击事件。我不确定为什么会这样,但它确实有效。