海龟 — 海龟图形 — Python 文档

来自菜鸟教程
Python/docs/3.7/library/turtle
跳转至:导航、​搜索

turtle — 海龟图形

源代码: :source:`Lib/turtle.py`



简介

海龟图形是向孩子们介绍编程的流行方式。 它是 1967 年由 Wally Feurzeig、Seymour Papert 和 Cynthia Solomon 开发的原始 Logo 编程语言的一部分。

想象一只机器乌龟从 xy 平面的 (0, 0) 开始。 在 import turtle 之后,给它命令 turtle.forward(15),它会在它面向的方向上移动(在屏幕上!)15 个像素,并在移动时画一条线。 给它命令 turtle.right(25),它会原地顺时针旋转 25 度。

龟星

海龟可以使用重复简单动作的程序绘制复杂的形状。

class=align-center|../_images/turtle-star.png

from turtle import *
color('red', 'yellow')
begin_fill()
while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break
end_fill()
done()

通过将这些和类似的命令组合在一起,可以轻松绘制复杂的形状和图片。

turtle 模块是从 Python 标准发行版到 Python 2.5 版本的同名模块的扩展重新实现。

它试图保持旧乌龟模块的优点,并(几乎)100% c与它兼容。 这首先意味着在使用 -n 开关从 IDLE 运行中使用模块时,让学习程序员能够交互地使用所有命令、类和方法。

海龟模块以面向对象和面向过程的方式提供海龟图形基元。 因为它使用 tkinter 作为底层图形,所以它需要一个安装了 Tk 支持的 Python 版本。

面向对象的接口本质上使用两个+两个类:

  1. TurtleScreen 类将图形窗口定义为绘图海龟的游乐场。 它的构造函数需要一个 tkinter.Canvas 或一个 ScrolledCanvas 作为参数。 当 turtle 用作某些应用程序的一部分时,应该使用它。

    函数 Screen() 返回一个 TurtleScreen 子类的单例对象。 当turtle作为独立的图形工具使用时,应使用此功能。 作为单例对象,从其类继承是不可能的。

    TurtleScreen/Screen 的所有方法也作为函数存在,即 作为面向过程的接口的一部分。

  2. RawTurtle(别名:RawPen)定义了在 TurtleScreen 上绘制的 Turtle 对象。 它的构造函数需要一个 Canvas、ScrolledCanvas 或 TurtleScreen 作为参数,因此 RawTurtle 对象知道在哪里绘制。

    派生自 RawTurtle 的是子类 Turtle(别名:Pen),它利用自动创建的“Screen 实例(如果尚未存在)。

    RawTurtle/Turtle 的所有方法也以函数的形式存在,即 面向过程的接口的一部分。

过程接口提供从类 ScreenTurtle 的方法派生的函数。 它们与相应的方法具有相同的名称。 只要调用从 Screen 方法派生的函数,就会自动创建一个屏幕对象。 每当调用从 Turtle 方法派生的任何函数时,都会自动创建一个(未命名的)海龟对象。

要在屏幕上使用多个海龟,必须使用面向对象的界面。

笔记

在以下文档中,给出了函数的参数列表。 当然,方法有额外的第一个参数 self,这里省略了。


可用的 Turtle 和 Screen 方法概述

RawTurtle/Turtle 的方法和对应的函数

本节中的大多数示例都引用了名为 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

如果 yNone,则 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)
turtle.setx(x)
参数

x – 一个数字(整数或浮点数)

将海龟的第一个坐标设置为 x,第二个坐标保持不变。

>>> turtle.position()
(0.00,240.00)
>>> turtle.setx(10)
>>> turtle.position()
(10.00,240.00)
turtle.sety(y)
参数

y – 一个数字(整数或浮点数)

将海龟的第二个坐标设置为 y,保持第一个坐标不变。

>>> 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。 以下是一些常见的度数方向:

标准模式

标志模式

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 – 一个数字(或 None

  • steps – 一个整数(或 None

用给定的 半径 画一个圆。 中心是乌龟左边的半径个单位; 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)  # draw a semicircle
>>> turtle.position()
(0.00,240.00)
>>> turtle.heading()
180.0
turtle.dot(size=None, *color)
参数
  • size – 一个整数 >= 1(如果给定)

  • color – 颜色字符串或数字颜色元组

使用 color 绘制直径为 size 的圆点。 如果未给出 size,则使用 pensize+4 和 2*pensize 的最大值。

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

在当前海龟位置的画布上标记海龟形状的副本。 返回该图章的stamp_id,可用于通过调用clearstamp(stamp_id) 删除它。

>>> turtle.color("blue")
>>> turtle.stamp()
11
>>> turtle.fd(50)
turtle.clearstamp(stampid)
参数

stampid – 一个整数,必须是前一个 stamp() 调用的返回值

删除给定 stampid 的图章。

>>> 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 的海龟图章。 如果 nNone , 删除所有图章,如果 n > 0 先删除 n 邮票,否则如果 n < 0 最后删除 n 邮票。

>>> for i in range(8):
...     turtle.stamp(); turtle.fd(30)
13
14
15
16
17
18
19
20
>>> 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 – 0..10 范围内的整数或速度字符串(见下文)

将海龟的速度设置为 0..10 范围内的整数值。 如果没有给出参数,则返回当前速度。

如果输入的数字大于 10 或小于 0.5,则速度设置为 0。 Speedstrings 映射到 speedvalues 如下:

  • “最快”:0

  • “快”:10

  • “正常”:6

  • “慢”:3

  • “最慢”:1

从 1 到 10 的速度强制执行越来越快的线条绘制和海龟转动动画。

注意:speed = 0 表示 no 动画发生。 向前/向后使海龟跳跃,同样向左/向右使海龟立即转动。

>>> turtle.speed()
3
>>> turtle.speed('normal')
>>> turtle.speed()
6
>>> turtle.speed(9)
>>> turtle.speed()
9


告诉 Turtle 的状态

turtle.position()
turtle.pos()

返回海龟的当前位置 (x,y)(作为 Vec2D 向量)。

>>> turtle.pos()
(440.00,-0.00)
turtle.towards(x, y=None)
参数
  • x – 一个数字或一对/数字向量或海龟实例

  • y – 如果 x 是数字,则为数字,否则为 None

返回从海龟位置到由 (x,y)、向量或其他海龟指定的位置之间的角度。 这取决于海龟的开始方向,这取决于模式 - “标准”/“世界”或“标志”)。

>>> 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)、给定向量或给定其他海龟的距离。

>>> 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 – 一个数字

设置角度测量单位,即 为一个完整的圆设置“度数”。 默认值为 360 度。

>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0

Change angle measurement unit to grad (also known as gon,
grade, or gradian and equals 1/100-th of the right angle.)
>>> 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.pendown()

turtle.pd()
turtle.down()

拉下笔——移动时画画。
turtle.penup()

turtle.pu()
turtle.up()

将笔拉起 - 移动时不绘图。
turtle.pensize(width=None)
turtle.width(width=None)
参数

width – 一个正数

将线宽设置为 width 或返回。 如果resizemode 设置为“auto”并且turtleshape 是一个多边形,则该多边形以相同的线条粗细绘制。 如果没有给出参数,则返回当前的画笔大小。

>>> turtle.pensize()
1
>>> turtle.pensize(10)   # from here on lines of width 10 are drawn
turtle.pen(pen=None, **pendict)
参数
  • pen – 包含以下列出的部分或全部键的字典

  • pendict – 一个或多个关键字参数,下面列出的键作为关键字

使用以下键/值对在“笔字典”中返回或设置笔的属性:

  • “显示”:真/假

  • “pendown”:真/假

  • “pencolor”:颜色字符串或颜色元组

  • “fillcolor”:颜色字符串或颜色元组

  • “pensize”:正数

  • “速度”:0..10 范围内的数字

  • “resizemode”:“auto”或“user”或“noresize”

  • “stretchfactor”:(正数,正数)

  • “大纲”:正数

  • “倾斜”:数字

此字典可用作后续调用 pen() 以恢复以前的笔状态的参数。 此外,这些属性中的一个或多个可以作为关键字参数提供。 这可用于在一个语句中设置多个笔属性。

>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
>>> sorted(turtle.pen().items())
[('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),
 ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
 ('shearfactor', 0.0), ('shown', True), ('speed', 9),
 ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)]
>>> penstate=turtle.pen()
>>> turtle.color("yellow", "")
>>> turtle.penup()
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow')]
>>> turtle.pen(penstate, fillcolor="green")
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]
turtle.isdown()

如果笔已按下,则返回 True,如果笔已抬起,则返回 False

>>> turtle.penup()
>>> turtle.isdown()
False
>>> turtle.pendown()
>>> turtle.isdown()
True


色彩控制

turtle.pencolor(*args)

返回或设置 pencolor。

允许四种输入格式:

pencolor()

将当前画笔颜色作为颜色规范字符串或元组返回(参见示例)。 可用作另一个 color/pencolor/fillcolor 调用的输入。

pencolor(colorstring)

设置pencolor为colorstring,为Tk颜色规范字符串,如"red""yellow""#33cc8c"

pencolor((r, g, b))

将 pencolor 设置为由 rgb 的元组表示的 RGB 颜色。 rgb 中的每一个都必须在 0..colormode 范围内,其中 colormode 为 1.0 或 255(请参阅 colormode( ))。

pencolor(r, g, b)

将 pencolor 设置为由 rgb 表示的 RGB 颜色。 rgb 中的每一个都必须在 0..colormode 范围内。

