"turtle" --- 海龟绘图
*********************

**源码：** Lib/turtle.py

======================================================================


Turtle star
^^^^^^^^^^^

使用海龟绘图可以编写重复执行简单动作的程序画出精细复杂的形状。

[图片： 带有细长尖刺和红色轮廓线的黄色星形图案，使用 turtle 绘制。][图
片]

请想象绘图区有一只机器海龟位于 x-y 平面中的起始位置 (0, 0)。 在
"import turtle" 之后，向它发出命令 "turtle.forward(15)"，它将（在屏幕
上！）朝它所面对的方向移动 15 个像素，随着它的移动画一条线段。 再向它
发出命令 "turtle.right(25)"，它将原地顺时针旋转 25 度。

Turtle graphics is an implementation of the drawing tools introduced
in Logo in 1967. It was created as an educational tool, and its
instant, visible feedback makes it an effective way for learners to
encounter programming concepts. It is also a convenient way to produce
simple graphical output without bringing in external libraries.

本文档包括了四个主要部分：

* 教程 讲解了海龟绘图的基础概念。

* 参考 描述了该模块定义的函数、方法和类。

* 常用方案指引 detail how to handle specific tasks.

* 说明 提供了有关面向对象接口的背景知识。

备注:

  Turtle graphics requires the "tkinter" *optional module*. The
  python.org installers for Windows and macOS include it, but some
  Linux distributions and other platforms may package it separately.
  If "import turtle" fails with an error mentioning "_tkinter", look
  for documentation from your distributor (that is, whoever provided
  Python to you). Check this in advance if you're planning to use
  turtle graphics with a learner.


教程
====

新用户应当从这里开始。 在本教程中我们将探索海龟绘图的一些基本知识。


启动海龟环境
------------

在 Python shell 中，导入 "turtle" 模块的所有对象:

   from turtle import *

如果你遇到了 "Standard library module '_tkinter' was not found" 错误，
则你需要在你的系统上安装 "Tk interface 软件包"。

尚未显示任何内容。 要打开海龟窗口，并显示海龟图标:

   showturtle()

打开一个新窗口，海龟位于中央，显示为一个指向东方的箭头。


基本绘图
--------

让海龟前进 100 步:

   forward(100)

You should see a line drawn by the turtle, heading East. Change the
direction of the turtle, so that it turns 120 degrees left (anti-
clockwise):

   left(120)

让我们继续画一个三角形:

   forward(100)
   left(120)
   forward(100)

注意以一个箭头表示的海龟是如何随着你的操纵指向不同方向的。

Experiment with those commands, and also with "backward()" and
"right()". Many commands also have shorter aliases, such as "fd()" for
"forward()".


画笔控制
~~~~~~~~

试着改变颜色 —— 例如，"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** -- 一个数值

   Move the turtle backward by *distance*, opposite to the direction
   the turtle is headed. The turtle's heading does not change.

      >>> turtle.position()
      (0.00,0.00)
      >>> turtle.backward(30)
      >>> turtle.position()
      (-30.00,0.00)

turtle.right(angle)
turtle.rt(angle)

   参数:
      **angle** -- 一个数值

   Turn the turtle right by the specified *angle*. The angle is
   measured in degrees by default; the unit can be changed with
   "degrees()" or "radians()". How the heading is measured depends on
   the turtle mode, see "mode()".

      >>> turtle.heading()
      22.0
      >>> turtle.right(45)
      >>> turtle.heading()
      337.0

turtle.left(angle)
turtle.lt(angle)

   参数:
      **angle** -- 一个数值

   Turn the turtle left by the specified *angle*. The angle is
   measured in degrees by default; the unit can be changed with
   "degrees()" or "radians()". How the heading is measured depends on
   the turtle mode, see "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"

   Move the turtle to an absolute position. If *y* is "None", *x* must
   be a pair of coordinates or a "Vec2D", for example as returned by
   "pos()". If the pen is down, a line is drawn. The turtle's heading
   does not change.

      >>> 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, y=None, *, fill_gap=False)

   参数:
      * **x** -- 一个数值或 "None"

      * **y** -- 一个数值或 "None"

      * **fill_gap** -- 布尔

   将海龟移到某个绝对位置。 不同于 goto(x, y)，这将不会画一条线段。 海
   龟的方向不变。 如果当前正在填充，离开后原位置上的多边形将被填充，在
   移位后将再次开始填充。 这可以通过 fill_gap=True 来禁用，此设置将使
   在移位期间海龟的移动轨迹线像在 goto(x, y) 中一样被当作填充边缘。

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

   Added in version 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** -- 一个数值

   Set the turtle's y coordinate to *y*. The x coordinate is
   unchanged.

      >>> 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** -- 一个数值

   Set the turtle's heading to *to_angle*. Here are some common
   directions in degrees:

   +---------------------+----------------------+
   | 标准模式            | logo 模式            |
   |=====================|======================|
   | 0 - 东              | 0 - 北               |
   +---------------------+----------------------+
   | 90 - 北             | 90 - 东              |
   +---------------------+----------------------+
   | 180 - 西            | 180 - 南             |
   +---------------------+----------------------+
   | 270 - 南            | 270 - 西             |
   +---------------------+----------------------+

      >>> turtle.setheading(90)
      >>> turtle.heading()
      90.0

turtle.home()

   Move the turtle to the origin, coordinates (0,0). The turtle's
   heading is set to its start orientation, which depends on the
   turtle mode, see "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"

   Draw a circle with the given *radius*. The center is *radius* units
   left of the turtle; *extent*, an angle, determines which part of
   the circle is drawn. If *extent* is not given, draw the entire
   circle. If *extent* is not a full circle, one endpoint of the arc
   is the current pen position. Draw the arc in counterclockwise
   direction if *radius* is positive, otherwise in clockwise
   direction. Finally, the turtle's heading is changed by *extent*.

   As the circle is approximated by an inscribed regular polygon,
   *steps* determines the number of steps to use. If not given, it
   will be calculated automatically. May be used to draw regular
   polygons.

      >>> 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** -- 一个整型数 >= 1 (如果指定)

      * **color** -- 一个颜色字符串或颜色数值元组

   绘制一个直径为 *size*，颜色为 *color* 的圆点。 如果未给出 *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")
      >>> stamp_id = turtle.stamp()
      >>> 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* 个海龟印章。如果 *n* 为 "None" 则删除全部印章，
   如果 *n* > 0 则删除前 *n* 个印章，否则如果 *n* < 0 则删除后 *n* 个
   印章。

      >>> 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** -- 一个 0..10 范围内的整型数或速度字符串 (见下)

   设置海龟移动的速度为 0..10 表示的整型数值。如未指定参数则返回当前速
   度。

   如果输入数值大于 10 或小于 0.5 则速度设为 0。速度字符串与速度值的对
   应关系如下:

   * "fastest":  0 最快

   * "fast":  10 快

   * "normal":  6 正常

   * "slow":  3 慢

   * "slowest":  1 最慢

   速度值从 1 到 10，画线和海龟转向的动画效果逐级加快。

   注意: *speed* = 0 表示 *没有* 动画效果。forward/back 将使海龟向前/
   向后跳跃，同样的 left/right 将使海龟立即改变朝向。

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


获取海龟的状态
~~~~~~~~~~~~~~

turtle.position()
turtle.pos()

   Return the turtle's current location (x,y) as a "Vec2D" vector.

      >>> turtle.pos()
      (440.00,-0.00)

turtle.towards(x, y=None)

   参数:
      * **x** -- 一个数值或数值对/矢量，或一个海龟实例

      * **y** -- 一个数值——如果 *x* 是一个数值，否则为 "None"

   Return the angle of the line from the turtle's position to (x,y).
   If *y* is "None", *x* must be a pair of coordinates, a "Vec2D", for
   example as returned by "pos()", or another turtle. The angle is
   measured from the turtle's start orientation, which depends on the
   turtle mode, see "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()

   Return the turtle's current heading. The value depends on the
   turtle mode, see "mode()".

      >>> turtle.home()
      >>> turtle.left(67)
      >>> turtle.heading()
      67.0

turtle.distance(x, y=None)

   参数:
      * **x** -- 一个数值或数值对/矢量，或一个海龟实例

      * **y** -- 一个数值——如果 *x* 是一个数值，否则为 "None"

   Return the distance from the turtle to (x,y) in turtle step units.
   If *y* is "None", *x* must be a pair of coordinates, a "Vec2D", for
   example as returned by "pos()", or another turtle.

      >>> 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** -- 一个数值

   Set the angle measurement units to degrees. The number of degrees
   in a full circle is set to *fullcircle*, which defaults to 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()

   Set the angle measurement units to radians.  Equivalent to
   "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 为多边形，该多边形也以同样粗细的线条绘制。如未指定参
   数，则返回当前的 pensize。

      >>> turtle.pensize()
      1
      >>> turtle.pensize(10)   # 从这里开始，画出宽度为10的线

turtle.pen(pen=None, **pendict)

   参数:
      * **pen** -- 一个包含部分或全部下列键的字典

      * **pendict** -- 一个或多个以下列键为关键字的关键字参数

   返回或设置画笔的属性，以一个包含以下键值对的 "画笔字典" 表示:

   * "shown": True/False

   * "pendown": True/False

   * "pencolor": 颜色字符串或颜色元组

   * "fillcolor": 颜色字符串或颜色元组

   * "pensize": 正数值

   * "speed": 0..10 范围内的数值

   * "resizemode": "auto" 或 "user" 或 "noresize"

   * "stretchfactor": (正数值, 正数值)

   * "outline": 正数值

   * "tilt": 数值

   此字典可作为后续调用 "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()
turtle.pencolor(color, /)
turtle.pencolor(r, g, b, /)

   返回或设置画笔颜色。

   允许以下四种输入格式:

   "pencolor()"
      Return the current pencolor as color specification string or as
      a tuple (see example).  May be used as input to another
      "color()", "pencolor()", "fillcolor()" or "bgcolor()" call.

   "pencolor(colorstring)"
      设置画笔颜色为 *colorstring* 指定的 Tk 颜色描述字符串，例如
      ""red""、""yellow"" 或 ""#33cc8c""。

   "pencolor((r, g, b))"
      设置画笔颜色为以 *r*, *g*, *b* 元组表示的 RGB 颜色。*r*, *g*,
      *b* 的取值范围应为 0..colormode，colormode 的值为 1.0 或 255 (参
      见 "colormode()")。

   "pencolor(r, g, b)"
      设置画笔颜色为以 *r*, *g*, *b* 表示的 RGB 颜色。*r*, *g*, *b* 的
      取值范围应为 0..colormode。

   如果 turtleshape 为多边形，该多边形轮廓也以新设置的画笔颜色绘制。

      >>> 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()"
      Return the current fillcolor as color specification string,
      possibly in tuple format (see example).  May be used as input to
      another "color()", "pencolor()", "fillcolor()" or "bgcolor()"
      call.

   "fillcolor(colorstring)"
      设置填充颜色为 *colorstring* 指定的 Tk 颜色描述字符串，例如
      ""red""、""yellow"" 或 ""#33cc8c""。

   "fillcolor((r, g, b))"
      设置填充颜色为以 *r*, *g*, *b* 元组表示的 RGB 颜色。*r*, *g*,
      *b* 的取值范围应为 0..colormode，colormode 的值为 1.0 或 255 (参
      见 "colormode()")。

   "fillcolor(r, g, b)"
      设置填充颜色为 *r*, *g*, *b* 表示的 RGB 颜色。*r*, *g*, *b* 的取
      值范围应为 0..colormode。

   如果 turtleshape 为多边形，该多边形内部也以新设置的填充颜色填充。

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

   返回或设置画笔颜色和填充颜色。

   允许多种输入格式。使用如下 0 至 3 个参数:

   "color()"
      返回以一对颜色描述字符串或元组表示的当前画笔颜色和填充颜色，两者
      可分别由 "pencolor()" 和 "fillcolor()" 返回。

   "color(colorstring)", "color((r,g,b))", "color(r,g,b)"
      输入格式与 "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))

另参见: Screen 方法 "colormode()"。


填充
""""

turtle.filling()

   返回填充状态 (填充为 "True"，否则为 "False")。

      >>> turtle.begin_fill()
      >>> if turtle.filling():
      ...    turtle.pensize(5)
      ... else:
      ...    turtle.pensize(3)

turtle.fill()

   填充在 "with turtle.fill():" 块中绘制的形状。

      >>> turtle.color("black", "red")
      >>> with turtle.fill():
      ...     turtle.circle(80)

   使用 "fill()" 相当于在填充块之前添加 "begin_fill()"，在填充块之后添
   加 "end_fill()":

      >>> turtle.color("black", "red")
      >>> turtle.begin_fill()
      >>> turtle.circle(80)
      >>> turtle.end_fill()

   Added in version 3.14.

turtle.begin_fill()

   在绘制要填充的形状之前调用。

turtle.end_fill()

   填充上次调用 "begin_fill()" 之后绘制的形状。

   自相交多边形或多个形状间的重叠区域是否填充取决于操作系统的图形引擎
   、重叠的类型以及重叠的层数。 例如上面的 Turtle 多芒星可能会全部填充
   为黄色，也可能会有一些白色区域。

      >>> turtle.color("black", "red")
      >>> turtle.begin_fill()
      >>> turtle.circle(80)
      >>> turtle.end_fill()


更多绘图控制
""""""""""""

turtle.reset()

   Delete the turtle's drawings and re-center the turtle. The turtle's
   settings are restored to their default values.

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

   Delete the turtle's drawings from the screen. The state and
   position of the turtle as well as the drawings of other turtles are
   not affected.

turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal'))

   参数:
      * **arg** -- 要书写到 TurtleScreen 的对象

      * **move** -- True/False

      * **align** -- 字符串 "left", "center" 或 "right"

      * **font** -- 一个三元组 (fontname, fontsize, fonttype)

   基于 *align* ("left", "center" 或 "right") 并使用给定的字体将文本
   —— *arg* 的字符串表示形式 —— 写到当前海龟位置。 如果 *move* 为真值
   ，画笔会移至文本的右下角。 默认情况下 *move* 为 "False"。

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


海龟状态
~~~~~~~~


可见性
""""""

turtle.hideturtle()
turtle.ht()

   Make the turtle invisible. If the pen is down, movement still
   draws.

turtle.showturtle()
turtle.st()

   使海龟可见。

turtle.isvisible()

   Return "True" if the turtle is shown, "False" if it's hidden.

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


外观
""""

