首页 > 解决方案 > python/tkinter 新手,不知道我做错了什么?

问题描述

我正在尝试从文本文件中给出的信息中绘制形状,该DrawOnCanvas函数的规范如下:

编写并测试一个函数,其第一行是

def drawOnCanvas(can, shape):

并将字典形状表示的形状添加到 tkinter Canvas 中。以下代码片段说明了函数的操作:

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()

我的代码目前看起来像这样,但它只显示矩形,而不是三角形,我不知道我应该如何做三角形?

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()

英尺地平线包含以下信息:

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

先感谢您!

标签: pythonpython-3.xtkinterpolygontkinter-canvas

解决方案


一个多边形项目至少需要三组坐标。你只提供两个。你不能画一个只有两个点的三角形。


推荐阅读