如果turtleshape 是多边形,则使用新设置的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(*args)

返回或设置填充颜色。

允许四种输入格式:

fillcolor()

将当前填充颜色作为颜色规范字符串返回,可能采用元组格式(参见示例)。 可用作另一个 color/pencolor/fillcolor 调用的输入。

fillcolor(colorstring)

设置fillcolor为colorstring,为Tk颜色规范字符串,如"red""yellow""#33cc8c"

fillcolor((r, g, b))

将 fillcolor 设置为由 rgb 的元组表示的 RGB 颜色。 rgb 中的每一个都必须在 0..colormode 范围内,其中 colormode 为 1.0 或 255(请参阅 colormode( ))。

fillcolor(r, g, b)

将 fillcolor 设置为由 rgb 表示的 RGB 颜色。 rgb 中的每一个都必须在 0..colormode 范围内。

如果turtleshape 是多边形,则使用新设置的fillcolor 绘制该多边形的内部。

>>> turtle.fillcolor("violet")
>>> turtle.fillcolor()
'violet'
>>> turtle.pencolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor((50, 193, 143))  # Integers, not floats
>>> turtle.fillcolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor('#ffffff')
>>> turtle.fillcolor()
(255.0, 255.0, 255.0)
turtle.color(*args)

返回或设置 pencolor 和 fillcolor。

允许使用多种输入格式。 它们使用 0 到 3 个参数,如下所示:

color()

将当前画笔颜色和当前填充颜色作为一对颜色规范字符串或元组返回,如 pencolor()fillcolor() 返回。

color(colorstring)color((r,g,b))color(r,g,b)

pencolor() 中的输入,将 fillcolor 和 pencolor 都设置为给定值。

color(colorstring1, colorstring2)color((r1,g1,b1), (r2,g2,b2))

等效于 pencolor(colorstring1)fillcolor(colorstring2),如果使用其他输入格式,则类似。

如果turtleshape 是多边形,则使用新设置的颜色绘制该多边形的轮廓和内部。

>>> turtle.color("red", "green")
>>> turtle.color()
('red', 'green')
>>> color("#285078", "#a0c8f0")
>>> color()
((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))

另请参阅:屏幕方法 colormode()


灌装

turtle.filling()

返回填充状态(True 如果填充,False 否则)。

>>> turtle.begin_fill()
>>> if turtle.filling():
...    turtle.pensize(5)
... else:
...    turtle.pensize(3)
turtle.begin_fill()
在绘制要填充的形状之前调用。
turtle.end_fill()

填充最后一次调用 begin_fill() 后绘制的形状。

是否填充自相交多边形或多个形状的重叠区域取决于操作系统图形、重叠类型和重叠数量。 例如,上面的海龟星可能全是黄色或有一些白色区域。

>>> 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 – 要写入 TurtleScreen 的对象

  • move – 真/假

  • align – “左”、“中”或“右”字符串之一

  • font – 三元组(字体名称、字体大小、字体类型)

写入文本 - arg 的字符串表示 - 根据 align(“左”,“中”或“右”)和给定的字体在当前海龟位置。 如果 move 为真,笔将移动到文本的右下角。 默认情况下,moveFalse

>>> turtle.write("Home = ", True, align="center")
>>> turtle.write((0,0), True)


龟州

能见度

turtle.hideturtle()
turtle.ht()

使乌龟隐形。 在您正在进行一些复杂的绘图时这样做是个好主意,因为隐藏海龟可以明显加快绘图速度。

>>> turtle.hideturtle()
turtle.showturtle()
turtle.st()

使乌龟可见。

>>> turtle.showturtle()
turtle.isvisible()

如果显示海龟,则返回 True,如果隐藏则返回 False

>>> turtle.hideturtle()
>>> turtle.isvisible()
False
>>> turtle.showturtle()
>>> turtle.isvisible()
True


外观

turtle.shape(name=None)
参数

name – 一个字符串,它是一个有效的 shapename

将海龟形状设置为具有给定 name 的形状,或者,如果未给出名称,则返回当前形状的名称。 带有 name 的形状必须存在于 TurtleScreen 的形状字典中。 最初有以下多边形形状:“箭头”、“乌龟”、“圆形”、“正方形”、“三角形”、“经典”。 要了解如何处理形状,请参阅 Screen 方法 register_shape()

>>> turtle.shape()
'classic'
>>> turtle.shape("turtle")
>>> turtle.shape()
'turtle'
turtle.resizemode(rmode=None)
参数

rmode – 字符串“auto”、“user”、“noresize”之一

