简体   繁体   English

如何在画布上单击鼠标上的图像以创建多边形Tkinter Python

[英]How to create polygon on mouse clicks on image in canvas tkinter python

The task is to create multiple polygons on image by mouse clicks on different positions on image. 任务是通过在图像的不同位置上单击鼠标,在图像上创建多个多边形。 I used Python tkinter for this task. 我将Python tkinter用于此任务。 I displayed the image to user. 我向用户显示了图像。 I got the x,y co-ordinates when user clicks on image. 当用户单击图像时,我得到了x,y坐标。 How to create polygon from different co-ordinates on which the user clicked. 如何从用户单击的不同坐标创建多边形。 Initially, I want to create simple line on mouse click but as the number of selected points increases, it should create polygon. 最初,我想通过单击鼠标来创建简单的线条,但是随着所选点数的增加,它应该创建多边形。 This is the part of code I did for this task. 这是我为此任务编写的代码部分。

# Function to get the co-ordianates of  mouse clicked position and draw polygons
def draw_plygons(event):
    mouse_xy = (event.x, event.y)

# Draw canvas for iput image to pop up image for clicks
    filename = ImageTk.PhotoImage(img)
    canvas = Canvas(root,height=img.size[0],width=img.size[0])
    canvas.image = filename
    canvas.create_image(0,0,anchor='nw',image=filename)
    canvas.pack()
# bind function to canvas to generate event
    canvas.bind("<Button 3>", draw_polygons)
    root.mainloop()

Here is the solution, How I did it. 这是解决方案,我是如何做到的。

def draw_polygons(event):
        mouse_xy = (event.x, event.y)

I collected all the clicked points in list_of_points list and then drawn using: 我收集了list_of_points列表中的所有单击的点,然后使用以下命令进行绘制:

canvas.create_polygon(list_of_points, fill='', outline='green', width=2)

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

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