python/tkinter新手,不知道我做错了什么?

2024-10-03 21:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图根据文本文件中给出的信息绘制形状,DrawOnCanvas函数的规范如下:

编写并测试第一行为的函数

def drawOnCanvas(can, shape):

它将字典形状表示的形状添加到tkinter画布上。以下代码片段说明了函数的操作:

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

Foot horizon包含以下信息:

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

提前谢谢你


Tags: 函数recttruetkinterdefrootfillcan
2条回答

您将获得各种多边形的边界框;在tkinter.Canvas上绘制多边形需要一系列顶点。一种方法是使用边界框值来优化顶点值。这可以在解析文件时完成

例如(使用字符串替换文件):

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

enter image description here

多边形项至少需要三组坐标。你只提供了两个。不能仅用两点绘制三角形

相关问题 更多 >