我想用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