将 resizemode 设置为以下值之一:“auto”、“user”、“noresize”。 如果未给出 rmode,则返回当前调整大小模式。 不同的resizemode有以下效果:

  • “auto”:根据 pensize 的值调整海龟的外观。

  • “user”:根据由shapesize()设置的stretchfactor和outlinewidth(outline)的值来适配海龟的外观。

  • “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 – 正数

  • stretch_len – 正数

  • outline – 正数

返回或设置笔的属性 x/y-stretchfactors 和/或轮廓。 将调整大小模式设置为“用户”。 当且仅当 resizemode 设置为“user”时,海龟将根据其拉伸因子显示拉伸:stretch_wid 是垂直于其方向的拉伸因子,stretch_len 是其方向的拉伸因子方向,outline 确定形状轮廓的宽度。

>>> 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 – 数字(可选)

设置或返回当前的剪切因子。 根据给定的剪切因子剪切剪切海龟形状,剪切角的切线。 做 改变海龟的航向(移动方向)。 如果没有给出剪切:返回当前的剪切因子,i。 e. 剪切角的切线,平行于海龟航向的线被剪切。

>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.shearfactor(0.5)
>>> turtle.shearfactor()
0.5
turtle.tilt(angle)
参数

angle – 一个数字

将海龟从当前倾斜角度旋转 angle,但不要 改变海龟的航向(移动方向)。

>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(30)
>>> turtle.fd(50)
>>> turtle.tilt(30)
>>> turtle.fd(50)
turtle.settiltangle(angle)
参数

angle – 一个数字

旋转海龟形状以指向 angle 指定的方向,而不管其当前的倾斜角度。 不要改变海龟的航向(移动方向)。

>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.settiltangle(45)
>>> turtle.fd(50)
>>> turtle.settiltangle(-45)
>>> turtle.fd(50)

自 3.1 版起已弃用。

turtle.tiltangle(angle=None)
参数

angle – 一个数字(可选)

设置或返回当前的倾斜角度。 如果给出角度,则旋转海龟形状以指向角度指定的方向,而不管其当前的倾斜角度。 做 改变海龟的航向(移动方向)。 如果没有给出角度:返回当前的倾斜角度,i。 e. 海龟形状的方向和海龟的方向(它的运动方向)之间的角度。

>>> 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 – 一个数字(可选)

  • t12 – 一个数字(可选)

  • t21 – 一个数字(可选)

  • t12 – 一个数字(可选)

设置或返回海龟形状的当前变换矩阵。

如果没有给出任何矩阵元素,则以 4 个元素的元组形式返回变换矩阵。 否则,设置给定的元素并根据由第一行 t11, t12 和第二行 t21, 22 组成的矩阵转换海龟形状。 行列式 t11 * t22 - t12 * t21 不能为零,否则会引发错误。 根据给定的矩阵修改拉伸因子、剪切因子和倾斜角。

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

将当前形状多边形作为坐标对的元组返回。 这可用于定义新形状或复合形状的组件。

>>> 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 – 一个带有两个参数的函数,将使用画布上点击点的坐标调用

  • btn – 鼠标按钮编号,默认为 1(鼠标左键)

  • addTrueFalse – 如果是 True,将添加新绑定,否则将替换之前的绑定

fun 绑定到此海龟的鼠标点击事件。 如果 funNone,则删除现有绑定。 匿名海龟的例子,即 程序方式:

>>> def turn(x, y):
...     left(180)
...
>>> onclick(turn)  # Now clicking into the turtle will turn it.
>>> onclick(None)  # event-binding will be removed
turtle.onrelease(fun, btn=1, add=None)
参数
  • fun – 一个带有两个参数的函数,将使用画布上点击点的坐标调用

  • btn – 鼠标按钮编号,默认为 1(鼠标左键)

  • addTrueFalse – 如果是 True,将添加新绑定,否则将替换之前的绑定

fun 绑定到此海龟上的鼠标按钮释放事件。 如果 funNone,则删除现有绑定。

>>> class MyTurtle(Turtle):
...     def glow(self,x,y):
...         self.fillcolor("red")
...     def unglow(self,x,y):
...         self.fillcolor("")
...
>>> turtle = MyTurtle()
>>> turtle.onclick(turtle.glow)     # clicking on turtle turns fillcolor red,
>>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
turtle.ondrag(fun, btn=1, add=None)
参数
  • fun – 一个带有两个参数的函数,将使用画布上点击点的坐标调用

  • btn – 鼠标按钮编号,默认为 1(鼠标左键)

  • addTrueFalse – 如果是 True,将添加新绑定,否则将替换之前的绑定

fun 绑定到此海龟上的鼠标移动事件。 如果 funNone,则删除现有绑定。

备注:海龟上的每个鼠标移动事件序列都在该海龟上发生鼠标点击事件之前。

>>> turtle.ondrag(turtle.goto)

随后,单击并拖动 Turtle 将在屏幕上移动它,从而产生手绘(如果笔已放下)。


特殊海龟方法

