How to display picture and get mouse click coordinate on it

Alex picture Alex · Mar 31, 2011 · Viewed 40.6k times · Source

I am wondering if it is possible in Python (Windows) to show some picture, then click with the mouse on this picture and get the coordinates of this click relative to picture edges.

Thanks!

Answer

Symon picture Symon · Mar 31, 2011

Yes it is possible and pretty easy once you understand tkinter, here's a quick script:

from Tkinter import *
from tkFileDialog import askopenfilename
import Image, ImageTk

if __name__ == "__main__":
    root = Tk()

    #setting up a tkinter canvas with scrollbars
    frame = Frame(root, bd=2, relief=SUNKEN)
    frame.grid_rowconfigure(0, weight=1)
    frame.grid_columnconfigure(0, weight=1)
    xscroll = Scrollbar(frame, orient=HORIZONTAL)
    xscroll.grid(row=1, column=0, sticky=E+W)
    yscroll = Scrollbar(frame)
    yscroll.grid(row=0, column=1, sticky=N+S)
    canvas = Canvas(frame, bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set)
    canvas.grid(row=0, column=0, sticky=N+S+E+W)
    xscroll.config(command=canvas.xview)
    yscroll.config(command=canvas.yview)
    frame.pack(fill=BOTH,expand=1)

    #adding the image
    File = askopenfilename(parent=root, initialdir="C:/",title='Choose an image.')
    img = ImageTk.PhotoImage(Image.open(File))
    canvas.create_image(0,0,image=img,anchor="nw")
    canvas.config(scrollregion=canvas.bbox(ALL))

    #function to be called when mouse is clicked
    def printcoords(event):
        #outputting x and y coords to console
        print (event.x,event.y)
    #mouseclick event
    canvas.bind("<Button 1>",printcoords)

    root.mainloop()

Unedited it will print using the default window coordinate system to the console. The canvas widget makes the top left corner the 0,0 point so you may have to mess around with the printcoords function. To get the loaded picture dimension you would use canvas.bbox(ALL), and you might want to switch to using canvasx and canvasy coords instead of how it is. If you're new to tkinter; google should be able to help you finish it from here :).