Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display picture and get mouse click coordinate on it [closed]

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!

like image 416
Alex Avatar asked Mar 31 '11 14:03

Alex


People also ask

How do I get the coordinates of a mouse click on a canvas element?

The dimension of the canvas is found using the getBoundingClientRect() function. This method returns the size of an element and its position relative to the viewport. The position of x-coordinate of the mouse click is found by subtracting the event's x position with the bounding rectangle's x position.


1 Answers

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 :).

like image 183
Symon Avatar answered Sep 20 '22 22:09

Symon