turtle.begin_poly()
开始记录多边形的顶点。 当前海龟位置是多边形的第一个顶点。
turtle.end_poly()
停止记录多边形的顶点。 当前海龟位置是多边形的最后一个顶点。 这将与第一个顶点连接。
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()

创建并返回具有相同位置、方向和海龟属性的海龟的克隆。

>>> mick = Turtle()
>>> joe = mick.clone()
turtle.getturtle()
turtle.getpen()

返回 Turtle 对象本身。 仅合理使用:作为返回“匿名海龟”的函数:

>>> 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 给出了 undo() 方法/函数可以撤消的海龟动作的最大数量。 如果 sizeNone,则禁用 undobuffer。

>>> turtle.setundobuffer(42)
turtle.undobufferentries()

返回撤消缓冲区中的条目数。

>>> while undobufferentries():
...     undo()


复合形状

要使用由多个不同颜色的多边形组成的复合海龟形状,您必须明确使用辅助类 Shape,如下所述:

  1. 创建一个“复合”类型的空 Shape 对象。

  2. 使用 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")
  3. 现在将 Shape 添加到 Screen 的 shapelist 并使用它:

    >>> register_shape("myshape", s)
    >>> shape("myshape")

笔记

Shape 类由 register_shape() 方法以不同方式在内部使用。 当使用如上所示的复合形状时,应用程序员必须处理 Shape 类 only


TurtleScreen/Screen 的方法和对应的函数

本节中的大多数示例都引用了一个名为 screen 的 TurtleScreen 实例。

窗口控制

turtle.bgcolor(*args)
参数

args – 一个颜色字符串或三个 0..colormode 范围内的数字或此类数字的 3 元组

设置或返回 TurtleScreen 的背景颜色。

>>> screen.bgcolor("orange")
>>> screen.bgcolor()
'orange'
>>> screen.bgcolor("#800080")
>>> screen.bgcolor()
(128.0, 0.0, 128.0)
turtle.bgpic(picname=None)
参数

picname – 一个字符串、gif 文件的名称或 "nopic"None

设置背景图片或返回当前背景图片的名称。 如果 picname 是文件名,则将相应的图像设置为背景。 如果 picname"nopic",请删除背景图像(如果存在)。 如果 picnameNone,则返回当前背景图片的文件名。

>>> screen.bgpic()
'nopic'
>>> screen.bgpic("landscape.gif")
>>> screen.bgpic()
"landscape.gif"
turtle.clear()
turtle.clearscreen()

从 TurtleScreen 中删除所有绘图和所有海龟。 将现在为空的 TurtleScreen 重置为其初始状态:白色背景、无背景图像、无事件绑定和跟踪。

笔记

此 TurtleScreen 方法仅在名称 clearscreen 下可用作全局函数。 全局函数 clear 是从 Turtle 方法 clear 派生的一个不同的函数。

turtle.reset()
turtle.resetscreen()

将屏幕上的所有海龟重置为其初始状态。

笔记

此 TurtleScreen 方法仅在名称 resetscreen 下可用作全局函数。 全局函数 reset 是另一个衍生自 Turtle 方法 reset 的函数。

turtle.screensize(canvwidth=None, canvheight=None, bg=None)
参数
  • canvwidth – 正整数,画布的新宽度(以像素为单位)

  • canvheight – 正整数,画布的新高度(以像素为单位)

  • bg – 颜色字符串或颜色元组,新的背景颜色

如果没有给出参数,则返回当前(画布宽度,画布高度)。 否则调整海龟正在绘制的画布的大小。 不要改变绘图窗口。 要观察画布的隐藏部分,请使用滚动条。 使用这种方法,可以使之前画布之外的绘图部分可见。

>>> screen.screensize()
(400, 300)
>>> screen.screensize(2000,1500)
>>> screen.screensize()
(2000, 1500)

例如 寻找一只错误逃脱的乌龟 ;-)

turtle.setworldcoordinates(llx, lly, urx, ury)
参数
  • llx – 一个数字,画布左下角的 x 坐标

  • lly – 一个数字,画布左下角的 y 坐标

  • urx – 一个数字,画布右上角的 x 坐标

  • ury – 数字,画布右上角的 y 坐标

设置用户定义的坐标系,必要时切换到“世界”模式。 这将执行 screen.reset()。 如果“世界”模式已激活,则所有图形都将根据新坐标重新绘制。

注意:在用户定义的坐标系中,角度可能会出现扭曲。

>>> screen.reset()
>>> screen.setworldcoordinates(-50,-7.5,50,7.5)
>>> for _ in range(72):
...     left(10)
...
>>> for _ in range(8):
...     left(45); fd(2)   # a regular octagon


动画控制

turtle.delay(delay=None)
参数

delay – 正整数

