简体   繁体   English

通过在TKinter中单击鼠标获取像素位置

[英]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. 我对Python还是很陌生,未能找到解决此问题的方法。 I have a GUI using TKinter that displays an image using Label. 我有一个使用TKinter的GUI,它使用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? 我相信bind不是我想要使用的,还有其他选择吗?

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" 我收到一条错误消息:“要解压缩的值太多”

bind is what you want, if you want to capture the x,y coordinate of the click. 如果要捕获点击的x,y坐标,bind是您想要的。 However, functions called from bindings don't "return". 但是,从绑定调用的函数不会“返回”。 Technically they do, but they return a value to the internals of Tkinter. 从技术上讲,它们可以,但是它们向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. 在问题中包含的代码中,如果添加global px,py ,则可以在其他代码中使用这些值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM