# python animation 轨迹_Python实例：自动轨迹绘制

1. 问题分析

Python的 turtle 库通过写代码的方式来绘图，现在我们要根据数据来绘制轨迹。

300,0,144,1,0,0

300,0,144,0,1,0

300,0,144,0,0,1

300,0,144,1,1,0

300,0,108,0,1,1

184,0,72,1,0,1

2.实例讲解

300,0,144,1,0,0

300,0,144,0,1,0

#AutoTraceDraw.py

import turtle as t

t.title('自动轨迹绘制')

t.setup(800, 600, 0, 0)

t.pencolor("red")

t.pensize(5)

#数据读取

datals = []

f = open("data.txt")

for line in f:

line = line.replace("\n","")

datals.append(list(map(eval, line.split(","))))

f.close()

#自动绘制

for i in range(len(datals)):

t.pencolor(datals[i][3],datals[i][4],datals[i][5])

t.fd(datals[i][0])

if datals[i][1]:

t.right(datals[i][2])

else:

t.left(datals[i][2])

300,0,144,1,0,0

300,0,144,0,1,0

300,0,144,0,0,1

300,0,144,1,1,0

300,0,108,0,1,1

184,0,72,1,0,1

184,0,72,0,0,0

184,0,72,0,0,0

184,0,72,0,0,0

184,1,72,1,0,1

184,1,72,0,0,0

184,1,72,0,0,0

184,1,72,0,0,0

184,1,72,0,0,0

184,1,720,0,0,0

for line in f:

line = line.replace("\n","")

datals.append(list(map(eval, line.split(","))))

print(datals)

f.close()

line = line.replace("\n","") 将文件最后的换行符转换为空字符串，去掉换行的信息，然后再赋给 line

map函数：将第一个参数的功能作用于第二个参数的每一个元素。简单地说就是对一个列表或者一个集合，这样的组合数据类型的每一个元素，都执行一次第一个参数所对应的函数。map()函数更多解释请看：https://www.runoob.com/python/python-func-map.html

3. 自动轨迹绘制实例的举一反三