【问题标题】:Python: Passing coordinates from text file to TurtlePython:将坐标从文本文件传递给 Turtle
【发布时间】:2014-04-17 05:53:51
【问题描述】:

我有一个带有坐标的测试文件,我的目标是创建一个函数,该函数接受文本文件并将其转换为坐标以在海龟中绘制以绘制图像:

river, 5
500, 500
-500, 360
400, 500

shadow, 4
500, 300
5, 500
300, 400

到目前为止,我有以下内容

f =open("coordinates.txt", "r")
for line in f:
    line=line.split(",")
    data=[]
    if line:
        data.append([i.strip() for i in line])

运行后我得到以下信息:

    [['river', '5']]
    [['500', '500']]
    [['-500', 360]]
    [['400', '500']]
    [['']]
    [['shadow', '4']]
    [['500', '300']]
    [['5', '500']]
    [['300', '400']]
    [['']]

但是当我将它通过海龟时,它会破裂并且不起作用。我的海龟函数如下:

p=[]
letter=block[0]
for line in block[1:]:
          l.append(line)
k=p[0]
turtle.setpos(k[0],k[1])

【问题讨论】:

  • block的内容是什么?
  • 另外,您能否更具体地了解哪些中断如何以及哪些不起作用?比如哪一行引发了哪个错误等
  • 块在渲染成列表时来自文件
  • 所以block 等于data?还是它的一部分?
  • 块等于数据

标签: python-3.x turtle-graphics


【解决方案1】:

这似乎是代码的随机集合而不是程序。下面是我从数据和代码重构程序的意图。数据被读入如下列表:

[('river', '5'), (500, 500), (-500, 360), (400, 500), ('shadow', '4'), (500, 300), (5, 500), (300, 400)]

然后用海龟画线。

import turtle

turtle.setup(1000, 1000)

data = []

with open('coordinates.txt') as my_file:
    for line in my_file:
        line = line.rstrip()

        if line:
            x, y = line.split(', ', maxsplit=1)

            try:
                data.append((int(x), int(y)))
            except ValueError:
                data.append((x, y))

print(data)

turtle.penup()

for pair in data:
    if isinstance(pair[0], int):
        turtle.setpos(pair)
        turtle.pendown()
    else:
        print('Drawing {} ({})'.format(*pair))
        turtle.penup()

turtle.hideturtle()

turtle.done()

我不能说示例图很有趣:

【讨论】:

    猜你喜欢
    • 2013-01-07
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多