我想用PIL向用户显示图像,当用户在此图像上的任何地方单击时,我想调用一个def onmousedown(x,y)。我会在这个功能中做一些额外的事情。我如何在PIL中做到这一点?捕获x,y与Python的坐标PIL
感谢,
我想用PIL向用户显示图像,当用户在此图像上的任何地方单击时,我想调用一个def onmousedown(x,y)。我会在这个功能中做一些额外的事情。我如何在PIL中做到这一点?捕获x,y与Python的坐标PIL
感谢,
PIL将独自做到这一点 - PIL是一种图像处理库,没有用户界面 - 它确实有一个show
方法,它不打开,显示图像的外部程序,但不不与Python进程进行通信。
因此,为了能够让用户与图像进行交互,人们必须使用其中一种整合工具包来构建一个GUI程序,以便与Python一起使用 - 更为人熟知的是Tkinter,GTK和Qt4 。 Tkinter很有趣,因为它预装了Windows Python安装程序,因此更容易为该系统的用户提供。如果您决定使用其他工具包,Windows用户将不得不单独下载并安装gtk或qt库以便能够使用您的程序。
这里是一个可点击的图像的Tkinter应用的简约例如:
import Tkinter
from PIL import Image, ImageTk
from sys import argv
window = Tkinter.Tk(className="bla")
image = Image.open(argv[1] if len(argv) >=2 else "bla2.png")
canvas = Tkinter.Canvas(window, width=image.size[0], height=image.size[1])
canvas.pack()
image_tk = ImageTk.PhotoImage(image)
canvas.create_image(image.size[0]//2, image.size[1]//2, image=image_tk)
def callback(event):
print "clicked at: ", event.x, event.y
canvas.bind("<Button-1>", callback)
Tkinter.mainloop()
这里是另外一个相关的帖子
How to display picture and get mouse click coordinate on it
在Ubuntu上安装
须藤APT-得到安装python python-tk空闲python-pmw python-imaging python-imaging-tk
然后一切正常。
我在@ jsbueno的解决方案中添加了一个调整大小,并修复了一个导入问题。
import Tkinter
from PIL import ImageDraw, Image, ImageTk
import sys
window = Tkinter.Tk(className="bla")
image = Image.open(sys.argv[1] if len(sys.argv) >=2 else "bla2.png")
image = image.resize((1000, 800), Image.ANTIALIAS)
canvas = Tkinter.Canvas(window, width=image.size[0], height=image.size[1])
canvas.pack()
image_tk = ImageTk.PhotoImage(image)
canvas.create_image(image.size[0]//2, image.size[1]//2, image=image_tk)
def callback(event):
print "clicked at: ", event.x, event.y
canvas.bind("<Button-1>", callback)
Tkinter.mainloop()
PIL只是一个影像库,你可以用它创建图像。显示图像和捕获点击事件是用户界面引擎的一项工作。你有什么用户界面王? – Ski 2011-12-21 13:17:12