TypeError:函数正好接受2个参数(给定1个)

时间:2018-07-17 13:48:10

标签: python tkinter python-imaging-library

尝试了不同的可能性后,最终要发布:

该程序将向用户显示图像。用户将使用鼠标单击来单击图像的不同区域。每次单击鼠标都会在list_of_points列表中收集点。右键单击,我想从list_of_points列表中生成一个多边形。多边形库必须为

  

PIL.ImageDraw.Draw.polygon(xy,fill = None,outline = None)

我反复遇到以下错误:

  

TypeError:函数正好接受2个参数(给定1个参数)

和此错误:

  

self.draw.draw_polygon(xy,墨水,0)   SystemError:新样式的getargs格式,但参数不是元组

下面是代码:

from Tkinter import *
import Image, ImageTk, ImageDraw
import numpy as np

coord=[]  # for saving coord of each click position
Dict_Polygon={}   # Dictionary for saving polygon
list_of_points=[]
flag=True
label=0

# Input image
img = Image.open("test.jpg")
draw = ImageDraw.Draw(img)
def draw_lines(event):

    mouse_xy = (event.x, event.y)
    func_Draw_lines(mouse_xy)


def func_Draw_lines(mouse_xy):

    center_x, center_y = mouse_xy
    if canvas.old_coords:
            x1, y1 = canvas.old_coords
            canvas.create_line(center_x, center_y, x1, y1)

    # add clicked positions to list
    if flag==True:
        list_of_points.append(mouse_xy)
        canvas.old_coords = center_x, center_y

def draw_poly(event):

    numberofPoint=len(list_of_points)
    if numberofPoint>2:

        #draw =ImageDraw.Draw(img)
        poly=zip(list_of_points)
        print(poly)

        draw.polygon(poly, fill=None, outline=(255, 0, 0))
     #   label= canvas.create_polygon(list_of_points, fill='', outline='green', width=2)
        canvas.old_coords=None
        list_of_points[:]=[]

# Main function
if __name__ == '__main__':

    root = Tk()    

# 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()
    canvas.old_coords = None
# bind function to canvas to generate event
    canvas.bind("<Button 3>", draw_lines)
    canvas.bind("<Button 1>", draw_poly)
    root.mainloop()

`

2 个答案:

答案 0 :(得分:3)

您需要类似-

的格式
[(411, 113), (158, 169), (344, 364)]

但是您正在传递元组的元组-

((411, 113),), ((158, 169),), ((344, 364),)]

尝试这种结构-

[(432, 224), (196, 245), (268, 379)]

或者直接列表也可以-

[432, 224, 196, 245, 268, 379]

查看文档here

元组的元组在需要两个参数时成为该函数的一个参数。您不需要zip(poly),只需传递numberofPoint就可以。让我知道是否有帮助

答案 1 :(得分:0)

当我直接将list_of_points传递给draw.polygon时,它可以正常工作,因此不需要任何转换。

但是,多边形是在PIL图像上绘制的,而不是在画布上显示的PhotoImage上绘制的。因此,要查看多边形,您需要更新PhotoImage。到达d的方法是使用.paste的{​​{1}}方法。

这是ImageTk.PhotoImage函数,具有以下更改:

draw_poly
相关问题