【发布时间】:2018-12-06 09:21:04
【问题描述】:
我正在加载带有多个多边形的 python 字典。多边形点是通过鼠标点击图像的不同位置获得的。该脚本向用户显示图像以选择多边形的不同点。用户将通过鼠标右键单击不同的位置。当用户单击鼠标左键时,会创建一个多边形并将其添加到带有标签的字典 Dict_Polygons 中。列表 list_of_points 被清除,因为新多边形的新点将添加到此列表中。问题是 Dict_Polygon 没有加载项目。这是完整的代码。
import math
import pickle
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
def draw_lines(event):
mouse_xy = (event.x, event.y)
func_Draw_lines(mouse_xy)
def func_Draw_lines(mouse_xy):
func_Draw_Dot(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 func_Draw_Dot(coord):
x_coord, y_coord=coord
#draw dot over position which is clicked
x1, y1 = (x_coord - 1), (y_coord - 1)
x2, y2 = (x_coord + 1), (y_coord + 1)
canvas.create_oval(x1, y1, x2, y2, fill='green', outline='green', width=5)
# This function will be called when the user wants to specify class, so a polygon will be drawn.
def func_draw_polygon(event):
numberofPoint=len(list_of_points)
if numberofPoint>2:
print ("test")
canvas.create_polygon(list_of_points, fill='', outline='green', width=2)
Dict_Polygon[label]=list_of_points
list_of_points[:]=[]
# del list_of_points[:] # clear list elements to add new polygon points
canvas.old_coords=None
global label
label=label+1
print (Dict_Polygon.items())
else:
print('Select minemum 3 points')
# Main function
if __name__ == '__main__':
root = Tk()
# Input image
img = Image.open("e.png")
# 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>", func_draw_polygon)
root.mainloop()
【问题讨论】:
-
首先你需要修复你的导入和缩进。您导入 tkinter 两次并尝试导入 Image 和 ImageTK 两次,甚至没有引用 PIL。
-
您将
list_of_points添加到字典中,然后删除该列表中的所有项目。为什么您希望数据在删除后仍然存在? -
Mike-SMT 我更新了代码。谢谢。
-
Bryan Oakley 我想将 list_of_points 添加到字典中,并想将新点添加到 list_of_points,所以我清除了它。如何处理这个。我的输出应该是具有多个 list_of_points 的字典。
-
您的导入仍然是错误的。从您提供的代码中,您需要的唯一导入是
import Tkinter as tk和from PIL import Image, ImageTk。
标签: python canvas tkinter tkinter-entry