以毫秒为单位设置或返回绘图 delay。 (这大约是两次连续画布更新之间的时间间隔。)绘制延迟越长,动画越慢。

可选参数:

>>> screen.delay()
10
>>> screen.delay(5)
>>> screen.delay()
5
turtle.tracer(n=None, delay=None)
参数
  • n – 非负整数

  • delay – 非负整数

打开/关闭海龟动画并设置更新图纸的延迟。 如果给出 n,则仅真正执行第 n 次常规屏幕更新。 (可用于加速复杂图形的绘制。)不带参数调用时,返回当前存储的 n 值。 第二个参数设置延迟值(参见 delay())。

>>> 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)
将焦点设置在 TurtleScreen 上(以收集关键事件)。 提供虚拟参数是为了能够将 listen() 传递给 onclick 方法。
turtle.onkey(fun, key)
turtle.onkeyrelease(fun, key)
参数
  • fun – 没有参数的函数或 None

  • key – 一个字符串:key(例如 “a”)或键符号(例如 “空间”)

fun 绑定到按键的按键释放事件。 如果 funNone,则删除事件绑定。 备注:为了能够注册按键事件,TurtleScreen 必须有焦点。 (参见方法 listen()。)

>>> def f():
...     fd(50)
...     lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
turtle.onkeypress(fun, key=None)
参数
  • fun – 没有参数的函数或 None

  • key – 一个字符串:key(例如 “a”)或键符号(例如 “空间”)

如果给定了键,则将 fun 绑定到键的按键事件,如果没有给定键,则绑定到任何按键事件。 备注:为了能够注册按键事件,TurtleScreen 必须有焦点。 (参见方法 listen()。)

>>> def f():
...     fd(50)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
turtle.onclick(fun, btn=1, add=None)
turtle.onscreenclick(fun, btn=1, add=None)
参数
  • fun – 一个带有两个参数的函数,将使用画布上点击点的坐标调用

  • btn – 鼠标按钮编号,默认为 1(鼠标左键)

  • addTrueFalse – 如果是 True,将添加新绑定,否则将替换之前的绑定

fun 绑定到此屏幕上的鼠标单击事件。 如果 funNone,则删除现有绑定。

名为 screen 的 TurtleScreen 实例和名为 turtle 的 Turtle 实例的示例:

>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>>                             # make the turtle move to the clicked point.
>>> screen.onclick(None)        # remove event binding again

笔记

此 TurtleScreen 方法仅在名称 onscreenclick 下可用作全局函数。 全局函数 onclick 是另一个衍生自 Turtle 方法 onclick 的函数。

turtle.ontimer(fun, t=0)
参数
  • fun – 一个没有参数的函数

  • t – 一个数字 >= 0

安装一个计时器,在 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 函数。 必须是海龟图形程序中的最后一条语句。 如果脚本在 IDLE 中以 -n 模式(无子进程)运行,则必须使用 not - 用于海龟图形的交互使用。

>>> screen.mainloop()


输入法

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 – 数字(可选)

  • minval – 数字(可选)

  • maxval – 数量(可选)

弹出一个输入数字的对话窗口。 title 是对话窗口的标题,prompt 是一段文字,主要描述输入什么数字信息。 默认值:默认值,minval:输入的最小值,maxval:输入的最大值输入的数字必须在 minval .. 如果给出这些,则为 maxval。 如果不是,则会发出提示并且对话框保持打开状态以进行更正。 返回数字输入。 如果对话框被取消,返回None

>>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)


设置和特殊方法

turtle.mode(mode=None)
参数

mode – 字符串“standard”、“logo”或“world”之一

设置海龟模式(“标准”、“标志”或“世界”)并执行重置。 如果没有给出模式,则返回当前模式。

模式“标准”与旧的 turtle 兼容。 模式“logo”与大多数 Logo 海龟图形兼容。 “世界”模式使用用户定义的“世界坐标”。 注意:在此模式下,如果x/y单位比不等于1,角度会出现扭曲。

模式

初始海龟航向

正角

“标准”

向右(东)

逆时针

“标识”

向上(北)

顺时针

>>> mode("logo")   # resets turtle heading to north
>>> mode()
'logo'
turtle.colormode(cmode=None)
参数

cmode – 值 1.0 或 255 之一

返回颜色模式或将其设置为 1.0 或 255。 随后颜色三元组的 rgb 值必须在 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)

可以通过三种不同的方式调用此函数:

  1. name为gif文件名,shapeNone:安装对应的图片形状。

    >>> screen.register_shape("turtle.gif")

    笔记

    转动海龟时图像形状旋转,因此它们不显示海龟的航向!

  2. name 是任意字符串,shape 是坐标对的元组:安装相应的多边形形状。

    >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
  3. name 是任意字符串,shape 是(复合) Shape 对象:安装对应的复合形状。

将海龟形状添加到 TurtleScreen 的形状列表。 通过发出命令shape(shapename),只能使用这样注册的形状。

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 的方法,不是从 TurtleScreen 继承的

turtle.bye()
关闭turtlegraphics窗口。
turtle.exitonclick()

将 bye() 方法绑定到屏幕上的鼠标点击。

如果配置字典中“using_IDLE”的值为False(默认值),同样进入mainloop。 备注:如果使用带有-n开关(无子进程)的IDLE,则该值应设置为turtle.cfg中的True。 在这种情况下,IDLE 自己的主循环对于客户端脚本也处于活动状态。

turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom'])

设置主窗口的大小和位置。 参数的默认值存储在配置字典中,可以通过 turtle.cfg 文件进行更改。

参数
  • width - 如果是整数,则以像素为单位的大小,如果是浮点数,则为屏幕的一部分; 默认为 50% of 屏幕

  • height - 如果是整数,则以像素为单位的高度,如果是浮点数,则为屏幕的一小部分; 默认为 75% of 屏幕

  • startx - 如果为正,从屏幕左边缘开始的像素位置,如果从右边缘为负,如果 None,水平居中窗口

  • starty - 如果为正,从屏幕顶部边缘开始的像素位置,如果从底部边缘为负,如果 None,垂直居中窗口

>>> screen.setup (width=200, height=200, startx=0, starty=0)
>>>              # sets window to 200x200 pixels, in upper left of screen
>>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
>>>              # sets window to 75% of screen by 50% of screen and centers
turtle.title(titlestring)
参数

titlestring – 显示在海龟图形窗口标题栏中的字符串

将海龟窗口的标题设置为 titlestring

>>> screen.title("Welcome to the turtle zoo!")


公开课

class turtle.RawTurtle(canvas)
class turtle.RawPen(canvas)
参数

canvastkinter.CanvasScrolledCanvasTurtleScreen

创建一只乌龟。 海龟具有上述所有方法,称为“海龟/RawTurtle 的方法”。

class turtle.Turtle
RawTurtle 的子类,具有相同的界面,但绘制在第一次需要时自动创建的默认 Screen 对象。
class turtle.TurtleScreen(cv)
参数

cvtkinter.Canvas

提供面向屏幕的方法,如 setbg() 等。 上面描述的。

class turtle.Screen
TurtleScreen 的子类,添加了 四个方法
class turtle.ScrolledCanvas(master)
参数

master – 一些包含 ScrolledCanvas 的 Tkinter 小部件,即 添加了滚动条的 Tkinter-canvas

由类 Screen 使用,因此它会自动提供一个 ScrolledCanvas 作为海龟的游乐场。

class turtle.Shape(type_, data)
参数

type_ – 字符串“polygon”、“image”、“compound”之一

数据结构建模形状。 对 (type_, data) 必须遵循以下规范:

类型_

数据

“多边形”

一个多边形元组,即 一组坐标对

“图片”

一张图片(这种形式只在内部使用!)

“化合物”

None(必须使用 addcomponent() 方法构建复合形状)

addcomponent(poly, fill, outline=None)
参数
  • poly – 一个多边形,即 一对数字的元组

  • fillpoly 将填充的颜色

  • outline – 多边形轮廓的颜色(如果给定)

示例:

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

一个二维向量类,用作实现海龟图形的辅助类。 也可能对海龟图形程序有用。 派生自元组,所以向量是元组!

提供(对于 ab 向量、k 编号):

  • a + b 矢量加法

  • a - b 矢量减法

  • a * b 内积

  • k * aa * k 与标量的乘法

  • abs(a) a 的绝对值

  • a.rotate(angle) 旋转


帮助和配置

如何使用帮助

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 – 一个字符串,用作文件名

使用给定的文件名创建 docstring-dictionary 并将其写入 Python 脚本。 必须显式调用此函数(海龟图形类不使用它)。 文档字符串字典将写入 Python 脚本 filename.py。 它旨在用作将文档字符串翻译成不同语言的模板。

如果您(或您的学生)想在您的母语中使用 turtle 在线帮助,您必须翻译文档字符串并将生成的文件保存为例如 turtle_docstringdict_german.py

如果您的 turtle.cfg 文件中有适当的条目,该词典将在导入时被读入并替换原始英文文档字符串。

在撰写本文时,有德语和意大利语的文档字符串词典。 (请求请发送至 glingl@aon.at。)


如何配置 Screen 和 Turtles

内置的默认配置模仿旧海龟模块的外观和行为,以保持与它的最佳兼容性。