turtle.shape(name=None)

   参数:
      **name** -- 一个有效的形状名字符串

   设置海龟形状为 *name* 指定的形状名，如未指定形状名则返回当前的形状
   名。*name* 指定的形状名应存在于 TurtleScreen 的 shape 字典中。多边
   形的形状初始时有以下几种: "arrow", "turtle", "circle", "square",
   "triangle", "classic"。要了解如何处理形状请参看 Screen 方法
   "register_shape()"。

      >>> turtle.shape()
      'classic'
      >>> turtle.shape("turtle")
      >>> turtle.shape()
      'turtle'

turtle.resizemode(rmode=None)

   参数:
      **rmode** -- 字符串 "auto", "user", "noresize" 其中之一

   设置大小调整模式为以下值之一: "auto", "user", "noresize"。如未指定
   *rmode* 则返回当前的大小调整模式。不同的大小调整模式的效果如下:

   * "auto": 根据画笔粗细值调整海龟的外观。

   * "user": 根据拉伸因子和轮廓宽度 (outline) 值调整海龟的外观，两者是
     由 "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** -- 正数值

      * **stretch_len** -- 正数值

      * **outline** -- 正数值

   返回或设置画笔的属性 x/y 拉伸因子和/或轮廓。 设置大小调整模式为
   "user"。 当且仅当大小调整模式为 "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** -- 数值 (可选)

   设置或返回当前的剪切因子。根据 shear 指定的剪切因子即剪切角度的切线
   来剪切海龟形状。*不* 改变海龟的朝向 (移动方向)。如未指定 shear 参数
   : 返回当前的剪切因子即剪切角度的切线，与海龟朝向平行的线条将被剪切
   。

      >>> 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.tiltangle(angle=None)

   参数:
      **angle** -- 一个数值 (可选)

   设置或返回当前的倾角。如果指定 angle 则旋转海龟形状使其指向 angle
   指定的方向，忽略其当前的倾角。*不* 改变海龟的朝向 (移动方向)。如果
   未指定 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** -- 一个数值 (可选)

      * **t12** -- 一个数值 (可选)

      * **t21** -- 一个数值 (可选)

      * **t12** -- 一个数值 (可选)

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

   如未指定任何矩阵元素，则返回以 4 元素元组表示的变形矩阵。 否则就根
   据设置指定元素的矩阵来改变海龟形状，矩阵第一排的值为 t11, t12 而第
   二排的值为 t21, t22。 行列式 t11 * t22 - t12 * t21 必须不为零，否则
   会引发错误。 根据指定矩阵修改拉伸因子 stretchfactor, 剪切因子
   shearfactor 和倾角 tiltangle。

      >>> 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** -- a function with two arguments or "None"

      * **btn** -- an integer

      * **add** -- a boolean or "None"

   Bind *fun* to mouse-click events on this turtle. *fun* is called
   with the coordinates of the clicked point on the canvas. If *fun*
   is "None", existing bindings are removed. *btn* is the number of
   the mouse button and defaults to 1, the left mouse button. If *add*
   is "True", a new binding is added, otherwise it replaces a former
   binding. Example for the anonymous turtle, that is, the procedural
   way:

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

   记录在 "with turtle.poly():" 块中绘制的多边形的顶点。 第一个和最后
   一个顶点将被连接。

      >>> with turtle.poly():
      ...     turtle.forward(100)
      ...     turtle.right(60)
      ...     turtle.forward(100)

   Added in version 3.14.

turtle.begin_poly()

   Start recording the vertices of a polygon. The current turtle
   position is the first vertex of the polygon.

turtle.end_poly()

   Stop recording the vertices of a polygon. The current turtle
   position is the last vertex of the polygon. This will be connected
   with the first vertex.

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

   返回海龟对象自身。唯一合理的用法: 作为一个函数来返回 "匿名海龟":

      >>> 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()" 方法/函数撤销海龟动作的最
   大次数。  如果 *size* 为 "None"，则禁用撤销缓冲区。

      >>> turtle.setundobuffer(42)

turtle.undobufferentries()

   返回撤销缓冲区里的条目数。

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


复合形状
~~~~~~~~

要使用由多个不同颜色多边形构成的复合海龟形状，你必须明确地使用辅助类
"Shape"，具体步骤如下:

1. 创建一个空 Shape 对象，类型为 "compound"。

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 对象的形状列表并使用它:

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

备注:

  "Shape" 类在 "register_shape()" 方法的内部以多种方式使用。应用程序编
  写者 *只有* 在使用上述的复合形状时才需要处理 Shape 类。


