回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我试图根据文本文件中给出的信息绘制形状,<code>DrawOnCanvas</code>函数的规范如下:</p>
<p>编写并测试第一行为的函数</p>
<pre><code>def drawOnCanvas(can, shape):
</code></pre>
<p>它将字典形状表示的形状添加到tkinter画布上。以下代码片段说明了函数的操作:</p>
<pre><code>from tkinter import *
root = Tk()
can = Canvas(root,width = 200, height = 100)
can.pack()
shape1 = {'bounds': [20, 20, 80, 50], 'kind': 'rect', 'fill': True}
shape2 = {'bounds': [80, 50, 20, 35], 'kind': 'tri', 'fill': False}
drawOnCanvas(can, shape1)
drawOnCanvas(can, shape2)
root.mainloop()
</code></pre>
<p>我的代码目前看起来像这样,但它只显示矩形,而不是三角形,我不知道我应该如何做三角形</p>
<pre><code>import tkinter as tk
def readShapes(filename):
with open(filename) as openedFile:
textSplit = []
for line in openedFile:
# str.rstrip() removes trailing "\n"
splitList = line.rstrip().split()
textSplit.append({
"kind": splitList[0],
"bounds": splitList[1:5],
"fill": splitList[5]
})
return textSplit
shapeCoords = readShapes("foot_horiz.txt")
print(*shapeCoords, sep="\n")
def drawOnCanvas(can, shape):
if shape["kind"] == "rect":
can.create_rectangle(shape['bounds'], fill = 'black')
if shape["kind"] == "tri":
can.create_polygon(shape['bounds'], fill = 'black')
root = tk.Tk()
can = tk.Canvas(root, bg='white', height=500, width=500)
can.pack()
for shape in shapeCoords:
drawOnCanvas(can, shape)
root.mainloop()
</code></pre>
<p>Foot horizon包含以下信息:</p>
<pre><code>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
</code></pre>
<p>提前谢谢你</p>