如果您想使用不同的配置来更好地反映此模块的功能或更适合您的需求,例如 在教室中使用时,您可以准备一个配置文件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 可以是任何内置的形状,例如:箭头、乌龟等。 有关更多信息,请尝试 help(shape)
  • 如果您不想使用填充色(即 使乌龟透明),你必须写 fillcolor = "" (但所有非空字符串在 cfg 文件中不能有引号)。
  • 如果你想反映乌龟的状态,你必须使用 resizemode = auto
  • 如果你设置例如 language = italian docstringdict turtle_docstringdict_italian.py 将在导入时加载(如果存在于导入路径中,例如 在与 turtle 相同的目录中。
  • 条目 exampleturtleexamplescreen 定义了这些对象在文档字符串中出现的名称。 将方法文档字符串转换为函数文档字符串将从文档字符串中删除这些名称。
  • using_IDLE:如果您经常使用 IDLE 及其 -n 开关(“无子进程”),请将其设置为 True。 这将阻止 exitonclick() 进入主循环。

turtle所在的目录下可以有一个turtle.cfg文件,在当前工作目录下还有一个。 后者将覆盖第一个的设置。

Lib/turtledemo 目录包含一个 turtle.cfg 文件。 您可以将其作为示例进行研究,并在运行演示时查看其效果(最好不在演示查看器中)。


turtledemo — 演示脚本

turtledemo 包包含一组演示脚本。 可以使用提供的演示查看器运行和查看这些脚本,如下所示:

python -m turtledemo

或者,您可以单独运行演示脚本。 例如,

python -m turtledemo.bytedesign

turtledemo 包目录包含:

  • 一个演示查看器 __main__.py,可用于查看脚本的源代码并同时运行它们。
  • 多个脚本演示了 turtle 模块的不同功能。 可以通过“示例”菜单访问示例。 它们也可以独立运行。
  • turtle.cfg 文件,作为如何编写和使用此类文件的示例。

演示脚本是:

姓名 说明 特点
字节设计 复杂的古典海龟图形图案 tracer(),延迟,update()
混乱 图 Verhulst 动力学,表明计算机的计算有时会产生违反常识预期的结果 世界坐标
时钟 显示计算机时间的模拟时钟 乌龟作为时钟的指针,计时器
混色器 用 r, g, b 做实验 ondrag()
森林 3 广度优先树 随机化
分形曲线 希尔伯特和科赫曲线 递归
林登迈尔 民族数学(印度科拉姆) L-系统
最小河内 河内塔 矩形海龟作为河内圆盘(形状,形状大小)
尼姆 用三堆木棒对着电脑玩经典的尼姆游戏。 海龟作为 nimsticks,事件驱动(鼠标,键盘)
油漆 超级简约的绘图程序 onclick()
和平 初级 乌龟:外观和动画
彭罗斯 用风筝和飞镖进行非周期性平铺 stamp()
行星和月亮 引力系统模拟 复合形状,Vec2D
圆舞 舞龟成对旋转相反方向 复合形状,克隆形状大小,倾斜,get_shapepoly,更新
sort_animate 不同分拣方法的可视化演示 简单对齐,随机化
(图形)广度优先树(使用生成器) clone()
two_canvases 简单的设计 两幅画布上的海龟
维基百科 维基百科关于海龟图形的文章的模式 clone()undo()
阴阳 另一个基本例子 circle()

玩得开心!


自 Python 2.6 以来的变化

  • 方法 Turtle.tracer()Turtle.window_width()Turtle.window_height() 已被淘汰。 具有这些名称和功能的方法现在只能作为 Screen 的方法使用。 从这些派生出来的功能仍然可用。 (实际上,在 Python 2.6 中,这些方法只是相应 TurtleScreen/Screen 方法的重复。)
  • 方法 Turtle.fill() 已被淘汰。 begin_fill()end_fill() 的行为略有变化:现在每个填充过程都必须通过 end_fill() 调用完成。
  • 添加了方法 Turtle.filling()。 它返回一个布尔值:True 如果正在填充过程,则 False 否则。 此行为对应于 Python 2.6 中不带参数的 fill() 调用。


自 Python 3.0 以来的变化

  • 添加了方法 Turtle.shearfactor()Turtle.shapetransform()Turtle.get_shapepoly()。 因此,现在可以使用所有常规线性变换来变换海龟形状。 Turtle.tiltangle() 功能增强:现在可用于获取或设置倾斜角。 Turtle.settiltangle() 已被弃用。
  • 方法 Screen.onkeypress() 已添加为 Screen.onkey() 的补充,实际上将动作绑定到 keyrelease 事件。 因此后者有一个别名:Screen.onkeyrelease()
  • 添加了方法 Screen.mainloop()。 因此,当仅使用 Screen 和 Turtle 对象时,不得再额外导入 mainloop()
  • 添加了两种输入法 Screen.textinput()Screen.numinput()。 这些弹出输入对话框并分别返回字符串和数字。
  • 两个示例脚本 tdemo_nim.pytdemo_round_dance.py 已添加到 Lib/turtledemo 目录中。