Capture x, y Coordinates with Python PIL

I want to show the image to the user using PIL, and when the user clicks on it anywhere in this image, I want def onmousedown (x, y) to be called. I will do some additional functions in this function. How can I do this in PIL?

Thanks,

+6
source share
2 answers

PIL will not do this alone - PIL is an image management library without user interfaces - it has a show method that opens an external program that displays the image but does not bind to the Python process.

Therefore, in order for the user to interact with the image, you need to create a GUI program using one of the consolidated toolkits for use with Python - the better known are Tkinter, GTK and Qt4. Tkinter is interesting in that it comes with a preinstalled Windows Python installation and is therefore more accessible to users of this system. Windows users would have to download and install the gtk or qt libraries separately in order to be able to use your program if you decide to use other tools.

Here is a minimalist Tkinter example with a clickable image:

 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() 
+8
source

Here is another related post

How to display an image and get the coordinate of a mouse click on it

In Ubuntu to install

sudo apt-get install python python-tk idle python-pmw python-imaging python-imaging-tk

Then everything works.

I added resizing to the @jsbueno solution and fixed the import problem.

 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() 
+2
source

Source: https://habr.com/ru/post/904237/


All Articles