Screen methods and functions
----------------------------

本节中的大部分示例都使用 TurtleScreen 类的一个实例，命名为 "screen"。


窗口控制
~~~~~~~~

turtle.bgcolor()
turtle.bgcolor(color, /)
turtle.bgcolor(r, g, b, /)

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

   允许以下四种输入格式:

   "bgcolor()"
      Return the current background color as a color specification
      string or as a tuple (see example).  May be used as input to
      another "color()", "pencolor()", "fillcolor()" or "bgcolor()"
      call.

   "bgcolor(colorstring)"
      设置背景颜色为 *colorstring*，使用 Tk 颜色描述字符串形式，如
      ""red"", ""yellow"" 或 ""#33cc8c""。

   "bgcolor((r, g, b))"
      Set the background color to the RGB color represented by the
      tuple of *r*, *g*, and *b*. Each of *r*, *g*, and *b* must be
      between 0 and colormode, where colormode is either 1.0 or 255
      (see "colormode()").

   "bgcolor(r, g, b)"
      Set the background color to the RGB color represented by *r*,
      *g*, and *b*. Each of *r*, *g*, and *b* must be between 0 and
      colormode.

      >>> screen.bgcolor("orange")
      >>> screen.bgcolor()
      'orange'
      >>> screen.bgcolor("#800080")
      >>> screen.bgcolor()
      (128.0, 0.0, 128.0)

turtle.bgpic(picname=None)

   参数:
      **picname** -- 字符串，图像文件的名称（PNG、 GIF、 PGM 和 PPM）
      或 ""nopic"" 或 "None"

   设置背景图片或返回当前背景图片名称。如果 *picname* 为一个文件名，则
   将相应图片设为背景。如果 *picname* 为 ""nopic""，则删除当前背景图片
   。如果 *picname* 为 "None"，则返回当前背景图片文件名。:

      >>> 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** -- 正整型数，以像素表示画布的新宽度值

      * **canvheight** -- 正整型数，以像素表示画布的新高度值

      * **bg** -- 颜色字符串或颜色元组，新的背景颜色

   如未指定任何参数，则返回当前的 (canvaswidth, canvasheight)。否则改
   变作为海龟绘图场所的画布大小。不改变绘图窗口。要观察画布的隐藏区域
   ，可以使用滚动条。通过此方法可以令之前绘制于画布之外的图形变为可见
   。

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

   也可以用来寻找意外逃走的海龟 ;-)

turtle.setworldcoordinates(llx, lly, urx, ury)

   参数:
      * **llx** -- 一个数值

      * **lly** -- 一个数值

      * **urx** -- 一个数值

      * **ury** -- 一个数值

   Set up a user-defined coordinate system. *llx* and *lly* are the x
   and y coordinates of the lower left corner of the canvas. *urx* and
   *ury* are the x and y coordinates of the upper right corner. Switch
   to mode "world" if necessary, which performs a reset. If mode
   "world" is already active, all drawings are redrawn according to
   the new coordinates. In user-defined coordinate systems, angles may
   appear distorted, see "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()

   Temporarily turn off turtle animation. The code inside the "with"
   block is not animated. Once the block is exited, the drawing
   appears. This is useful for drawing complex shapes where even the
   fastest speed setting is too slow.

      >>> with screen.no_animation():
      ...     for dist in range(2, 400, 2):
      ...         fd(dist)
      ...         rt(90)

   Added in version 3.14.

turtle.delay(delay=None)

   参数:
      **delay** -- 一个非负整数或 "None"

   Return or set the drawing delay in milliseconds. This is
   approximately the time interval between two consecutive canvas
   updates. The longer the drawing delay, the slower the animation.

      >>> screen.delay()
      10
      >>> screen.delay(5)
      >>> screen.delay()
      5

turtle.tracer(n=None, delay=None)

   参数:
      * **n** -- 一个非负整数或 "None"

      * **delay** -- 一个非负整数或 "None"

   Turn turtle animation on or off and set the drawing delay. If *n*
   is given, only every n-th regular screen update is performed, which
   can be used to speed up the drawing of complex graphics. If *n* is
   0, animation is turned off and the screen is only updated by
   calling "update()". If *delay* is given, it sets the drawing delay,
   see "delay()". When called without arguments, return the current
   value of *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)

   设置焦点到 TurtleScreen (以便接收按键事件)。使用两个 Dummy 参数以便
   能够传递 "listen()" 给 onclick 方法。

turtle.onkey(fun, key)
turtle.onkeyrelease(fun, key)

   参数:
      * **fun** -- 一个无参数的函数或 "None"

      * **key** -- 一个字符串: 键 (例如 "a") 或键标 (例如 "space")

   绑定 *fun* 指定的函数到按键释放事件。如果 *fun* 值为 "None"，则移除
   事件绑定。注: 为了能够注册按键事件，TurtleScreen 必须得到焦点。(参
   见 "listen()" 方法。)

      >>> def f():
      ...     fd(50)
      ...     lt(60)
      ...
      >>> screen.onkey(f, "Up")
      >>> screen.listen()

