Get Mouse position on click in Python

Im trying to get the mouse position after clicking on an opened image, and saving coordinates.

I was able to do this in IJ Macro because there is some example code, but not sure how to go at it in python. Could someone provide some tips?

Below is the IJ Macro code that I want to convert.

//open image
open("C:\\Users\\dleger\\Documents\\NIKON OUT PROCESS\\Test NIS IMAGE SAVE folder\\image1.nd2");

//user can click on the image
      while (running==true) {
          getCursorLoc(x, y, z, flags);       
             if (flags&leftButton!=0){             
              xsave = x;
              ysave = y;
              print("Saved values","x=",xsave," y=",ysave);
//save the xcoord to a file"C:\\Users\\dleger\\Documents\\NIKON OUT PROCESS\\threshold.txt");
print(file, xsave);

Hello Dlite -

Use jython (python) to define and instantiate a MouseListener
and attach it to the ImageCanvas of your ImagePlus.

Here is a complete, runnable jython script that illustrates this:

from java.awt.event import MouseAdapter

from ij import IJ
from ij.gui import WaitForUserDialog

class DliteMouseListener (MouseAdapter):
    def __init__ (self):
        self.xSave = 0
        self.ySave = 0
    def mouseClicked (self, e):
        print 'In DliteMouseListener: e.getX() =', e.getX(), ', e.getY() =', e.getY()
        self.xSave = e.getX()
        self.ySave = e.getY()

imp = IJ.createImage ('ramp', '8-bit ramp', 256, 256, 1)

dML = DliteMouseListener()

imp.getCanvas().addMouseListener (dML)

for  i in range (1, 4):
    wUD = WaitForUserDialog ('Click Image ' + str (i), 'Quick! Quick!!!')
    print 'In script: i =', i, ', x =', dML.xSave, ', y =', dML.ySave

If you want further control over how you handle the mouse, take
a look at the methods in MouseListener and MouseEvent.

Thanks, mm


thanks for posting so Quick Quick! :slight_smile: