文章目录
前言
本文基于Python 3.7.13
版本的官方文档,本人整理并加以补充。如有错误,敬请指正。
本节中的大部分示例都使用 Turtle 类的一个实例,命名为 turtle
。
海龟基本运动函数
forward() | fd()
用法
turtle.forward(distance)
turtle.fd(distance)
参数:distance – 一个数值 (整型或浮点型)
用处
海龟前进 distance 指定的距离,方向为海龟的朝向。
示例
>>> turtle.position() #获取海龟坐标
(0.00,0.00)
>>> turtle.forward(25)
>>> turtle.position()
(25.00,0.00)
>>> turtle.forward(-75)
>>> turtle.position()
(-50.00,0.00)
动画演示
back() | bk() | backward()
用法
turtle.back(distance)
turtle.bk(distance)
turtle.backward(distance)
参数:distance – 一个数值 (整型或浮点型)
用处
海龟后退 distance 指定的距离,方向与海龟的朝向相反。不改变海龟的朝向。
示例
>>> turtle.position() #获取海龟坐标
(0.00,0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00,0.00)
动画演示
right() | rt()
用法
turtle.right(angle)
turtle.rt(angle)
参数:angle – 一个数值 (整型或浮点型)
用处
海龟右转 angle 个单位。
(单位默认为角度,但可通过 degrees()
和 radians()
函数改变设置。) 角度的正负由海龟模式确定,参见 mode()
。
示例
>>> turtle.heading() #获取海龟朝向
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0
动画演示
right() | rt()
用法
turtle.left(angle)
turtle.lt(angle)
参数:angle – 一个数值 (整型或浮点型)
用处
海龟左转 angle 个单位。
(单位默认为角度,但可通过 degrees()
和 radians()
函数改变设置。) 角度的正负由海龟模式确定,参见 mode()
。
示例
>>> turtle.heading() #获取海龟朝向
22.0
>>> turtle.left(45)
>>> turtle.heading()
67.0
动画演示
goto() | setpos() | setposition()
用法
turtle.goto(x, y=None)
turtle.setpos(x, y=None)
turtle.setposition(x, y=None)
参数:
- x – 一个数值或数值对/向量
- y – 一个数值或
None
用处
海龟移动到一个绝对坐标。如果画笔已落下将会画线。不改变海龟的朝向。
如果 y 为 None
,x 应为一个表示坐标的数值对或 Vec2D
类对象 (例如 pos()
返回的对象).
示例
>>> tp = turtle.pos() #获取海龟位置
>>> tp
(0.00,0.00)
>>> turtle.setpos(60,30)
>>> turtle.pos()
(60.00,30.00)
>>> turtle.setpos((20,80))
>>> turtle.pos()
(20.00,80.00)
>>> turtle.setpos(tp)
>>> turtle.pos()
(0.00,0.00)
动画演示
setx()
用法
turtle.setx(x)
参数:x – 一个数值 (整型或浮点型)
用处
设置海龟的横坐标为 x,纵坐标保持不变。
示例
>>> turtle.position() #获取海龟位置
(0.00,240.00)
>>> turtle.setx(10)
>>> turtle.position()
(10.00,240.00)
动画演示
sety()
用法
turtle.sety(y)
参数:y – 一个数值 (整型或浮点型)
用处
设置海龟的纵坐标为 y,横坐标保持不变。
示例
>>> turtle.position() #获取海龟位置
(0.00,40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00,-10.00)
动画演示
setheading() | seth()
用法
turtle.setheading(to_angle)
turtle.seth(to_angle)
参数:to_angle – 一个数值 (整型或浮点型)
用处
设置海龟的朝向为 to_angle。以下是以角度表示的几个常用方向:
标准模式 | logo模式 |
---|---|
0 - 东 | 0 - 北 |
90 - 北 | 90 - 东 |
180 - 西 | 180 - 南 |
270 - 南 | 270 - 西 |
示例
>>> turtle.setheading(90)
>>> turtle.heading() #获取海龟朝向
90.0
动画演示
home()
用法
turtle.home()
参数:无
用处
海龟移至初始坐标 (0,0),并设置朝向为初始方向
(由海龟模式确定,参见 mode()
)。
示例
>>> turtle.heading() #获取海龟朝向
90.0
>>> turtle.position() #获取海龟位置
(0.00,-10.00)
>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0