<p>您将获得各种多边形的边界框;在<code>tkinter.Canvas</code>上绘制多边形需要一系列顶点。一种方法是使用边界框值来优化顶点值。这可以在解析文件时完成</p>
<p>例如(使用字符串替换文件):</p>
<pre><code>import tkinter as tk
def drawOnCanvas(canvas, shape):
"""takes a shape, a bbox, and a fill, and draws a polygon on canvas"""
sh, bbox, fill = shape
vertices = make_vertices_from_bbox(sh, bbox)
color = 'white'
if fill:
color = 'black'
canvas.create_polygon(*vertices, fill=color)
def make_rect_vertices(bbox):
"""returns the vertices for a rectangle"""
x0, y0, x2, y2 = bbox
x1, y1 = x0, y2
x3, y3 = x2, y0
return (x0, y0, x1, y1, x2, y2, x3, y3)
def make_tri_vertices(bbox):
"""returns the vertices for a triangle
Note that there are many alternate ways to choose the vertices
"""
x0, y0, x2, y2 = bbox
x1, y1 = x0, y2
return (x0, y0, x1, y1, x2, y2)
def make_vertices_from_bbox(shape, bbox):
"""calls the proper helper and returns the vertices"""
if shape == 'rect':
return make_rect_vertices(bbox)
if shape == 'tri':
return make_tri_vertices(bbox)
raise ValueError(f'the shape {shape} is not defined')
def parse_f(f):
shapes = []
for line in f.split('\n'):
poly, x0, y0, x1, y1, fill = line.split()
shapes.append((poly, (int(x0), int(y0), int(x1), int(y1)), eval(fill)))
return shapes
f = """rect 20 20 80 50 True
tri 80 50 20 35 False
rect 80 20 115 62 True
tri 122 27 143 20 True
tri 122 27 143 34 True
tri 122 41 143 34 True
tri 122 41 143 48 True
tri 122 55 143 48 True
tri 122 55 143 62 True"""
parse_f(f)
root = tk.Tk()
canvas = tk.Canvas(root, bg='white', height=500, width=500)
canvas.pack()
for shape in parse_f(f):
drawOnCanvas(canvas, shape)
root.mainloop()
</code></pre>
<p><a href="https://i.stack.imgur.com/EhbQI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EhbQI.png" alt="enter image description here"/></a></p>