turtle.onkeypress(fun, key=None)

   参数:
      * **fun** -- 一个无参数的函数或 "None"

      * **key** -- 一个字符串: 键 (例如 "a") 或键标 (例如 "space")

   绑定 *fun* 指定的函数到指定键的按下事件。如未指定键则绑定到任意键的
   按下事件。注: 为了能够注册按键事件，必须得到焦点。(参见 "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** -- a function with two arguments or "None"

      * **btn** -- an integer

      * **add** -- a boolean or "None"

   Bind *fun* to mouse-click events on this screen. *fun* is called
   with the coordinates of the clicked point on the canvas. If *fun*
   is "None", existing bindings are removed. *btn* is the number of
   the mouse button and defaults to 1, the left mouse button. If *add*
   is "True", a new binding is added, otherwise it replaces a former
   binding.

   以下示例使用一个 TurtleScreen 实例 "screen" 和一个 Turtle 实例
   "turtle":

      >>> screen.onclick(turtle.goto) # 后续对 TurtleScreen 的点击
      >>>                             # 将使海龟移至被点击的位置。
      >>> screen.onclick(None)        # 再次移除事件绑定

   备注:

     此 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()   ### 让海龟随意前进
      >>> running = False

turtle.mainloop()
turtle.done()

   Start the event loop by calling Tkinter's "mainloop()" method. Must
   be the last statement in a turtle graphics program. Must *not* be
   used if a script is run from within IDLE in -n mode (see 在没有子进
   程的情况下运行).


输入方法
~~~~~~~~

turtle.textinput(title, prompt)

   参数:
      * **title** -- 字符串

      * **prompt** -- 字符串

   Pop up a dialog window for input of a string. *title* is the title
   of the dialog window and *prompt* is a text describing what
   information to input. Return the string entered. If the dialog is
   canceled, return "None".

      >>> screen.textinput("NIM", "Name of first player:")

turtle.numinput(title, prompt, default=None, minval=None, maxval=None)

   参数:
      * **title** -- 字符串

      * **prompt** -- 字符串

      * **default** -- 一个数值或 "None"

      * **minval** -- 一个数值或 "None"

      * **maxval** -- 一个数值或 "None"

   Pop up a dialog window for input of a number. *title* is the title
   of the dialog window and *prompt* is a text describing what
   numerical information to input. *default* is the default value,
   *minval* and *maxval* are the minimum and maximum values for input.
   If these are given, the number entered must be between *minval* and
   *maxval*. If not, a hint is issued and the dialog remains open for
   correction. Return the number entered. If the dialog is canceled,
   return "None".

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


设置与特殊方法
~~~~~~~~~~~~~~

turtle.mode(mode=None)

   参数:
      **mode** -- 一个字符串或 "None"

   Set the turtle mode and perform a reset. *mode* is one of the
   strings "standard", "logo" or "world". If *mode* is not given,
   return the current mode.

   Mode "standard" is compatible with the old "turtle" module. Mode
   "logo" is compatible with most Logo turtle graphics. Mode "world"
   uses user-defined world coordinates, see "setworldcoordinates()".
   In this mode, angles appear distorted if the x and y units are not
   of equal length.

   +--------------+---------------------------+---------------------+
   | 模式         | 初始海龟朝向              | 正数角度            |
   |==============|===========================|=====================|
   | "standard"   | 朝右 (东)                 | 逆时针              |
   +--------------+---------------------------+---------------------+
   | "logo"       | 朝上 (北)                 | 顺时针              |
   +--------------+---------------------------+---------------------+

      >>> mode("logo")  # resets turtle heading to north
      >>> mode()
      'logo'

turtle.colormode(cmode=None)

   参数:
      **cmode** -- 一个数值或 "None"

   Return the colormode or set it to 1.0 or 255. After setting it, the
   *r*, *g* and *b* values of color triples have to be between 0 and
   *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** -- a string, a tuple of pairs of numbers, a "Shape"
        object or "None"

   Add a turtle shape to the TurtleScreen's shape list. It can be
   called in four different ways:

   1. *name* 为一个图像文件（PNG、 GIF、 PGM和PPM）的文件名， *shape*
      为 "None": 安装相应的图像形状。:

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

   2. *name* 为任意字符串， *shape* 为图像文件（PNG、 GIF、 PGM和PPM）
      的名称：安装相应的图像形状。:

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

   3. *name* 为指定的字符串，*shape* 为由坐标值对构成的元组: 安装相应
      的多边形形状。

         >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))

   4. *name* 为任意字符串而 *shape* 为 (复合) "Shape" 对象：安装相应的
      复合形状。

   Image shapes do not rotate when turning the turtle, so they do not
   display the heading of the turtle. To use a registered shape, call
   "shape()" with its name.

   在 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-only methods
