user3115691
user3115691

Reputation: 95

Get pixel location from mouse click in TKinter

I'm quite new to Python and have been unsuccessful in finding a way around this problem. I have a GUI using TKinter that displays an image using Label. I would like the user to be able to click on two places in the image and use those two pixel locations elsewhere.

Below is the basic code I'm using so far, but I'm unable to return the pixel locations. I believe bind is not what I want to use, is there another option?

px = []
py = []

def onmouse(event):
        px.append(event.x)
        py.append(event.y)
        return px,py

self.ImgPanel.bind('<button-1>',onmouse)

If I try to use:

px,py = self.ImgPanel.bind('<button-1>',onmouse)

I get an error "Too many values to unpack"

Upvotes: 1

Views: 3197

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386352

bind is what you want, if you want to capture the x,y coordinate of the click. However, functions called from bindings don't "return". Technically they do, but they return a value to the internals of Tkinter.

What you need to do is set an instance or global variable within the bound function. In the code you included in your question, if you add global px,py, you can then use those values in other code.

Upvotes: 1

Related Questions