使用click事件计算两个坐标之间的距离

2024-04-19 10:29:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以在我的面板上显示一个图像,我需要的是点击图片中的两个点并计算它们之间的距离。我在使用事件处理程序以及如何在Java中类似于扫描仪时遇到问题。例如,如果我运行程序并在图像中的某个地方单击一次,它将同时运行所有3个方法,这将导致错误。在

root = Tk()

img = ImageTk.PhotoImage(Image.open("target.PNG"))
#img = cv2.imread("target.PNG")
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")

def leftClick(event):
   global x0,y0
   x0 = event.x
   y0 = event.y
   return x0, y0

panel.bind("<Button-1>", leftClick)

def rightClick(event):
   global x1,y1
   x1 = event.x
   y1 = event.y
   return x1, y1    

 panel.bind("<Button-1>", rightClick)

def getDistance(event):
    distance = math.sqrt( ((x0-x1)**2)+((y0-y1)**2) )
    print(distance)

panel.bind("<Button-1>", getDistance)
root.mainloop()

我想要的是一次执行一次每一步。计算距离的最后一步可以在方法之外完成,这并不重要。我只需要先找到坐标。请告诉我怎样才能解决这个问题。在


Tags: 方法图像event距离targetimgbinddef
2条回答

你可以试试这两种:

过程1(使用鼠标左键单击、右键单击、中键(滚动)单击):

下面的代码需要

(x0,y0)从鼠标左键单击

(x1,y1)从鼠标右键单击

然后在鼠标中键(滚动)上打印它们之间的距离

from tkinter import *
from PIL import ImageTk, Image
import math

root = Tk()

img = ImageTk.PhotoImage(Image.open("Logo.png"))
panel = Label(root, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
x0 = 0
y0 = 0
x1 = 0
y1 = 0


def leftClick(event):
    global x0, y0
    x0 = event.x
    y0 = event.y
    # return [x0, y0]


panel.bind("<Button-1>", leftClick)


def rightClick(event):
    global x1, y1
    x1 = event.x
    y1 = event.y
    # return x1, y1


panel.bind("<Button-3>", rightClick)


def getDistance(event):
    global x0, y0, x1, y1
    distance = math.sqrt(((x0 - x1)**2)+((y0 - y1)**2))
    print(distance)


panel.bind("<Button-2>", getDistance)
root.mainloop()

过程2(仅使用鼠标左键单击):

下面的代码需要

(x0,y0)从第一个鼠标左键单击

(x1,y1)从第二个鼠标左键单击

然后在第三次鼠标左键单击打印它们之间的距离

^{pr2}$

下面是一个从起点到终点计数距离的演示,它需要鼠标左键拖动操作。在

import tkinter as tk
from PIL import ImageTk, Image
import math
start_point_x, start_point_y, end_point_x, end_point_y = 0, 0, 0, 0

def mouse_left_down_detection(event):
    global start_point_x, start_point_y
    start_point_x = event.x
    start_point_y = event.y

def mouse_left_release_detection(event):
    global end_point_x, end_point_y
    end_point_x = event.x
    end_point_y = event.y
    print(start_point_x, start_point_y, end_point_x, end_point_y)
    print(get_instance(start_point_x, start_point_y, end_point_x, end_point_y))

def get_instance(x1, y1, x2, y2):
    return math.sqrt((pow(abs(x2-x1), abs(x2-x1))+pow(abs(y2-y1), abs(y2-y1))))

image_path = "andy.jpg"
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(image_path))
panel = tk.Label(root, image=img)
# Bind event mouse left down
panel.bind("<Button-1>", mouse_left_down_detection)
# Bind event mouse left release and calculate distance
panel.bind("<ButtonRelease-1>", mouse_left_release_detection)
panel.pack(side="bottom", fill="both", expand="yes")
root.mainloop()

相关问题 更多 >