turtle won't draw because TypeError: unsupported operand type(s) for -: 'tuple' and 'float'

turtle won't draw because TypeError: unsupported operand type(s) for -: 'tuple' and 'float'

我正在尝试绘制字典 dct 中给出的圆圈,然后在列表 e 中作为元组给出的圆圈名称之间画线。

import turtle
e = [('A','B') , ('A','C') , ('B' , 'C')]
dct = {'A': (250.0, 0.0), 'B': (-125.0, 216.5), 'C': (-125.0, -216.50)}
for x in dct :
    turtle.penup()
    turtle.goto(dct[x][0] , dct[x][1])
    turtle.pendown()
    turtle.circle(20)
    turtle.write(x, move=False, align='left', font='Arial')
    turtle.penup()
for y in range(len(e)) :
    turtle.goto(dct[e[y][0]], dct[e[y][1]])
    turtle.pendown()
    turtle.goto(dct[e[y+1][0]], dct[e[y+1][1]])
    turtle.penup()

但它给了我很长的错误,最后是:

  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/turtle.py", line 1777, in goto
    self._goto(Vec2D(x, y))
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/turtle.py", line 3166, in _goto
    diff = (end-start)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/turtle.py", line 263, in __sub__
    return Vec2D(self[0]-other[0], self[1]-other[1])
TypeError: unsupported operand type(s) for -: 'tuple' and 'float'

像这样改变你的第二个循环:

import turtle
e = [('A','B') , ('A','C') , ('B' , 'C')]
dct = {'A': (250.0, 0.0), 'B': (-125.0, 216.5), 'C': (-125.0, -216.50)}
for x in dct :
    turtle.penup()
    turtle.goto(dct[x][0] , dct[x][1])
    turtle.pendown()
    turtle.circle(20)
    turtle.write(x, move=False, align='left', font='Arial')
    turtle.penup()
for y in range(len(e)) :
    turtle.goto(dct[e[y][0]][0], dct[e[y][0]][1])
    turtle.pendown()
    turtle.goto(dct[e[y][1]][0], dct[e[y][1]][1])
    turtle.penup()

而不是:

turtle.goto(dct[e[y][0]], dct[e[y][1]])

turtle.goto(dct[e[y+1][0]], dct[e[y+1][1]])

你需要:

turtle.goto(dct[e[y][0]][0], dct[e[y][0]][1])

turtle.goto(dct[e[y][1]][0], dct[e[y][1]][1])

我相信您将自己的索引设置得太复杂了,这让您感到困惑。让我们通过将数据解构为 for 循环的一部分来简化事情,并意识到我们可以将元组或单个值传递给海龟 goto() 函数:

import turtle

RADIUS = 20

e = [('A', 'B'), ('B', 'C'), ('C', 'A')]

dct = {
    'A': (250.0, 0.0),
    'B': (-125.0, 216.5),
    'C': (-125.0, -216.5),
}

for name, (x, y) in dct.items():
    turtle.penup()
    turtle.goto(x, y - RADIUS)
    turtle.pendown()
    turtle.circle(RADIUS)
    turtle.write(name, font='Arial')

for start, end in e:
    turtle.penup()
    turtle.goto(dct[start])
    turtle.pendown()
    turtle.goto(dct[end])

turtle.hideturtle()
turtle.done()