~~~~~~~~~~~~~~~~~~~

turtle.bye()

   Close the turtle graphics window.

turtle.exitonclick()

   将 "bye()" 方法绑定到 Screen 上的鼠标点击事件。

   如果配置字典中 "using_IDLE" 的值为 "False" (默认值) 则同时进入主事
   件循环。注: 如果启动 IDLE 时使用了 "-n" 开关 (无子进程)，
   "turtle.cfg" 中此数值应设为 "True"。在此情况下 IDLE 本身的主事件循
   环同样会作用于客户脚本。

turtle.save(filename, overwrite=False)

   将当前海龟绘图（和海龟）另存为PostScript文件。

   参数:
      * **filename** -- 保存PostScript文件的路径

      * **overwrite** -- 如果为 "False" 并且已经存在具有给定文件名的文
        件，则该函数将引发 "FileExistsError"。 如果为 "True"，文件将被
        覆盖。

      >>> screen.save("my_drawing.ps")
      >>> screen.save("my_drawing.ps", overwrite=True)

   Added in version 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** -- 字符串

   Set the title of the turtle window to *titlestring*. The title is
   shown in the title bar of the turtle graphics window.

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


公共类
------

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

   参数:
      **canvas** -- 一个 "tkinter.Canvas", "ScrolledCanvas" 或
      "TurtleScreen"

   创建一个海龟。海龟对象具有 "Turtle/RawTurtle 方法" 一节所述的全部方
   法。

class turtle.Turtle

   RawTurtle 的子类，具有相同的接口，但其绘图场所为默认的 "Screen" 类
   对象，在首次使用时自动创建。

class turtle.TurtleScreen(cv)

   参数:
      **cv** -- 一个 "tkinter.Canvas"

   提供面向屏幕的方法如 "bgcolor()" 等。 说明见上文。

class turtle.Screen

   Subclass of "TurtleScreen", with four methods added. Calling
   "Screen()" returns the single screen object. If it does not exist
   yet, it is created. Otherwise the existing one is returned.

class turtle.ScrolledCanvas(master)

   参数:
      **master** -- 可容纳 ScrolledCanvas 的 Tkinter 部件，即添加了滚
      动条的 Tkinter-canvas

   由 Screen 类使用，使其能够自动提供一个 ScrolledCanvas 作为海龟的绘
   图场所。

class turtle.Shape(type_, data)

   参数:
      * **type_** -- 字符串

      * **data** -- depends on *type_*

   Data structure modeling shapes. *type_* is one of the strings
   "polygon", "image" or "compound". What *data* must be depends on
   *type_*: for "polygon" a tuple of pairs of coordinates, for "image"
   an image (only used internally), and for "compound" "None", as a
   compound shape is built up using the "addcomponent()" method.

   addcomponent(poly, fill, outline=None)

      参数:
         * **poly** -- a tuple of pairs of numbers

         * **fill** -- a color

         * **outline** -- a color or "None"

      Add a component to a shape of type "compound". *poly* is a
      polygon, a tuple of pairs of numbers. *fill* is the color the
      polygon is filled with and *outline* is the color of its
      outline. If *outline* is not given, *fill* is used for it as
      well.

      示例:

         >>> 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)" 旋转


异常
----

The "turtle" module defines the following exception:

exception turtle.TurtleGraphicsError

   Raised for invalid arguments or operations. For example, a
   malformed color string:

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


使用 "turtle" 模块命名空间
--------------------------

使用 "from turtle import *" 是很方便 —— 但要注意它导入的对象集相当大，
如果你还在做海龟绘图以外的事情就有发生名称冲突的风险（如果你在可能导入
了其他模块的脚本中使用海龟绘图则可能会遇到更大的问题）。

解决办法是使用 "import turtle" —— "fd()" 将变成 "turtle.fd()"，
"width()" 将变成 "turtle.width()" 等等。 （如果反复输入“turtle”太过烦
琐，还可改成 "import turtle as t" 等。）


在脚本中使用海龟绘图
--------------------

建议使用上文所述的 "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" 对象）的方法。 你
*可以* 在 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")


如何使用帮助
------------

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"。该文件可作为模板用来将文档字符
   串翻译为不同语言。

If you (or your students) want to use "turtle" with online help in
your native language, you have to translate the docstrings and save
the resulting file as e.g. "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"。

* If you set e.g. "language = italian" the docstringdict
  "turtle_docstringdict_italian.py" will be loaded at import time (if
  present on the import path, e.g. in the same directory as "turtle").

* *exampleturtle* 和 *examplescreen* 条目定义了相应对象在文档字符串中
  显示的名称。方法文档字符串转换为函数文档字符串时将从文档字符串中删去
  这些名称。

