turtle --- 海龟绘图¶
源码: Lib/turtle.py
请想象绘图区有一只机器海龟位于 x-y 平面中的起始位置 (0, 0)。 在 import turtle 之后,向它发出命令 turtle.forward(15),它将(在屏幕上!)朝它所面对的方向移动 15 个像素,随着它的移动画一条线段。 再向它发出命令 turtle.right(25),它将原地顺时针旋转 25 度。
海龟绘图是对于 1967 年 在Logo 中引入的绘图工具 的实现。 它作为一种教育工具被创建,它以即时、直观的反馈成为学习者接触编程概念的有效途径。 它还是一种无需引入外部库即可产生简单图形输出的便捷方式。
本文档包括了四个主要部分:
备注
Turtle 图形需要 tkinter 这个 可选模块。Windows 和 macOS 的 python.org 安装程序会包含这些组件,但某些 Linux 发行版及其他平台可能会将其单独打包提供。如果 import turtle 因提及 _tkinter 的错误而失败,请向您的发行商(即向您提供 Python 的人)索取相关文档。如果您计划与学习者一起使用 Turtle 图形,建议提前确认这一点。
教程¶
新用户应当从这里开始。 在本教程中我们将探索海龟绘图的一些基本知识。
启动海龟环境¶
在 Python shell 中,导入 turtle 模块的所有对象:
from turtle import *
如果你遇到了 Standard library module '_tkinter' was not found 错误,则你需要在你的系统上安装 Tk interface 软件包。
尚未显示任何内容。 要打开海龟窗口,并显示海龟图标:
showturtle()
打开一个新窗口,海龟位于中央,显示为一个指向东方的箭头。
基本绘图¶
让海龟前进 100 步:
forward(100)
你应该会看到一条由海龟绘制的线,朝向为东。改变海龟的朝向,使其向左旋转 120 度(逆时针):
left(120)
让我们继续画一个三角形:
forward(100)
left(120)
forward(100)
注意以一个箭头表示的海龟是如何随着你的操纵指向不同方向的。
尝试使用这些命令,也可以尝试 backward() 和 right() 。许多命令还具有较短的别名,例如 forward() 的别名为 fd() 。
画笔控制¶
试着改变颜色 —— 例如,color('blue') 和线宽 —— 例如,width(3) 然后再次绘制。
您也可以在不绘制线条的情况下移动海龟,即在移动前抬起画笔: up()。 要重新开始绘制,请使用 down()。
海龟的位置¶
将海龟送回起点(这适用于海龟消失在屏幕之外的情况):
home()
初始位置在海龟屏幕的中心。 如果你需要知道具体数值,可以这样获取海龟的 x-y 坐标:
pos()
初始点在 (0, 0)。
过一段时间后,也许可以考虑清空窗口这样我们就可以重新开始:
clearscreen()
使用算法绘制图案¶
使用循环,可以构建出各种几何图案:
for steps in range(100):
for c in ('blue', 'red', 'green'):
color(c)
forward(steps)
right(30)
- 当然,这仅受限于你的想象力!
让我们绘制本页面顶部的星形。 我们想要用红色线条,黄色填充:
color('red')
fillcolor('yellow')
就像用 up() 和 down() 决定是否画线一样,填充也可以打开或关闭:
begin_fill()
接下来我们将创建一个循环:
start = pos()
while True:
forward(200)
left(170)
if distance(start) < 1:
break
distance(start) < 1 是确定海龟何时回到其初始位置的好办法。
最后,完成填充:
end_fill()
(请注意只有在你给出 end_fill() 命令时才会实际进行填充。)
参考¶
海龟方法与函数¶
本节中的大部分示例都使用 Turtle 类的一个实例,命名为 turtle。
移动和绘制¶
- 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)
- 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)
- turtle.right(angle)¶
- turtle.rt(angle)¶
- 参数:
angle -- 一个数值
将海龟向右转动指定的 angle 角度。角度默认以度为单位;可以使用
degrees()或radians()更改单位。朝向的度量方式取决于海龟模式,参见mode()。>>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.0
- turtle.left(angle)¶
- turtle.lt(angle)¶
- 参数:
angle -- 一个数值
将海龟向左转动指定的 angle 角度。角度默认以度为单位;可以使用
degrees()或radians()更改单位。朝向的度量方式取决于海龟模式,参见mode()。>>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.0
- 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.goto(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.goto((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.goto(tp) >>> turtle.pos() (0.00,0.00)
- turtle.teleport(x=None, y=None, *, fill_gap=False)¶
- 参数:
x -- 一个数值或
Noney -- 一个数值或
Nonefill_gap -- 布尔
将 turtle 传送(即立即移动)到绝对位置。与
goto()不同,此处不会绘制任何线条。如果未指定 x 或 y,则该坐标将保持原值;turtle 的朝向也不会改变。如果海龟正在填充一个形状,那么在传送之前,当前绘制的形状已完成填充;随后填充将从新位置重新开始。将
fill_gap=True传入,则将继续填充同一个形状;此时,传送将被视为该形状的边界,其处理方式与使用goto()时相同。>>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.teleport(60) >>> turtle.pos() (60.00,0.00) >>> turtle.teleport(y=10) >>> turtle.pos() (60.00,10.00) >>> turtle.teleport(20, 30) >>> turtle.pos() (20.00,30.00)
在 3.12 版本加入.
- turtle.setx(x)¶
- 参数:
x -- 一个数值
设置海龟的 x 坐标为 x。 y 坐标保持不变。
>>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)
- turtle.sety(y)¶
- 参数:
y -- 一个数值
将海龟的 y 坐标设置为 y 。x 坐标保持不变。
>>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)
- 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
- 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
- turtle.circle(radius, extent=None, steps=None)¶
- 参数:
radius -- 一个数值
extent -- 一个数值或
Nonesteps -- 一个整型数值或
None
绘制一个具有给定 radius 半径的圆。圆心位于海龟左侧 radius 个单位处; extent 为一个角度,确定绘制圆的哪个部分。如果未给出 extent ,则绘制整个圆。如果 extent 不是一个完整的圆,则圆弧的一个端点是当前的画笔位置。如果 radius 为正,则按逆时针方向绘制圆弧,否则按顺时针方向绘制。最后,海龟的朝向会改变 extent 。
由于圆是用内接正多边形近似表示的, steps 确定要使用的步数。如果未给出,将自动计算。可用于绘制正多边形。
>>> turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.0 >>> turtle.circle(50) >>> turtle.position() (-0.00,0.00) >>> turtle.heading() 0.0 >>> turtle.circle(120, 180) # 画一个半圆 >>> turtle.position() (0.00,240.00) >>> turtle.heading() 180.0
- turtle.dot()¶
- turtle.dot(size)
- turtle.dot(color, /)
- turtle.dot(size, color, /)
- turtle.dot(size, r, g, b, /)
- 参数:
size -- 一个正整数或
Nonecolor -- 一个颜色字符串或颜色数值元组
使用 color 绘制一个直径为 size 的圆形点。如果未指定 size,则采用
pensize + 4和2 * pensize中较大的值;如果未指定 color,则使用当前的 pencolor。>>> turtle.home() >>> turtle.dot() >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50) >>> turtle.position() (100.00,-0.00) >>> turtle.heading() 0.0
- turtle.stamp()¶
在画布上印出一个海龟形状的拷贝并返回其 ID。 印章将放置于当前海龟位置。 返回的 ID 可被用来使用
clearstamp()删除印章。>>> turtle.color("blue") >>> stamp_id = turtle.stamp() >>> turtle.fd(50)
- turtle.clearstamp(stampid)¶
- 参数:
stampid -- 一个整数
删除具有给定 stampid 的印章。 stampid 必须为之前
stamp()调用的返回值。>>> turtle.position() (150.00,-0.00) >>> turtle.color("blue") >>> astamp = turtle.stamp() >>> turtle.fd(50) >>> turtle.position() (200.00,-0.00) >>> turtle.clearstamp(astamp) >>> turtle.position() (200.00,-0.00)
- turtle.clearstamps(n=None)¶
- 参数:
n -- 一个整型数值或
None
删除全部或者最前或最后的 n 个海龟印章。 如果未给出 n,则删除全部印章。 如果 n 为正数,则删除最前的 n 个印章。 如果 n 为负数,则删除最后的 n 个印章,因此 -2 为删除最后的两个。
>>> for i in range(8): ... unused_stamp_id = turtle.stamp() ... turtle.fd(30) >>> turtle.clearstamps(2) >>> turtle.clearstamps(-2) >>> turtle.clearstamps()
- turtle.undo()¶
撤消 (或连续撤消) 最近的一个 (或多个) 海龟动作。可撤消的次数由撤消缓冲区的大小决定。
>>> for i in range(4): ... turtle.fd(50); turtle.lt(80) ... >>> for i in range(8): ... turtle.undo()
- turtle.speed(speed=None)¶
- 参数:
speed -- 一个整数、字符串或
None
返回或设置海龟的速度。如果未指定 speed,则返回当前速度;否则,将海龟的速度设置为 0 到 10 之间的整数。如果 speed 的值大于 10 或小于 0.5,则将其速度设置为 0。您也可以使用这些名称来替代数字:
"fastest": 0
"fast": 10
"normal": 6
"slow": 3
“最慢”:1
速度从 1 到 10 会逐步加快线条绘制和海龟转向的动画效果。速度为 0 表示不产生任何动画:
forward()和back()会使海龟跳跃,而left()和right()则会使海龟立即转向。>>> turtle.speed() 3 >>> turtle.speed('normal') >>> turtle.speed() 6 >>> turtle.speed(9) >>> turtle.speed() 9
获取海龟的状态¶
- turtle.towards(x, y=None)¶
- 参数:
x -- 一个数值或数值对/矢量,或一个海龟实例
y -- 一个数值——如果 x 是一个数值,否则为
None
返回从海龟位置到 (x,y) 的连线的角度。如果 y 为
None,则 x 必须是一对坐标、一个Vec2D(例如由pos()返回的结果)或另一个海龟。角度从海龟的初始朝向开始度量,这取决于海龟模式,参见mode()。>>> turtle.goto(10, 10) >>> turtle.towards(0,0) 225.0
- turtle.xcor()¶
返回海龟的 x 坐标。
>>> turtle.home() >>> turtle.left(50) >>> turtle.forward(100) >>> turtle.pos() (64.28,76.60) >>> print(round(turtle.xcor(), 5)) 64.27876
- turtle.ycor()¶
返回海龟的 y 坐标。
>>> turtle.home() >>> turtle.left(60) >>> turtle.forward(100) >>> print(turtle.pos()) (50.00,86.60) >>> print(round(turtle.ycor(), 5)) 86.60254
- turtle.heading()¶
返回海龟的当前朝向。该值取决于海龟模式,参见
mode()。>>> turtle.home() >>> turtle.left(67) >>> turtle.heading() 67.0
- turtle.distance(x, y=None)¶
- 参数:
x -- 一个数值或数值对/矢量,或一个海龟实例
y -- 一个数值——如果 x 是一个数值,否则为
None
以海龟步长单位返回从海龟到 (x,y) 的距离。如果 y 为
None,则 x 必须是一对坐标、一个Vec2D(例如由pos()返回的结果)或另一个海龟。>>> turtle.home() >>> turtle.distance(30,40) 50.0 >>> turtle.distance((30,40)) 50.0 >>> joe = Turtle() >>> joe.forward(77) >>> turtle.distance(joe) 77.0
度量单位设置¶
- turtle.degrees(fullcircle=360.0)¶
- 参数:
fullcircle -- 一个数值
将角度度量单位设置为度。一个完整圆的度数被设置为 fullcircle ,默认值为 360。
>>> turtle.home() >>> turtle.left(90) >>> turtle.heading() 90.0 >>> # 将角度计量单位改为 grad (或称 gon, grade >>> # 或 gradian,等于直角的 1/100。) >>> turtle.degrees(400.0) >>> turtle.heading() 100.0 >>> turtle.degrees(360) >>> turtle.heading() 90.0
- turtle.radians()¶
将角度度量单位设置为弧度。相当于
degrees(2 * math.pi)。>>> turtle.home() >>> turtle.left(90) >>> turtle.heading() 90.0 >>> turtle.radians() >>> turtle.heading() 1.5707963267948966
画笔控制¶
绘图状态¶
- turtle.pensize(width=None)¶
- turtle.width(width=None)¶
- 参数:
width -- 一个正数或
None
返回或设置线条粗细。如果未指定 width,则返回当前的 pensize。如果 resizemode 设置为“auto”,且 turtle 形状为多边形,则该多边形将以相同的线条粗细绘制。
>>> turtle.pensize() 1 >>> turtle.pensize(10) # 从这里开始,画出宽度为10的线
- turtle.pen(pen=None, **pendict)¶
- 参数:
pen -- 一个字典或
Nonependict -- 具有下列键的关键字参数
返回或设置画笔的属性。 属性将作为一个具有下列键和值的字典返回:
"shown":
True或False"pendown":
True或False"pencolor": 颜色字符串或颜色元组
"fillcolor": 颜色字符串或颜色元组
"pensize": 一个正数
"speed": 0 到 10 范围内的数字
"resizemode": "auto", "user" 或 "noresize"
"stretchfactor": 一对正数
"shearfactor": a number
"outline": a positive number
"tilt": a number
Such a dictionary can be passed as pen to restore a former pen state. The attributes can also be given as keyword arguments, which can be used to set several of them in one statement.
>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10) >>> turtle.pen() {'shown': True, 'pendown': True, 'pencolor': 'red', 'fillcolor': 'black', 'pensize': 10, 'speed': 9, 'resizemode': 'noresize', 'stretchfactor': (1.0, 1.0), 'shearfactor': 0.0, 'outline': 1, 'tilt': 0.0} >>> penstate = turtle.pen() >>> turtle.color("yellow", "") >>> turtle.penup() >>> turtle.pen()["pencolor"] 'yellow' >>> # restore the saved pen state, but with a green fill >>> turtle.pen(penstate, fillcolor="green") >>> turtle.pen()["pencolor"] 'red' >>> turtle.pen()["fillcolor"] 'green'
- turtle.isdown()¶
若画笔处于落下状态则返回
True,处于抬起状态则返回False。>>> turtle.penup() >>> turtle.isdown() False >>> turtle.pendown() >>> turtle.isdown() True
颜色控制¶
- turtle.pencolor()¶
- turtle.pencolor(color, /)
- turtle.pencolor(r, g, b, /)
返回或设置画笔颜色。
允许以下四种输入格式:
pencolor()将当前的 pencolor 以颜色规范字符串或元组形式返回(参见示例)。该值可用作另一个
color()、pencolor()、fillcolor()或bgcolor()调用的输入。pencolor(colorstring)将 pencolor 设置为 colorstring;该变量是一个 Tk 颜色指定字符串,例如
"red"、"yellow"或"#33cc8c"。pencolor((r, g, b))将 pencolor 设置为由 r、g 和 b 组成的元组所表示的 RGB 颜色。r、g 和 b 中的每一个值必须介于 0 和 colormode 之间,其中 colormode 的取值为 1.0 或 255(参见
colormode())。pencolor(r, g, b)将 pencolor 设置为由 r、g 和 b 表示的 RGB 颜色。r、g 和 b 中的每个值必须介于 0 和 colormode 之间。
如果龟形是一个多边形,则会用新设置的 pencolor 绘制该多边形的轮廓。
>>> colormode() 1.0 >>> turtle.pencolor() 'red' >>> turtle.pencolor("brown") >>> turtle.pencolor() 'brown' >>> tup = (0.2, 0.8, 0.55) >>> turtle.pencolor(tup) >>> turtle.pencolor() (0.2, 0.8, 0.5490196078431373) >>> colormode(255) >>> turtle.pencolor() (51.0, 204.0, 140.0) >>> turtle.pencolor('#32c18f') >>> turtle.pencolor() (50.0, 193.0, 143.0)
- turtle.fillcolor()¶
- turtle.fillcolor(color, /)
- turtle.fillcolor(r, g, b, /)
返回或设置填充颜色。
允许以下四种输入格式:
fillcolor()将当前的 fillcolor 返回为颜色规范字符串,可采用元组格式(参见示例)。该字符串可作为另一个
color()、pencolor()、fillcolor()或bgcolor()调用的输入参数。fillcolor(colorstring)将 fillcolor 设置为 colorstring;该变量是一个 Tk 颜色规范字符串,例如
"red"、"yellow"或"#33cc8c"。fillcolor((r, g, b))将 fillcolor 设置为由 r、g 和 b 组成的元组所表示的 RGB 颜色。r、g 和 b 中的每个值必须介于 0 和 colormode 之间,其中 colormode 的取值为 1.0 或 255(参见
colormode())。fillcolor(r, g, b)将 fillcolor 设置为由 r、g 和 b 表示的 RGB 颜色。r、g 和 b 中的每个值必须介于 0 和 colormode 之间。
如果龟形是一个多边形,则使用该新设置的 fillcolor 绘制该多边形的内部。
>>> turtle.fillcolor("violet") >>> turtle.fillcolor() 'violet' >>> turtle.pencolor() (50.0, 193.0, 143.0) >>> turtle.fillcolor((50, 193, 143)) # 整数,而非浮点数 >>> turtle.fillcolor() (50.0, 193.0, 143.0) >>> turtle.fillcolor('#ffffff') >>> turtle.fillcolor() (255.0, 255.0, 255.0)
- turtle.color()¶
- turtle.color(color, /)
- turtle.color(r, g, b, /)
- turtle.color(pencolor, fillcolor, /)
返回或设置 pencolor 和 fillcolor。
支持多种输入格式。这些格式使用 0 到 3 个参数,具体如下:
color()返回以一对颜色描述字符串或元组表示的当前画笔颜色和填充颜色,两者可分别由
pencolor()和fillcolor()返回。color(colorstring),color((r,g,b)),color(r,g,b)输入参数如
pencolor()所示。将 pencolor 和 fillcolor 均设置为给定值。color(colorstring1, colorstring2),color((r1,g1,b1), (r2,g2,b2))相当于
pencolor(colorstring1)加fillcolor(colorstring2),使用其他输入格式的方法也与之类似。
如果龟形是一个多边形,则该多边形的轮廓和内部将采用新设置的颜色绘制。
>>> turtle.color("red", "green") >>> turtle.color() ('red', 'green') >>> color("#285078", "#a0c8f0") >>> color() ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))
另参见: Screen 方法 colormode()。
填充¶
- turtle.filling()¶
若海龟正在填充,则返回
True;否则返回False。>>> turtle.begin_fill() >>> if turtle.filling(): ... turtle.pensize(5) ... else: ... turtle.pensize(3)
- turtle.fill()¶
Fill the shape drawn in the
withblock.>>> turtle.color("black", "red") >>> with turtle.fill(): ... turtle.circle(80)
fill()is a context manager, so using it is the same as callingbegin_fill()before the block andend_fill()after it:>>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(80) >>> turtle.end_fill()
在 3.14 版本加入.
- turtle.begin_fill()¶
Call just before drawing a shape to be filled. The shape is filled by the next call to
end_fill().
- turtle.end_fill()¶
填充上次调用
begin_fill()之后绘制的形状。If the shape crosses itself or several shapes overlap, whether the overlapping parts are filled depends on the operating system, the type of overlap and how many there are. For example, the turtle star above may be either all yellow or have some white regions.
>>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(80) >>> turtle.end_fill()
更多绘图控制¶
- turtle.reset()¶
删除海龟的绘图,并将海龟重新居中。海龟的设置将恢复为默认值。
>>> turtle.goto(0,-22) >>> turtle.left(100) >>> turtle.position() (0.00,-22.00) >>> turtle.heading() 100.0 >>> turtle.reset() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.0
- turtle.clear()¶
从屏幕上删除海龟的绘图。海龟的状态和位置以及其他海龟的绘图将不受影响。
- turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal'))¶
- 参数:
arg -- an object
move -- 布尔
align -- 字符串
font -- a tuple of a string, an integer and a string
Write text at the current turtle position. The text is the string representation of arg. align is one of the strings "left", "center" or "right" and says how the text is placed relative to the turtle position. font is a triple of font name, font size and font type. If move is
True, the pen is moved to the bottom-right corner of the text.>>> turtle.write("Home = ", True, align="center") >>> turtle.write((0,0), True)
海龟状态¶
可见性¶
- turtle.isvisible()¶
如果海龟可见,则返回
True;如果海龟被隐藏,则返回False。>>> turtle.hideturtle() >>> turtle.isvisible() False >>> turtle.showturtle() >>> turtle.isvisible() True
外观¶
- turtle.shape(name=None)¶
- 参数:
name -- 一个字符串或
None
将龟形设置为指定名称的形状。如果未提供 name,则返回当前形状的名称。该形状必须存在于
TurtleScreen的形状字典中。初始时包含以下形状:“arrow”、“turtle”、“circle”、“square”、“triangle”和“classic”。如需添加形状,请参阅Screen方法register_shape()。>>> turtle.shape() 'classic' >>> turtle.shape("turtle") >>> turtle.shape() 'turtle'
- turtle.resizemode(rmode=None)¶
- 参数:
rmode -- 一个字符串或
None
将 resizemode 设置为“auto”、“user”或“noresize”。如果未指定 rmode,则返回当前的 resizemode。不同的 resizemode 具有以下效果:
“auto”:海龟的大小将根据
pensize()的值进行调整。“user”:海龟会根据由
shapesize()设置的拉伸因子和轮廓宽度进行尺寸调整。“noresize”:海龟不会调整大小。
resizemode("user")会由shapesize()带参数使用时被调用。>>> turtle.resizemode() 'noresize' >>> turtle.resizemode("auto") >>> turtle.resizemode() 'auto'
- turtle.shapesize(stretch_wid=None, stretch_len=None, outline=None)¶
- turtle.turtlesize(stretch_wid=None, stretch_len=None, outline=None)¶
- 参数:
stretch_wid -- 一个正数或
Nonestretch_len -- 一个正数或
Noneoutline -- 一个正数或
None
返回或设置 turtle 的拉伸因子和轮廓宽度。若未提供任何参数,则返回当前值;否则将 resizemode 设置为“user”,使 turtle 根据其拉伸因子以拉伸后的形式显示:
stretch_wid:垂直于海龟朝向的拉伸因子
stretch_len:沿海龟朝向方向的拉伸因子
outline:形状轮廓的宽度
例如,
shapesize(2, 1)会使龟形图宽度增加一倍,而不会改变其长度。如果仅指定 stretch_wid,则 stretch_len 将被设置为相同值。>>> turtle.shapesize() (1.0, 1.0, 1) >>> turtle.resizemode("user") >>> turtle.shapesize(5, 5, 12) >>> turtle.shapesize() (5, 5, 12) >>> turtle.shapesize(outline=8) >>> turtle.shapesize() (5, 5, 8)
- turtle.shearfactor(shear=None)¶
- 参数:
shear -- 一个数值或
None
Return or set the current shear factor. Shearing slants the turtle shape, like the slant of italic letters. The shear factor says how much it is slanted: 0 is not slanted at all, and the larger the number, the stronger the slant. Negative numbers slant the other way. If shear is not given, return the current shear factor. Otherwise slant the turtle shape accordingly and set resizemode to "user". The turtle's heading does not change. Precisely, the shear factor is the tangent of the shear angle.
>>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.shearfactor(0.5) >>> turtle.shearfactor() 0.5
- turtle.tilt(angle)¶
- 参数:
angle -- 一个数值
Turn the turtle shape by angle from its current tilt angle. The turtle's heading does not change, so the turtle keeps moving in the same direction. See
tiltangle().>>> turtle.reset() >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.tilt(30) >>> turtle.fd(50) >>> turtle.tilt(30) >>> turtle.fd(50)
- turtle.tiltangle(angle=None)¶
- 参数:
angle -- 一个数值或
None
Return or set the current tilt angle. The tilt angle is the angle between the direction the turtle shape points in and the direction the turtle moves in. Normally the shape points in the direction of movement, so the tilt angle is 0. If angle is given, turn the turtle shape to that tilt angle, no matter what it was before, and set resizemode to "user". The turtle's heading does not change. If angle is not given, return the current tilt angle.
>>> turtle.reset() >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.tilt(45) >>> turtle.tiltangle() 45.0
- turtle.shapetransform(t11=None, t12=None, t21=None, t22=None)¶
- 参数:
t11 -- 一个数值或
Nonet12 -- 一个数值或
Nonet21 -- 一个数值或
Nonet22 -- 一个数值或
None
Return or set the transformation matrix of the turtle shape. The matrix combines the stretch factors, the shear factor and the tilt angle of the turtle shape into four numbers: t11 and t12 form its first row, t21 and t22 its second. If none of them are given, return the current matrix as a tuple of four numbers. Otherwise set the given elements and update the stretch factors, shear factor and tilt angle accordingly.
t11 * t22 - t12 * t21must not be zero, otherwise an error is raised.>>> turtle = Turtle() >>> turtle.shape("square") >>> turtle.shapesize(4,2) >>> turtle.shearfactor(-0.5) >>> turtle.shapetransform() (4.0, -1.0, -0.0, 2.0)
- turtle.get_shapepoly()¶
Return the points that form the outline of the current turtle shape as a tuple of
(x, y)coordinate pairs. These points can be used to define a new shape or parts of a compound shape>>> turtle.shape("square") >>> turtle.shapetransform(4, -1, 0, 2) >>> turtle.get_shapepoly() ((50, -20), (30, 20), (-50, 20), (-30, -20))
使用事件¶
- turtle.onclick(fun, btn=1, add=None)
- 参数:
fun -- 一个具有两个参数的函数或
Nonebtn -- 一个整数
add -- 布尔值或
None
将 fun 绑定到该 turtle 的鼠标点击事件上。fun 会在调用时接收画布上点击点的坐标。如果 fun 为
None,则会移除现有的绑定;btn 表示鼠标按钮的编号,默认为 1,即左键。如果 add 为True,则会添加新的绑定;否则,则会替换原有的绑定。以下以匿名 turtle(即过程式方式)为例说明:>>> def turn(x, y): ... left(180) ... >>> onclick(turn) # 现在点击海龟将使其转向。 >>> onclick(None) # 事件绑定将被移除
- turtle.onrelease(fun, btn=1, add=None)¶
- 参数:
fun -- 一个函数,调用时将传入两个参数表示在画布上点击的坐标。
btn -- 鼠标按钮编号,默认值为 1 (鼠标左键)
add --
True或False-- 如为True则将添加一个新绑定,否则将取代先前的绑定
将 fun 指定的函数绑定到在此海龟上释放鼠标按键事件。如果 fun 值为
None,则移除现有的绑定。>>> class MyTurtle(Turtle): ... def glow(self,x,y): ... self.fillcolor("red") ... def unglow(self,x,y): ... self.fillcolor("") ... >>> turtle = MyTurtle() >>> turtle.onclick(turtle.glow) # 点击turtle会将填充颜色设置为红色。 >>> turtle.onrelease(turtle.unglow) # 释放会使它变得透明
- turtle.ondrag(fun, btn=1, add=None)¶
- 参数:
fun -- 一个函数,调用时将传入两个参数表示在画布上点击的坐标。
btn -- 鼠标按钮编号,默认值为 1 (鼠标左键)
add --
True或False-- 如为True则将添加一个新绑定,否则将取代先前的绑定
将 fun 指定的函数绑定到在此海龟上移动鼠标事件。如果 fun 值为
None,则移除现有的绑定。注: 在海龟上移动鼠标事件之前应先发生在此海龟上点击鼠标事件。
>>> turtle.ondrag(turtle.goto)
在此之后点击并拖动海龟可在屏幕上手绘线条 (如果画笔为落下)。
特殊海龟方法¶
- turtle.poly()¶
Record the vertices of a polygon drawn in the
withblock. The first and last vertices will be connected.>>> with turtle.poly(): ... turtle.forward(100) ... turtle.right(60) ... turtle.forward(100)
poly()is a context manager, so using it is the same as callingbegin_poly()before the block andend_poly()after it:>>> turtle.begin_poly() >>> turtle.forward(100) >>> turtle.right(60) >>> turtle.forward(100) >>> turtle.end_poly()
在 3.14 版本加入.
- turtle.begin_poly()¶
开始记录多边形的顶点。当前 turtle 的位置即为多边形的第一个顶点。
- turtle.end_poly()¶
停止记录多边形的顶点。当前 turtle 的位置即为多边形的最后一个顶点;该顶点将与第一个顶点相连。
- turtle.get_poly()¶
返回最新记录的多边形。
>>> turtle.home() >>> turtle.begin_poly() >>> turtle.fd(100) >>> turtle.left(20) >>> turtle.fd(30) >>> turtle.left(60) >>> turtle.fd(50) >>> turtle.end_poly() >>> p = turtle.get_poly() >>> register_shape("myFavouriteShape", p)
- turtle.clone()¶
创建并返回一个海龟的克隆体。该克隆体具有与原始海龟相同的位置、朝向和海龟属性。
>>> leonel = Turtle() >>> marco = leonel.clone()
- turtle.getturtle()¶
- turtle.getpen()¶
返回 Turtle 对象本身。
调用
getturtle(),以获取由forward()和left()等函数使用的海龟:>>> pet = getturtle() >>> pet.fd(50) >>> pet <turtle.Turtle object at 0x...>
- turtle.getscreen()¶
返回作为海龟绘图场所的
TurtleScreen类对象。该对象将可调用 TurtleScreen 方法。>>> ts = turtle.getscreen() >>> ts <turtle._Screen object at 0x...> >>> ts.bgcolor("pink")
- turtle.setundobuffer(size)¶
- 参数:
size -- 一个整型数值或
None
设置或禁用撤销缓冲区。如果 size 为整数,则会创建一个大小为 size 的空撤销缓冲区。size 表示
undo()可撤销的 turtle 操作最大数量。如果 size 为None,则禁用撤销缓冲区。>>> turtle.setundobuffer(42)
- turtle.undobufferentries()¶
返回撤销缓冲区的条目数量。
>>> while undobufferentries(): ... undo()
Screen 方法和函数¶
本节中的大部分示例都使用 TurtleScreen 类的一个实例,命名为 screen。
窗口控制¶
- turtle.bgcolor()¶
- turtle.bgcolor(color, /)
- turtle.bgcolor(r, g, b, /)
返回或设置 TurtleScreen 的背景颜色。
允许以下四种输入格式:
bgcolor()将当前背景颜色以颜色规范字符串或元组的形式返回(参见示例)。该值可用作另一个
color()、pencolor()、fillcolor()或bgcolor()调用的输入。bgcolor(colorstring)设置背景颜色为 colorstring,使用 Tk 颜色描述字符串形式,如
"red","yellow"或"#33cc8c"。bgcolor((r, g, b))将背景颜色设置为由 r、g 和 b 组成的元组所表示的 RGB 颜色。r、g 和 b 中的每个值必须介于 0 和 colormode 之间,其中 colormode 的取值为 1.0 或 255(参见
colormode())。bgcolor(r, g, b)将背景颜色设置为由 r、g 和 b 表示的 RGB 颜色。r、g 和 b 中的每一个值必须介于 0 和 colormode 之间。
>>> screen.bgcolor("orange") >>> screen.bgcolor() 'orange' >>> screen.bgcolor("#800080") >>> screen.bgcolor() (128.0, 0.0, 128.0)
- turtle.bgpic(picname=None)¶
- 参数:
picname -- 一个字符串或
None
Set the background image or return the name of the current one. If picname is the name of an image file (PNG, GIF, PGM, and PPM), set that image as the background. If picname is
"nopic", delete the background image, if present. If picname isNone, return the filename of the current background image.>>> screen.bgpic() 'nopic' >>> screen.bgpic("landscape.gif") >>> screen.bgpic() 'landscape.gif'
- turtle.clear()
备注
此 TurtleScreen 方法作为全局函数时只有一个名字
clearscreen。全局函数clear所对应的是 Turtle 方法clear。
- turtle.clearscreen()¶
从中删除所有海龟的全部绘图。将已清空的 TurtleScreen 重置为初始状态: 白色背景,无背景图片,无事件绑定并启用追踪。
- turtle.reset()
备注
此 TurtleScreen 方法作为全局函数时只有一个名字
resetscreen。全局函数reset所对应的是 Turtle 方法reset。
- turtle.resetscreen()¶
重置屏幕上的所有海龟为其初始状态。
- turtle.screensize(canvwidth=None, canvheight=None, bg=None)¶
- 参数:
canvwidth -- 一个正整数或
Nonecanvheight -- 一个正整数或
Nonebg -- a colorstring or a color tuple or
None
Resize the canvas the turtles are drawing on. canvwidth and canvheight are the new width and height of the canvas in pixels, and bg is the new background color. If no arguments are given, return the current canvas width and height.
The drawing window is not altered. To see hidden parts of the canvas, use the scrollbars. This can make visible those parts of a drawing which were outside the canvas before, for example to find a turtle that has wandered off the canvas.
>>> screen.screensize() (400, 300) >>> screen.screensize(2000,1500) >>> screen.screensize() (2000, 1500)
- turtle.setworldcoordinates(llx, lly, urx, ury)¶
- 参数:
llx -- 一个数值
lly -- 一个数值
urx -- 一个数值
ury -- 一个数值
设置用户自定义坐标系。llx 和 lly 分别是画布左下角的 x 坐标和 y 坐标;urx 和 ury 则是右上角的 x 坐标和 y 坐标。如有需要,请切换至“world”模式,该模式会执行重置操作。若“world”模式已启用,所有绘图将根据新坐标重新绘制。在用户自定义坐标系中,角度可能会呈现扭曲效果,详见
mode()。>>> screen.reset() >>> screen.setworldcoordinates(-50,-7.5,50,7.5) >>> for _ in range(72): ... left(10) ... >>> for _ in range(8): ... left(45); fd(2) # 一个正八边形
动画控制¶
- turtle.no_animation()¶
暂时关闭海龟动画。
with块内的代码不会执行动画效果;一旦退出该块,绘图便会显示。这对于绘制复杂形状非常有用,因为即使采用最快的速度设置,效果仍然会显得过于缓慢。>>> with screen.no_animation(): ... for dist in range(2, 400, 2): ... fd(dist) ... rt(90)
在 3.14 版本加入.
- turtle.delay(delay=None)¶
- 参数:
delay -- 一个非负整数或
None
以毫秒为单位返回或设置绘图延迟。这大致相当于两次连续画布更新之间的时间间隔。绘图延迟时间越长,动画运行速度就越慢。
>>> screen.delay() 10 >>> screen.delay(5) >>> screen.delay() 5
- turtle.tracer(n=None, delay=None)¶
- 参数:
n -- 一个非负整数或
Nonedelay -- 一个非负整数或
None
开启或关闭龟形动画,并设置绘图延迟。如果指定了 n,则仅每 n 次常规屏幕更新执行一次更新,这可用于加快复杂图形的绘制速度。如果 n 为 0,则关闭动画,仅通过调用
update()来更新屏幕。如果指定了 delay,则设置绘图延迟,详见delay()。若不带参数调用,则返回 n 的当前值。>>> screen.tracer(8, 25) >>> dist = 2 >>> for i in range(200): ... fd(dist) ... rt(90) ... dist += 2
- turtle.update()¶
执行一次 TurtleScreen 刷新。在禁用追踪时使用。
另参见 RawTurtle/Turtle 方法 speed()。
使用屏幕事件¶
- turtle.listen(xdummy=None, ydummy=None)¶
- 参数:
xdummy -- ignored
ydummy -- ignored
Set focus on the
TurtleScreenso that it receives key events. The two dummy arguments are only there so thatlisten()can be passed toonclick().
- turtle.onkey(fun, key)¶
- turtle.onkeyrelease(fun, key)¶
- 参数:
fun -- 一个无参数的函数或
Nonekey -- 字符串
Bind fun to the key-release event of key. key is a key, such as "a", or a key symbol, such as "space". If fun is
None, the event binding is removed. To be able to receive key events, theTurtleScreenmust have focus, seelisten().>>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkey(f, "Up") >>> screen.listen()
The turtle can then be moved by repeatedly pressing the up-arrow key, drawing a hexagon.
- turtle.onkeypress(fun, key=None)¶
- 参数:
fun -- 一个无参数的函数或
Nonekey -- 一个字符串或
None
Bind fun to the key-press event of key. key is a key, such as "a", or a key symbol, such as "space". If key is not given, fun is bound to the key-press event of any key. If fun is
None, the event binding is removed. To be able to receive key events, theTurtleScreenmust have focus, seelisten().>>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkeypress(f, "Up") >>> screen.listen()
The turtle can then be moved by pressing or holding down the up-arrow key, drawing a hexagon.
- turtle.onclick(fun, btn=1, add=None)¶
- turtle.onscreenclick(fun, btn=1, add=None)¶
- 参数:
fun -- 一个具有两个参数的函数或
Nonebtn -- 一个整数
add -- 布尔值或
None
将 fun 绑定到本屏幕上的鼠标点击事件。fun 会在调用时接收画布上点击点的坐标。如果 fun 为
None,则移除现有绑定;btn 表示鼠标按钮编号,默认为 1,即鼠标左键;如果 add 为True,则添加新的绑定;否则则替换原有的绑定。以下示例使用一个 TurtleScreen 实例
screen和一个 Turtle 实例turtle:>>> screen.onclick(turtle.goto) # 后续对 TurtleScreen 的点击 >>> # 将使海龟移至被点击的位置。 >>> screen.onclick(None) # 再次移除事件绑定
备注
此 TurtleScreen 方法作为全局函数时只有一个名字
onscreenclick。全局函数onclick所对应的是 Turtle 方法onclick。
- turtle.ontimer(fun, t=0)¶
- 参数:
fun -- 一个无参数的函数
t -- a nonnegative number
安装一个计时器,在 t 毫秒后调用 fun 函数。
>>> running = True >>> def f(): ... if running: ... fd(50) ... lt(60) ... screen.ontimer(f, 250) >>> f() # makes the turtle march around >>> running = False
- turtle.mainloop()¶
- turtle.done()¶
通过调用 Tkinter 的
mainloop()方法启动事件循环。这必须是 turtle graphics 程序中的最后一个语句。如果脚本是在 IDLE 的 -n 模式下从内部运行的,则*不得*使用此方法(参见 在没有子进程的情况下运行)。
输入方法¶
- turtle.textinput(title, prompt)¶
- 参数:
title -- 字符串
prompt -- 字符串
弹出一个用于输入字符串的对话框。title 是对话框的标题,prompt 是描述应输入何种信息的文本。返回所输入的字符串。如果取消对话框,则返回
None。:>>> screen.textinput("NIM", "Name of first player:")
- turtle.numinput(title, prompt, default=None, minval=None, maxval=None)¶
- 参数:
title -- 字符串
prompt -- 字符串
default -- 一个数值或
Noneminval -- 一个数值或
Nonemaxval -- 一个数值或
None
弹出一个用于输入数字的对话框。title 是对话框的标题,prompt 是描述应输入何种数值信息的文本;default 是默认值,minval 和 maxval 分别是输入值的最小值和最大值。如果提供了这些参数,则输入的数字必须介于 minval 和 maxval 之间;否则,系统会提示建议,且对话框将保持打开状态,供用户进行修正。返回所输入的数字;若取消对话框,则返回
None。:>>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
设置与特殊方法¶
- turtle.mode(mode=None)¶
- 参数:
mode -- 一个字符串或
None
设置海龟模式并执行重置。mode 是字符串 “standard”、“logo” 或 “world” 之一。如果未指定 mode,则返回当前模式。
“standard”模式与旧版
turtle模块兼容。“logo”模式与大多数 Logo 海龟绘图兼容。“world”模式使用用户自定义的世界坐标系,详见setworldcoordinates()。在此模式下,若 x 和 y 的单位长度不相等,角度会呈现畸变。模式
初始海龟朝向
正数角度
"standard"
朝右 (东)
逆时针
"logo"
朝上 (北)
顺时针
>>> mode("logo") # resets turtle heading to north >>> mode() 'logo'
- turtle.colormode(cmode=None)¶
- 参数:
cmode -- 一个数值或
None
返回 colormode,或将其设置为 1.0 或 255。设置完成后,颜色三元组中的 r、g 和 b 值必须介于 0 与 cmode 之间。
>>> screen.colormode(1) >>> turtle.pencolor(240, 160, 80) Traceback (most recent call last): ... TurtleGraphicsError: bad color sequence: (240, 160, 80) >>> screen.colormode() 1.0 >>> screen.colormode(255) >>> screen.colormode() 255 >>> turtle.pencolor(240,160,80)
- turtle.getcanvas()¶
返回此 TurtleScreen 的 Canvas 对象。供了解 Tkinter 的 Canvas 对象内部机理的人士使用。
>>> cv = screen.getcanvas() >>> cv <turtle.ScrolledCanvas object ...>
- turtle.getshapes()¶
返回所有当前可用海龟形状的列表。
>>> screen.getshapes() ['arrow', 'blank', 'circle', ..., 'turtle']
- turtle.register_shape(name, shape=None)¶
- turtle.addshape(name, shape=None)¶
- 参数:
name -- 字符串
shape -- 一个字符串、一个由数字对组成的元组、一个
Shape对象或None
将龟形添加到 TurtleScreen 的形状列表中。该形状可以通过四种不同方式调用:
name 为一个图像文件(PNG、 GIF、 PGM和PPM)的文件名, shape 为
None: 安装相应的图像形状。:>>> screen.register_shape("turtle.gif")
name 为任意字符串, shape 为图像文件(PNG、 GIF、 PGM和PPM)的名称:安装相应的图像形状。:
>>> screen.register_shape("turtle", "turtle.gif")
name 为指定的字符串,shape 为由坐标值对构成的元组: 安装相应的多边形形状。
>>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
name 为任意字符串而 shape 为 (复合)
Shape对象:安装相应的复合形状。
图像形状在旋转海龟时不会随之旋转,因此不会显示海龟的朝向。若要使用已注册的形状,请使用其名称调用
shape()。在 3.14 版本发生变更: 增加了对PNG、PGM和PPM图像格式的支持。可以指定形状名称和图像文件名。
- turtle.turtles()¶
返回屏幕上的海龟列表。
>>> for turtle in screen.turtles(): ... turtle.color("red")
- turtle.window_height()¶
返回海龟窗口的高度。:
>>> screen.window_height() 480
- turtle.window_width()¶
返回海龟窗口的宽度。:
>>> screen.window_width() 640
仅限 Screen 的方法¶
- turtle.bye()¶
关闭 Turtle Graphics 窗口。
- turtle.exitonclick()¶
将
bye()方法绑定到 Screen 上的鼠标点击事件。如果配置字典中 "using_IDLE" 的值为
False(默认值) 则同时进入主事件循环。注: 如果启动 IDLE 时使用了-n开关 (无子进程),turtle.cfg中此数值应设为True。在此情况下 IDLE 本身的主事件循环同样会作用于客户脚本。
- turtle.save(filename, *, overwrite=False)¶
- 参数:
filename -- 字符串
overwrite -- 布尔
Save the current drawing and the turtles as a PostScript file. filename is the path of the file to create. It must end with
".ps"or".eps". If a file with that name already exists, aFileExistsErroris raised, unless overwrite isTrue. overwrite must be given by name, as inoverwrite=True.>>> screen.save("my_drawing.ps") >>> screen.save("my_drawing.ps", overwrite=True)
在 3.14 版本加入.
- turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom'])¶
设置主窗口的大小和位置。默认参数值保存在配置字典中,可通过
turtle.cfg文件进行修改。- 参数:
width -- 如为一个整型数值,表示大小为多少像素,如为一个浮点数值,则表示屏幕的占比;默认为屏幕的 50%
height -- 如为一个整型数值,表示高度为多少像素,如为一个浮点数值,则表示屏幕的占比;默认为屏幕的 75%
startx -- 如为正值,表示初始位置距离屏幕左边缘多少像素,负值表示距离右边缘,
None表示窗口水平居中starty -- 如为正值,表示初始位置距离屏幕上边缘多少像素,负值表示距离下边缘,
None表示窗口垂直居中
>>> screen.setup (width=200, height=200, startx=0, starty=0) >>> # 设置窗口为 200x200 像素,位于屏幕左上角 >>> screen.setup(width=.75, height=0.5, startx=None, starty=None) >>> # 设置窗口宽度为屏幕的 75% 高度为屏幕的 50% 并居中
- turtle.title(titlestring)¶
- 参数:
titlestring -- 字符串
将 turtle 窗口的标题设置为 titlestring。标题会显示在 turtle 图形窗口的标题栏中。
>>> screen.title("Welcome to the turtle zoo!")
公共类¶
- class turtle.RawTurtle(canvas)¶
- class turtle.RawPen(canvas)¶
- 参数:
canvas -- 一个
tkinter.Canvas,ScrolledCanvas或TurtleScreen
创建一个海龟。海龟对象具有 "Turtle/RawTurtle 方法" 一节所述的全部方法。
- class turtle.Screen¶
TurtleScreen的子类,其中包含 four methods added。调用Screen()将返回单个屏幕对象;如果该对象尚未存在,则将其创建;否则则返回现有对象。
- class turtle.ScrolledCanvas(master)¶
- 参数:
master -- 可容纳 ScrolledCanvas 的 Tkinter 部件,即添加了滚动条的 Tkinter-canvas
由 Screen 类使用,使其能够自动提供一个 ScrolledCanvas 作为海龟的绘图场所。
- class turtle.Shape(type_, data)¶
- 参数:
type_ -- 字符串
data -- 取决于 type_
数据结构建模形态。type_ 是字符串 “polygon”、“image” 或 “compound” 之一。data 的具体形式取决于 type_*:对于 “polygon”,是一个坐标点对的元组;对于 “image”,是一个图像(仅用于内部处理);对于 “compound”,则是
None,因为复合形状是通过addcomponent()方法构建而成的。- addcomponent(poly, fill, outline=None)¶
- 参数:
poly -- 一个由数字对组成的元组
fill -- 一种颜色
outline -- 一种颜色或
None
向类型为“compound”的形状添加一个组件。poly 表示多边形,即一组数字对组成的元组;fill 表示多边形填充的颜色,而 outline 表示其轮廓的颜色。如果未指定 outline,则默认使用 fill 的颜色作为轮廓颜色。
示例:
>>> poly = ((0,0), (10,-5), (0,10), (-10,-5)) >>> s = Shape("compound") >>> s.addcomponent(poly, "red", "blue") >>> # ... add more components and then use register_shape()
参见 如何使用复合形状。
- class turtle.Vec2D(x, y)¶
一个二维矢量类,用来作为实现海龟绘图的辅助类。也可能在海龟绘图程序中使用。派生自元组,因此矢量也属于元组!
提供的运算 (a, b 为矢量, k 为数值):
a + b矢量加法a - b矢量减法a * b内积k * a和a * k与标量相乘abs(a)a 的绝对值a.rotate(angle)旋转
异常¶
turtle 模块定义了以下异常:
- exception turtle.TurtleGraphicsError¶
当参数或操作无效时引发。例如,格式错误的颜色字符串:
>>> turtle.color("blau") Traceback (most recent call last): ... turtle.TurtleGraphicsError: bad color string: blau
常用方案指引¶
本节介绍一些典型的海龟使用案例和操作方式。
如何自动开始和结束填充¶
从 Python 3.14 开始,你可以使用 fill() context manager 来代替 begin_fill() 和 end_fill() 以自动开始和结束填充。 下面是一个示例:
with fill():
for i in range(4):
forward(100)
right(90)
forward(200)
上面的代码等价于:
begin_fill()
for i in range(4):
forward(100)
right(90)
end_fill()
forward(200)
如何使用复合形状¶
要使用由多个不同颜色多边形构成的复合海龟形状,你必须明确地使用辅助类 Shape,具体步骤如下:
创建一个类型为“compound”的空
Shape对象。可根据需要使用
addcomponent()方法向此对象添加多个组件。例如:
>>> s = Shape("compound") >>> poly1 = ((0,0), (10,-5), (0,10), (-10,-5)) >>> s.addcomponent(poly1, "red", "blue") >>> poly2 = ((0,0), (10,-5), (-10,-5)) >>> s.addcomponent(poly2, "blue", "red")
接下来将 Shape 对象添加到 Screen 对象的形状列表并使用它:
>>> register_shape("myshape", s) >>> shape("myshape")
如何使用 turtle 模块命名空间¶
使用 from turtle import * 是很方便 —— 但要注意它导入的对象集相当大,如果你还在做海龟绘图以外的事情就有发生名称冲突的风险(如果你在可能导入了其他模块的脚本中使用海龟绘图则可能会遇到更大的问题)。
解决办法是使用 import turtle —— fd() 将变成 turtle.fd(),width() 将变成 turtle.width() 等等。 (如果反复输入“turtle”太过烦琐,还可改成 import turtle as t 等。)
如何在脚本中使用 turtle graphics¶
建议使用上文所述的 turtle 模块命名空间,例如:
import turtle as t
from random import random
for i in range(100):
steps = int(random() * 100)
angle = int(random() * 360)
t.right(angle)
t.fd(steps)
但还需要另一个步骤 —— 因为一旦脚本结束,Python 将会同时关闭海龟的窗口。 请添加:
t.mainloop()
到脚本的末尾。 现在脚本将等待被关闭而不会自动退出直到被主动终止,例如海龟绘图窗口被关闭。
如何使用面向对象式 turtle 图形¶
参见
除了非常基本的入门目的,或是尽快尝试操作之外,使用面向对象的方式进行海龟绘图更为常见也更为强大。 例如,这将允许屏幕上同时存在多只海龟。
在这种方式下,各种海龟命令都是对象(主要是 Turtle 对象)的方法。 你 可以 在 shell 中使用面向对象的方法,但在 Python 脚本中使用是更为典型的做法。
这样上面的例子就将变成:
from turtle import Turtle
from random import random
t = Turtle()
for i in range(100):
steps = int(random() * 100)
angle = int(random() * 360)
t.right(angle)
t.fd(steps)
t.screen.mainloop()
请注意最后一行。 t.screen 是 Turtle 实例所在的 Screen 的实例;它是与海龟一起自动创建的。
海龟的屏幕可以被自定义,例如:
t.screen.title('Object-oriented turtle demo')
t.screen.bgcolor("orange")
如何使用 help()¶
Screen 和 Turtle 类的公用方法以文档字符串提供了详细的文档。因此可以利用 Python 帮助工具获取这些在线帮助信息:
当使用 IDLE 时,输入函数/方法调用将弹出工具提示显示其签名和文档字符串的头几行。
对方法或函数调用
help()将显示其文档字符串:>>> help(Screen.bgcolor) Help on method bgcolor in module turtle: bgcolor(self, *args) unbound turtle.Screen method Set or return backgroundcolor of the TurtleScreen. Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. >>> screen.bgcolor("orange") >>> screen.bgcolor() "orange" >>> screen.bgcolor(0.5,0,0.5) >>> screen.bgcolor() "#800080" >>> help(Turtle.penup) Help on method penup in module turtle: penup(self) unbound turtle.Turtle method Pull the pen up -- no drawing when moving. Aliases: penup | pu | up No argument >>> turtle.penup()
方法对应函数的文档字符串的形式会有一些修改:
>>> help(bgcolor) Help on function bgcolor in module turtle: bgcolor(*args) Set or return backgroundcolor of the TurtleScreen. Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. Example:: >>> bgcolor("orange") >>> bgcolor() "orange" >>> bgcolor(0.5,0,0.5) >>> bgcolor() "#800080" >>> help(penup) Help on function penup in module turtle: penup() Pull the pen up -- no drawing when moving. Aliases: penup | pu | up No argument Example: >>> penup()
这些修改版文档字符串是在导入时与方法对应函数的定义一起自动生成的。
文档字符串翻译为不同的语言¶
可使用工具创建一个字典,键为方法名,值为 Screen 和 Turtle 类公共方法的文档字符串。
- turtle.write_docstringdict(filename='turtle_docstringdict')¶
- 参数:
filename -- 一个字符串,表示文件名
创建文档字符串字典并将其写入 filename 指定的 Python 脚本文件。此函数必须显式地调用 (海龟绘图类并不使用此函数)。文档字符串字典将被写入到 Python 脚本文件
filename.py。该文件可作为模板用来将文档字符串翻译为不同语言。
如果您(或您的学生)希望使用 turtle 并获取母语版本的在线帮助,则必须将 docstrings 进行翻译,并将生成的文件保存为例如 turtle_docstringdict_german.py.
如果你在 turtle.cfg 文件中加入了相应的条目,此字典将在导入模块时被读取并替代原有的英文版文档字符串。
在撰写本文档时已经有了德语和意大利语版的文档字符串字典。(更多需求请联系 glingl@aon.at)
如何配置 Screen 和 Turtle¶
内置的默认配置是模仿旧 turtle 模块的外观和行为,以便尽可能地与其保持兼容。
如果你想使用不同的配置,以便更好地反映此模块的特性或是更适合你的需求,例如在课堂中使用,你可以准备一个配置文件 turtle.cfg,该文件将在导入模块时被读取并根据其中的设定修改模块配置。
内置的配置对应了下面的 turtle.cfg:
width = 0.5
height = 0.75
leftright = None
topbottom = None
canvwidth = 400
canvheight = 300
mode = standard
colormode = 1.0
delay = 10
undobuffersize = 1000
shape = classic
pencolor = black
fillcolor = black
resizemode = noresize
visible = True
language = english
exampleturtle = turtle
examplescreen = screen
title = Python Turtle Graphics
using_IDLE = False
选定条目的简短说明:
开头的四行对应了
Screen.setup方法的参数。第 5 和第 6 行对应于
Screen.screensize方法的参数。shape 可以是任何内置形状,即: arrow, turtle 等。更多信息可用
help(shape)查看。如果你想使用无填充色(即让海龟变透明),则你必须写
fillcolor = ""(但在 cfg 文件中所有非空字符串都不可加引号)。如果你想令海龟反映其状态,你必须使用
resizemode = auto。如果您设置例如
language = italian,那么 docstringdictturtle_docstringdict_italian.py将在导入时加载(如果该文件存在于导入路径中,例如与turtle处于同一目录)。exampleturtle 和 examplescreen 条目定义了相应对象在文档字符串中显示的名称。方法文档字符串转换为函数文档字符串时将从文档字符串中删去这些名称。
using_IDLE: 如果你经常使用 IDLE 及其
-n开关选项("无子进程")则将此项设为True。 这将阻止exitonclick()进入主事件循环。
在存储 turtle 的目录中可以存在一个 turtle.cfg 文件,在当前工作目录中还可以存在另一个文件;后者将覆盖第一个文件的设置。
Lib/turtledemo 目录中也有一个 turtle.cfg 文件。你可以将其作为示例进行研究,并在运行演示时查看其作用效果 (但最好不要在演示查看器中运行)。
说明¶
海龟对象在屏幕对象上绘图,在 turtle 的面向对象接口中有许多关键的类可被用于创建它们并将它们相互关联。
Turtle 实例将自动创建一个 Screen 实例,如果它还未创建的话。
Turtle 是 RawTurtle 的子类,它 不会 自动创建绘图区域 —— 需要为其提供或创建一个 canvas。 canvas 可以是一个 tkinter.Canvas, ScrolledCanvas 或 TurtleScreen。
TurtleScreen 是基本的海龟绘图区域。 Screen 是 TurtleScreen 的子类,并包括 一些额外方法 用来管理其外观(包括大小和标题)及行为。 TurtleScreen 的构造器需要一个 tkinter.Canvas 或 ScrolledCanvas 作为参数。
海龟绘图的函数式接口使用 Turtle 和 TurtleScreen/Screen 的各种方法。 在下层,每当从 Screen 方法派生的函数被调用时就会自动创建一个屏幕对象。 同样地,每当从 Turtle 方法派生的函数被调用时也都会自动创建一个 Turtle 对象。
要在一个屏幕中使用多个海龟,就必须使用面向对象的接口。
turtledemo --- 演示脚本¶
turtledemo 软件包包含一组演示脚本。可通过随附的演示查看器以如下方式运行并查看这些脚本:
python -m turtledemo
此外,你也可以单独运行其中的演示脚本。例如,:
python -m turtledemo.bytedesign
turtledemo 包目录中包含:
一个演示查看器
__main__.py,可用来查看脚本的源码并即时运行。演示
turtle模块的不同特性的多个脚本。 所有示例可通过 Examples 菜单打开。 它们也可以独立运行。一个
turtle.cfg文件,作为说明如何编写并使用模块配置文件的示例模板。
演示脚本清单如下:
名称 |
描述 |
相关特性 |
|---|---|---|
|
复杂的传统海龟绘图模式 |
|
|
绘制 Verhulst 动态模型,演示通过计算机的运算可能会生成令人惊叹的结果 |
世界坐标系 |
|
绘制模拟时钟显示本机的当前时间 |
海龟作为表针, |
|
试验 r, g, b 颜色模式 |
|
|
绘制 3 棵广度优先树 |
随机化 |
|
绘制 Hilbert & Koch 曲线 |
递归 |
|
文化数学 (印度装饰艺术) |
L-系统 |
|
汉诺塔 |
矩形海龟作为汉诺盘 ( |
|
玩经典的“尼姆”游戏,开始时有三堆小棒,与电脑对战。 |
海龟作为小棒,事件驱动 (鼠标, 键盘) |
|
超极简主义绘画程序 |
|
|
初级技巧 |
海龟: 外观与动画 |
|
非周期性地使用风筝和飞镖形状铺满平面 |
|
|
模拟引力系统 |
复合形状, |
|
一个来自介绍海龟绘图的维基百科文章的图案 |
|
|
两两相对并不断旋转舞蹈的海龟 |
复合形状, |
|
动态演示不同的排序方法 |
简单对齐, 随机化 |
|
一棵 (图形化的) 广度优先树 (使用生成器) |
|
|
简单设计 |
两块画布上的海龟 |
|
另一个初级示例 |
|
祝你玩得开心!