给我一段python代码,读取一个png文件,显示在屏幕上,然后接受鼠标的两次点击,作为对角点,形成一个矩形区域。保存区域的坐标点。
时间: 2024-12-12 10:27:08 浏览: 10
在Python中,我们可以使用`PIL`库(Pillow)来处理图像,`pyautogui`库来模拟鼠标操作,以及`tkinter`库来创建一个简单的GUI来展示图片和接收鼠标点击。下面是一个示例代码:
```python
from PIL import Image, ImageTk
import tkinter as tk
import pyautogui
# 加载PNG文件
img = Image.open('your_image.png')
width, height = img.size
# 创建一个Tk窗口并加载图片
root = tk.Tk()
canvas = tk.Canvas(root, width=width, height=height)
photo = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, image=photo, anchor=tk.NW)
def on_click(event):
if event.num == 1 and mouse_press_count == 0: # num 1表示左键
click_x = event.x
click_y = event.y
mouse_press_count += 1
print(f"First click: ({click_x}, {click_y})")
elif event.num == 1 and mouse_press_count == 1:
drag_x = event.x
drag_y = event.y
print(f"Second click: ({drag_x}, {drag_y})")
# 计算矩形区域的左上角和右下角坐标
rect_top_left = (min(click_x, drag_x), min(click_y, drag_y))
rect_bottom_right = (max(click_x, drag_x), max(click_y, drag_y))
print(f"Rectangle coordinates: ({rect_top_left[0]}, {rect_top_left[1]}), ({rect_bottom_right[0]}, {rect_bottom_right[1]})")
# 这里你可以选择如何存储或进一步处理这个区域信息
# 例如,将坐标作为元组存入列表或字典等数据结构
canvas.bind("<Button-1>", on_click) # 绑定左键单击事件
canvas.pack() # 显示图片
root.mainloop()
```
**请注意替换 'your_image.png' 为你实际的图片路径。**
阅读全文