* *using_IDLE*: 如果你经常使用 IDLE 及其 "-n" 开关选项（"无子进程"）则
  将此项设为 "True"。 这将阻止 "exitonclick()" 进入主事件循环。

There can be a "turtle.cfg" file in the directory where "turtle" is
stored and an additional one in the current working directory.  The
latter will override the settings of the first one.

"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" --- Demo scripts
=============================

The "turtledemo" package includes a set of demo scripts.  These
scripts can be run and viewed using the supplied demo viewer as
follows:

   python -m turtledemo

此外，你也可以单独运行其中的演示脚本。例如，:

   python -m turtledemo.bytedesign

"turtledemo" 包目录中包含：

* 一个演示查看器 "__main__.py"，可用来查看脚本的源码并即时运行。

* 演示 "turtle" 模块的不同特性的多个脚本。 所有示例可通过 Examples 菜
  单打开。 它们也可以独立运行。

* 一个 "turtle.cfg" 文件，作为说明如何编写并使用模块配置文件的示例模板
  。

演示脚本清单如下:

+--------------------------+--------------------------------+----------------------------------------+
| 名称                     | 描述                           | 相关特性                               |
|==========================|================================|========================================|
| "bytedesign"             | 复杂的传统海龟绘图模式         | "tracer()", "delay()", "update()"      |
+--------------------------+--------------------------------+----------------------------------------+
| "chaos"                  | 绘制 Verhulst 动态模型，演示通 | 世界坐标系                             |
|                          | 过计算机的运算可能会生成令人惊 |                                        |
|                          | 叹的结果                       |                                        |
+--------------------------+--------------------------------+----------------------------------------+
| "clock"                  | 绘制模拟时钟显示本机的当前时间 | 海龟作为表针, "ontimer()"              |
+--------------------------+--------------------------------+----------------------------------------+
| "colormixer"             | 试验 r, g, b 颜色模式          | "ondrag()" 当鼠标拖动                  |
+--------------------------+--------------------------------+----------------------------------------+
| "forest"                 | 绘制 3 棵广度优先树            | 随机化                                 |
+--------------------------+--------------------------------+----------------------------------------+
| "fractalcurves"          | 绘制 Hilbert & Koch 曲线       | 递归                                   |
+--------------------------+--------------------------------+----------------------------------------+
| "lindenmayer"            | 文化数学 (印度装饰艺术)        | L-系统                                 |
+--------------------------+--------------------------------+----------------------------------------+
| "minimal_hanoi"          | 汉诺塔                         | 矩形海龟作为汉诺盘 ("shape()",         |
|                          |                                | "shapesize()")                         |
+--------------------------+--------------------------------+----------------------------------------+
| "nim"                    | 玩经典的“尼姆”游戏，开始时有三 | 海龟作为小棒，事件驱动 (鼠标, 键盘)    |
|                          | 堆小棒，与电脑对战。           |                                        |
+--------------------------+--------------------------------+----------------------------------------+
| "paint"                  | 超极简主义绘画程序             | "onclick()" 当鼠标点击                 |
+--------------------------+--------------------------------+----------------------------------------+
| "peace"                  | 初级技巧                       | 海龟: 外观与动画                       |
+--------------------------+--------------------------------+----------------------------------------+
| "penrose"                | 非周期性地使用风筝和飞镖形状铺 | "stamp()" 印章                         |
|                          | 满平面                         |                                        |
+--------------------------+--------------------------------+----------------------------------------+
| "planet_and_moon"        | 模拟引力系统                   | 复合形状, "Vec2D" 类                   |
+--------------------------+--------------------------------+----------------------------------------+
| "rosette"                | 一个来自介绍海龟绘图的维基百科 | "clone()", "undo()"                    |
|                          | 文章的图案                     |                                        |
+--------------------------+--------------------------------+----------------------------------------+
| "round_dance"            | 两两相对并不断旋转舞蹈的海龟   | 复合形状, "clone()" "shapesize()",     |
|                          |                                | "tilt()", "get_shapepoly()",           |
|                          |                                | "update()"                             |
+--------------------------+--------------------------------+----------------------------------------+
| "sorting_animate"        | 动态演示不同的排序方法         | 简单对齐, 随机化                       |
+--------------------------+--------------------------------+----------------------------------------+
| "tree"                   | 一棵 (图形化的) 广度优先树 (使 | "clone()" 克隆                         |
|                          | 用生成器)                      |                                        |
+--------------------------+--------------------------------+----------------------------------------+
| "two_canvases"           | 简单设计                       | 两块画布上的海龟                       |
+--------------------------+--------------------------------+----------------------------------------+
| "yinyang"                | 另一个初级示例                 | "circle()" 画圆                        |
+--------------------------+--------------------------------+----------------------------------------+

祝你玩得开心！
