Turtle绘图库的使用
Turtle库是非常适合儿童学习的入门绘图库。绘画的过程就像拿一支画笔在画布画画一样,非常直观和易于理解。下面举几个例子并用提到的这些例子作一些练习。
- 设定画布大小:setup(canvas_width, canvas_high, coordinate_x, coordinate_y)
- 设定画笔笔迹大小:pensize(number)
- 设定画笔颜色:pencolor(color in number)
- 设定画笔行进方向:seth(angle)
- 提起画笔:penup()
- 放下画笔:pendown()
- 画直线:fd(distance)
- 画圆:circle(radius)
扩展阅读
Python标准库Turtle文档
练习
import turtle as t
import random as r
def randomcolor():
color = (r.random(), r.random(), r.random())
return color
def moveto(x, y):
t.penup()
t.goto(x, y)
t.pendown()
# set canvas dimension
t.setup(800, 800, 200, 200)
# draw 2 lines to separate the canvas in 4 zones
t.pensize(1)
t.pencolor(randomcolor())
moveto(-400, 0)
t.fd(800)
moveto(0, 400)
t.seth(-90)
t.fd(800)
t.pensize(5)
t.pencolor(randomcolor())
# draw a square
moveto(-300, 100)
for i in range(4):
t.seth(90 * i)
t.fd(200)
# a hexagon
moveto(100, 80)
for i in range(6):
t.seth(i * 60)
t.fd(150)
# a special form
moveto(-280, -320)
param = 9
for i in range(param):
t.seth(i * 720 / param)
t.fd(200)
# circles
moveto(200, -350)
t.seth(0)
for i in range(4):
t.circle(i * 20 + 100)
t.done()
函数练习
编程中经常需要自定义函数,以方便重复使用。把上面的代码稍微加以改变,自定义一些函数,得到的是同一个运行结果。
import turtle as t
import random as r
def randomcolor():
color = (r.random(), r.random(), r.random())
return color
def moveto(x, y):
t.penup()
t.goto(x, y)
t.pendown()
def square(a):
for i in range(4):
t.seth(90 * i)
t.fd(a)
def hexagon(a):
for i in range(6):
t.seth(i * 60)
t.fd(a)
def myform(param):
for i in range(param):
t.seth(i * 720 / param)
t.fd(200)
def circles(num):
t.seth(0)
for i in range(num):
t.circle(i * 20 + 100)
# set canvas dimension
t.setup(800, 800, 200, 200)
# draw 2 lines to separate the canvas in 4 zones
t.pensize(1)
t.pencolor(randomcolor())
moveto(-400, 0)
t.fd(800)
moveto(0, 400)
t.seth(-90)
t.fd(800)
t.pensize(5)
t.pencolor(randomcolor())
# draw a square
moveto(-300, 100)
square(200)
# a hexagon
moveto(100, 80)
hexagon(150)
# a special form
moveto(-280, -320)
myform(9)
# circles
moveto(200, -350)
circles(4)
t.done()