Turtle绘图库的使用

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

运行结果

运行结果

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值