turtleTurtle graphics海龟图形

Source code: Lib/turtle.py


Introduction介绍

Turtle graphics is a popular way for introducing programming to kids. 海龟图形是向孩子们介绍编程的一种流行方式。It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.它是Wally Feurzeig、Seymour Papert和Cynthia Solomon于1967年开发的原始徽标编程语言的一部分。

Imagine a robotic turtle starting at (0, 0) in the x-y plane. 想象一只机器人龟在x-y平面上从(0, 0)开始。After an import turtle, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. import turtle后,给它一个turtle.forward(15)命令,它就会(在屏幕上!)在其面对的方向上移动15个像素,在其移动时绘制一条线。Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise.将命令turtle.right(25)赋予它,它将顺时针旋转25度。

By combining together these and similar commands, intricate shapes and pictures can easily be drawn.通过将这些命令和类似命令组合在一起,可以轻松绘制复杂的形状和图片。

The turtle module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5.turtle模块是从Python标准发行版到Python 2.5版本的同名模块的扩展重新实现。

It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. 它试图保持旧turtle模块的优点,并与之(几乎)100%兼容。This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch.这首先意味着,当使用-n开关在空闲运行中使用模块时,使学习程序员能够交互式地使用所有命令、类和方法。

The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. turtle模块以面向对象和面向过程的方式提供turtle图形原语。Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.因为它使用tkinter作为底层图形,所以需要安装一个支持Tk的Python版本。

The object-oriented interface uses essentially two+two classes:面向对象接口基本上使用两个+两个类:

  1. The TurtleScreen class defines graphics windows as a playground for the drawing turtles. TurtleScreen类将图形窗口定义为绘制海龟的游乐场。Its constructor needs a tkinter.Canvas or a ScrolledCanvas as argument. 它的构造函数需要tkinter.CanvasScrolledCanvas作为参数。It should be used when turtle is used as part of some application.turtle被用作某些应用程序的一部分时,应该使用它。

    The function Screen() returns a singleton object of a TurtleScreen subclass. 函数Screen()返回TurtleScreen子类的singleton对象。This function should be used when turtle is used as a standalone tool for doing graphics. turtle作为独立的图形工具使用时,应该使用此功能。As a singleton object, inheriting from its class is not possible.作为单例对象,无法从其类继承。

    All methods of TurtleScreen/Screen also exist as functions, i.e. as part of the procedure-oriented interface.TurtleScreen/Screen的所有方法也作为功能存在,即作为面向过程的界面的一部分。

  2. RawTurtle (alias: RawPen) defines Turtle objects which draw on a TurtleScreen. (别名:RawPen)定义在TurtleScreen上绘制的Turtle对象。Its constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle objects know where to draw.它的构造函数需要一个CanvasScrolledCanvasTurtleScreen作为参数,以便RawTurtle对象知道在哪里绘制。

    Derived from RawTurtle is the subclass Turtle (alias: Pen), which draws on “the” Screen instance which is automatically created, if not already present.派生自RawTurtle的子类Turtle(别名:Pen),它在自动创建的“the”Screen实例上绘制,如果尚未出现的话。

    All methods of RawTurtle/Turtle also exist as functions, i.e. part of the procedure-oriented interface.RawTurtle/Turtle的所有方法也作为函数存在,即面向过程的接口的一部分。

The procedural interface provides functions which are derived from the methods of the classes Screen and Turtle. 过程接口提供了从ScreenTurtle类的方法派生的函数。They have the same names as the corresponding methods. 它们与相应的方法具有相同的名称。A screen object is automatically created whenever a function derived from a Screen method is called. 每当调用从screen方法派生的函数时,都会自动创建screen对象。An (unnamed) turtle object is automatically created whenever any of the functions derived from a Turtle method is called.每当调用从turtle方法派生的任何函数时,都会自动创建一个(未命名的)turtle对象。

To use multiple turtles on a screen one has to use the object-oriented interface.要在屏幕上使用多个海龟,必须使用面向对象的界面。

Note

In the following documentation the argument list for functions is given. 以下文档中给出了函数的参数列表。Methods, of course, have the additional first argument self which is omitted here.当然,方法有额外的第一个参数self,这里省略了它。

Overview of available Turtle and Screen methods可用TurtleScreen方法概述

Turtle methodsTurtle方法

Turtle motionTurtle运动
Move and draw移动和绘制
Tell Turtle’s state告诉Turtle的状态
Setting and measurement设置和测量
Pen control笔控件
Drawing state图纸状态
Color control颜色控件
Filling填满
More drawing control更多绘图控件
Turtle stateTurtle状态
Visibility可见性
Appearance外观
Using events使用事件
Special Turtle methods特殊Turtle方法

Methods of TurtleScreen/ScreenTurtleScreen/Screen的方法

Window control窗口控件
Animation control动画控件
Using screen events使用屏幕事件
Settings and special methods设置和特殊方法
Input methods输入方法
Methods specific to Screen专用于Screen的方法

Methods of RawTurtle/Turtle and corresponding functionsRawTurtle/Turtle方法及其函数

Most of the examples in this section refer to a Turtle instance called turtle.本节中的大多数示例都引用了一个名为Turtle的Turtle实例。

Turtle motionTurtle运动

turtle.forward(distance)
turtle.fd(distance)
Parameters参数

distancea number (integer or float)数字(整数或浮点)

Move the turtle forward by the specified distance, in the direction the turtle is headed.将海龟向前移动指定距离,朝海龟前进的方向移动。

>>> 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)
Parameters参数

distancea number一个数字

Move the turtle backward by distance, opposite to the direction the turtle is headed. 将海龟向后移动距离,与海龟的头部方向相反。Do not change the turtle’s heading.不要改变海龟的方向。

>>> turtle.position()
(0.00,0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00,0.00)
turtle.right(angle)
turtle.rt(angle)
Parameters参数

anglea number (integer or float)数字(整数或浮点)

Turn turtle right by angle units. angle单位向右旋转海龟。(Units are by default degrees, but can be set via the degrees() and radians() functions.) (单位默认为度,但可以通过degrees()radians()函数进行设置。)Angle orientation depends on the turtle mode, see mode().角度方向取决于海龟模式,请参阅mode()

>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0
turtle.left(angle)
turtle.lt(angle)
Parameters参数

anglea number (integer or float)数字(整数或浮点)

Turn turtle left by angle units. angle单位向左旋转海龟。(Units are by default degrees, but can be set via the degrees() and radians() functions.) (单位默认为度,但可以通过degrees()radians()函数进行设置。)Angle orientation depends on the turtle mode, see mode().角度方向取决于海龟模式,请参阅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)
Parameters参数
  • xa number or a pair/vector of numbers数字或数字对/数字向量

  • ya number or None数字或None

If y is None, x must be a pair of coordinates or a Vec2D (e.g. as returned by pos()).如果yNone,则x必须是一对坐标或一个Vec2D(例如,由pos()返回)。

Move turtle to an absolute position. 将乌龟移动到绝对位置。If the pen is down, draw line. 如果笔放下,画线。Do not change the turtle’s orientation.不要改变海龟的方向。

 >>> 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)
Parameters参数

xa number (integer or float)数字(整数或浮点)

Set the turtle’s first coordinate to x, leave second coordinate unchanged.将海龟的第一个坐标设置为x,第二个坐标保持不变。

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

ya number (integer or float)数字(整数或浮点)

Set the turtle’s second coordinate to y, leave first coordinate unchanged.将海龟的第二个坐标设置为y,保持第一个坐标不变。

>>> turtle.position()
(0.00,40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00,-10.00)
turtle.setheading(to_angle)
turtle.seth(to_angle)
Parameters参数

to_anglea number (integer or float)数字(整数或浮点)

Set the orientation of the turtle to to_angle. 将海龟的方向设置为to_angleHere are some common directions in degrees:以下是一些常用的度数方向:

standard mode标准模式

logo mode徽标模式

0 - east

0 - north

90 - north

90 - east

180 - west

180 - south

270 - south

270 - west

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

Move turtle to the origin – coordinates (0,0) – and set its heading to its start-orientation (which depends on the mode, see mode()).将海龟移动到原点坐标(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)
Parameters参数
  • radiusa number一个数字

  • extenta number (or None)数字(或None

  • stepsan integer (or None)整数(或None

Draw a circle with given radius. 画一个radius给定的圆。The center is radius units left of the turtle; extent – an angle – determines which part of the circle is drawn. 中心是海龟左侧的radius单位;extent-角度-确定绘制圆的哪个部分。If extent is not given, draw the entire circle. 如果未给出extent,则绘制整个圆。If extent is not a full circle, one endpoint of the arc is the current pen position. 如果extent不是一个整圆,则圆弧的一个端点是当前笔的位置。Draw the arc in counterclockwise direction if radius is positive, otherwise in clockwise direction. 如果radius为正,则按逆时针方向绘制圆弧,否则按顺时针方向绘制。Finally the direction of the turtle is changed by the amount of extent.最后,海龟的方向会随着extent的大小而改变。

As the circle is approximated by an inscribed regular polygon, steps determines the number of steps to use. 由于圆由内接正多边形近似,因此steps决定要使用的步长。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) # draw a semicircle
>>> turtle.position()
(0.00,240.00)
>>> turtle.heading()
180.0
turtle.dot(size=None, *color)
Parameters参数
  • size – an integer >= 1 (if given)

  • colora colorstring or a numeric color tuple颜色字符串或数字颜色元组

Draw a circular dot with diameter size, using color. 使用color绘制直径size为的圆点。If size is not given, the maximum of pensize+4 and 2*pensize is used.如果未给出尺寸,则使用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 a copy of the turtle shape onto the canvas at the current turtle position. 在当前海龟位置的画布上加盖海龟形状的副本。Return a stamp_id for that stamp, which can be used to delete it by calling clearstamp(stamp_id).返回该戳记的stamp_id,可通过调用clearstamp(stamp_id)将其删除。

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

stampidan integer, must be return value of previous stamp() call整数,必须是上一个stamp()调用的返回值

Delete stamp with given stampid.删除具有给定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)
Parameters参数

nan integer (or None)整数(或None

Delete all or first/last n of turtle’s stamps. 删除所有或第一/最后n个海龟邮票。If n is None, delete all stamps, if n > 0 delete first n stamps, else if n < 0 delete last n stamps.如果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()

Undo (repeatedly) the last turtle action(s). 撤消(重复)最后一个海龟操作。Number of available undo actions is determined by the size of the undobuffer.可用撤消操作的数量由undobuffer的大小决定。

>>> for i in range(4):
... turtle.fd(50); turtle.lt(80)
...
>>> for i in range(8):
... turtle.undo()
turtle.speed(speed=None)
Parameters参数

speedan integer in the range 0..10 or a speedstring (see below)范围为0..10的整数或speedstring(见下文)

Set the turtle’s speed to an integer value in the range 0..10. 将海龟的速度设置为0..10范围内的整数值。If no argument is given, return current speed.如果未给出参数,则返回当前速度。

If input is a number greater than 10 or smaller than 0.5, speed is set to 0. 如果输入值大于10或小于0.5,则速度设置为0。Speedstrings are mapped to speedvalues as follows:SpeedString映射到SpeedValue,如下所示:

  • “fastest”: 0

  • “fast”: 10

  • “normal”: 6

  • “slow”: 3

  • “slowest”: 1

Speeds from 1 to 10 enforce increasingly faster animation of line drawing and turtle turning.从1到10的速度使线条绘制和海龟转弯的动画速度越来越快。

Attention: speed = 0 means that no animation takes place. 注意:speed=0表示没有动画发生。forward/back makes turtle jump and likewise left/right make the turtle turn instantly.向前/向后使海龟跳跃,同样地向左/向右使海龟立即转身。

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

Tell Turtle’s state告诉乌龟的状态

turtle.position()
turtle.pos()

Return the turtle’s current location (x,y) (as a Vec2D vector).返回海龟的当前位置(x,y)(作为Vec2D向量)。

>>> turtle.pos()
(440.00,-0.00)
turtle.towards(x, y=None)
Parameters参数
  • xa number or a pair/vector of numbers or a turtle instance数字或数字对/向量或海龟实例

  • ya number if x is a number, else None如果x是数字,则为数字,否则为None

Return the angle between the line from turtle position to position specified by (x,y), the vector or the other turtle. 返回从海龟位置到(x,y)、向量或其他海龟指定位置的直线之间的角度。This depends on the turtle’s start orientation which depends on the mode - “standard”/”world” or “logo”.这取决于海龟的起始方向,该方向取决于模式-“标准”/“世界”或“徽标”。

>>> turtle.goto(10, 10)
>>> turtle.towards(0,0)
225.0
turtle.xcor()

Return the turtle’s x coordinate.返回海龟的x坐标。

>>> turtle.home()
>>> turtle.left(50)
>>> turtle.forward(100)
>>> turtle.pos()
(64.28,76.60)
>>> print(round(turtle.xcor(), 5))
64.27876
turtle.ycor()

Return the turtle’s y coordinate.返回海龟的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 (value depends on the turtle mode, see mode()).返回海龟的当前航向(值取决于海龟模式,请参阅mode())。

>>> turtle.home()
>>> turtle.left(67)
>>> turtle.heading()
67.0
turtle.distance(x, y=None)
Parameters参数
  • xa number or a pair/vector of numbers or a turtle instance数字或数字对/向量或海龟实例

  • ya number if x is a number, else None如果x是数字,则为数字,否则为None

Return the distance from the turtle to (x,y), the given vector, or the given other turtle, in turtle step units.使海龟返回到(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

Settings for measurement测量设置

turtle.degrees(fullcircle=360.0)
Parameters参数

fullcirclea number数字

Set angle measurement units, i.e. set number of “degrees” for a full circle. 设置角度测量单位,即设置整圈的“度数”。Default value is 360 degrees.默认值为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()

Set the angle measurement units to radians. 将角度测量单位设置为弧度。Equivalent to degrees(2*math.pi).相当于degrees(2*math.pi)

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

Pen control笔控件

Drawing state图纸状态

turtle.pendown()
turtle.pd()
turtle.down()

Pull the pen down – drawing when moving.移动时将笔向下拉-绘图。

turtle.penup()
turtle.pu()
turtle.up()

Pull the pen up – no drawing when moving.向上拉笔-移动时不要画图。

turtle.pensize(width=None)
turtle.width(width=None)
Parameters参数

width – a positive number

Set the line thickness to width or return it. 将线条粗细设置为width或将其返回。If resizemode is set to “auto” and turtleshape is a polygon, that polygon is drawn with the same line thickness. 如果resizemode设置为“自动”,并且turtleshape是多边形,则将使用相同的线宽绘制该多边形。If no argument is given, the current pensize is returned.如果没有给出参数,则返回当前养老金。

>>> turtle.pensize()
1
>>> turtle.pensize(10) # from here on lines of width 10 are drawn
turtle.pen(pen=None, **pendict)
Parameters参数
  • pena dictionary with some or all of the below listed keys包含以下部分或全部键的字典

  • pendictone or more keyword-arguments with the below listed keys as keywords一个或多个关键字参数,以下列关键字为关键字

Return or set the pen’s attributes in a “pen-dictionary” with the following key/value pairs:使用以下键/值对在“笔字典”中返回或设置笔的属性:

  • “shown”: True/False

  • “pendown”: True/False

  • “pencolor”: color-string or color-tuple颜色字符串或颜色元组

  • “fillcolor”: color-string or color-tuple颜色字符串或颜色元组

  • “pensize”: positive number正数,正数

  • “speed”: number in range 0..10范围0..10中的数字

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

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

  • “outline”: positive number正数,正数

  • “tilt”: number

This dictionary can be used as argument for a subsequent call to pen() to restore the former pen-state. 此字典可用作后续调用pen()的参数,以恢复以前的pen状态。Moreover one or more of these attributes can be provided as keyword-arguments. 此外,这些属性中的一个或多个可以作为关键字参数提供。This can be used to set several pen attributes in one statement.这可用于在一条语句中设置多个笔属性。

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

Return True if pen is down, False if it’s up.如果笔向下,则返回True;如果笔向上,则返回False

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

Color control颜色控件

turtle.pencolor(*args)

Return or set the pencolor.返回或设置铅笔颜色。

Four input formats are allowed:允许四种输入格式:

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 call.可以用作另一个color/pencolor/fillcolor调用的输入。

pencolor(colorstring)

Set pencolor to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#33cc8c".pencolor设置为colorstring,这是一个Tk颜色规范字符串,例如"red""yellow""#33cc8c"

pencolor((r, g, b))

Set pencolor to the RGB color represented by the tuple of r, g, and b. pencolor设置为由rgb的元组表示的RGB颜色。Each of r, g, and b must be in the range 0..colormode, where colormode is either 1.0 or 255 (see colormode()).rgb中的每一个都必须在0..colormode的范围内,其中colormode为1.0或255(请参见colormode())。

pencolor(r, g, b)

Set pencolor to the RGB color represented by r, g, and b. pencolor设置为由rgb表示的RGB颜色。Each of r, g, and b must be in the range 0..colormode.rgb中的每一个都必须在0..colormode范围内。

If turtleshape is a polygon, the outline of that polygon is drawn with the newly set pencolor.如果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)

Return or set the fillcolor.返回或设置fillcolor

Four input formats are allowed:允许四种输入格式:

fillcolor()

Return the current fillcolor as color specification string, possibly in tuple format (see example). 返回当前fillcolor作为颜色规范字符串,可能是元组格式(请参见示例)。May be used as input to another color/pencolor/fillcolor call.可以用作另一个color/pencolor/fillcolor调用的输入。

fillcolor(colorstring)

Set fillcolor to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#33cc8c".fillcolor设置为colorstring,这是一个Tk颜色规范字符串,例如"red""yellow""#33cc8c"

fillcolor((r, g, b))

Set fillcolor to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be in the range 0..colormode, where colormode is either 1.0 or 255 (see colormode()).fillcolor设置为由rgb的元组表示的RGB颜色。其中rgb的每个值都必须在0..colormode范围内,其中colormode为1.0或255(请参见colormode())。

fillcolor(r, g, b)

Set fillcolor to the RGB color represented by r, g, and b. fillcolor设置为由rgb表示的RGB颜色。Each of r, g, and b must be in the range 0..colormode.rgb中的每一个都必须在0..colormode范围内。

If turtleshape is a polygon, the interior of that polygon is drawn with the newly set fillcolor.如果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)

Return or set pencolor and fillcolor.返回或设置pencolor和fillcolor。

Several input formats are allowed. 允许多种输入格式。They use 0 to 3 arguments as follows:它们使用0到3个参数,如下所示:

color()

Return the current pencolor and the current fillcolor as a pair of color specification strings or tuples as returned by pencolor() and fillcolor().将当前pencolor和当前fillcolor作为一对颜色规范字符串或元组返回,由pencolor()fillcolor()返回。

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

Inputs as in pencolor(), set both, fillcolor and pencolor, to the given value.pencolor()中输入,将fillcolorpencolor都设置为给定值。

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

Equivalent to pencolor(colorstring1) and fillcolor(colorstring2) and analogously if the other input format is used.pencolor(colorstring1)fillcolor(colorstring2)等效,如果使用其他输入格式,则与之类似。

If turtleshape is a polygon, outline and interior of that polygon is drawn with the newly set colors.若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))

See also: Screen method colormode().另请参见:Screen方法colormode()

Filling填满

turtle.filling()

Return fillstate (True if filling, False else).返回fillstate(如果填充则为True,否则为False)。

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

To be called just before drawing a shape to be filled.在绘制要填充的形状之前调用。

turtle.end_fill()

Fill the shape drawn after the last call to begin_fill().填充上次调用begin_fill()后绘制的形状。

Whether or not overlap regions for self-intersecting polygons or multiple shapes are filled depends on the operating system graphics, type of overlap, and number of overlaps. 是否填充自交多边形或多个形状的重叠区域取决于操作系统图形、重叠类型和重叠数量。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()

More drawing control更多绘图控件

turtle.reset()

Delete the turtle’s drawings from the screen, re-center the turtle and set variables to the 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. 从屏幕中删除海龟的图形。Do not move turtle. State and position of the turtle as well as drawings of other turtles are not affected.不要移动乌龟。海龟的状态和位置以及其他海龟的图纸不受影响。

turtle.write(arg, move=False, align='left', font='Arial', 8, 'normal')
Parameters参数
  • argobject to be written to the TurtleScreen要写入TurtleScreen的对象

  • moveTrue/FalseTrue/False

  • alignone of the strings “left”, “center” or right”字符串"left""center""right"之一

  • fonta triple (fontname, fontsize, fonttype)三元组(fontnamefontsizefonttype

Write text - the string representation of arg - at the current turtle position according to align (“left”, “center” or “right”) and with the given font. 根据对齐("left""center""right")和给定字体,在当前乌龟位置写入文本(arg的字符串表示)。If move is true, the pen is moved to the bottom-right corner of the text. 如果movetrue,则笔将移动到文本的右下角。By default, move is False.默认情况下,moveFalse

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

Turtle stateTurtle状态

Visibility可见性

turtle.hideturtle()
turtle.ht()

Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing, because hiding the turtle speeds up the drawing observably.当你正在做一些复杂的绘图时,这样做是个好主意,因为隐藏海龟可以明显加快绘图速度。

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

Make the turtle visible.

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

Return True if the Turtle is shown, False if it’s hidden.如果显示海龟,则返回True;如果隐藏海龟,则返回False

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

Appearance

turtle.shape(name=None)
Parameters参数

namea string which is a valid shapename有效形状名称的字符串

Set turtle shape to shape with given name or, if name is not given, return name of current shape. 将turtle shape设置为具有给定name的形状,或者,如果未给定名称,则返回当前形状的名称。Shape with name must exist in the TurtleScreen’s shape dictionary. 具有name的形状必须存在于TurtleScreen的形状字典中。Initially there are the following polygon shapes: “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”. 最初有以下多边形形状:"arrow""turtle""circle""square""triangle""classic"To learn about how to deal with shapes see Screen method register_shape().要了解如何处理形状,请参阅Screen方法register_shape()

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

rmodeone of the strings “auto”, “user”, “noresize”字符串"auto""user""noresize"之一

Set resizemode to one of the values: “auto”, “user”, “noresize”. resizemode设置为以下值之一:"auto""user""noresize"If rmode is not given, return current resizemode. 如果未给定rmode,则返回当前resizemodeDifferent resizemodes have the following effects:不同的resizemode具有以下效果:

  • "auto": adapts the appearance of the turtle corresponding to the value of pensize.根据pensize的值调整海龟的外观。

  • "user": adapts the appearance of the turtle according to the values of stretchfactor and outlinewidth (outline), which are set by shapesize().根据shapesize()设置的shapesize()的值调整海龟的外观。

  • "noresize": no adaption of the turtle’s appearance takes place.海龟的外貌不会发生变化。

resizemode("user") is called by shapesize() when used with arguments.与参数一起使用时,由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)
Parameters参数
  • stretch_widpositive number正数,正数

  • stretch_lenpositive number正数,正数

  • outlinepositive number正数,正数

Return or set the pen’s attributes x/y-stretchfactors and/or outline. Set resizemode to “user”. 返回或设置画笔的属性x/y-stretchfactors和/或outline。将resizemode设置为“user”。If and only if resizemode is set to “user”, the turtle will be displayed stretched according to its stretchfactors: stretch_wid is stretchfactor perpendicular to its orientation, stretch_len is stretchfactor in direction of its orientation, outline determines the width of the shapes’s outline.如果且仅当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)
Parameters参数

sheara number (optional)数字(可选)

Set or return the current shearfactor. 设置或返回当前剪切因子。Shear the turtleshape according to the given shearfactor shear, which is the tangent of the shear angle. 根据给定的剪切系数剪切套头衫,即剪切角的切线。Do not change the turtle’s heading (direction of movement). 不要改变海龟的方向(移动方向)。If shear is not given: return the current shearfactor, i. e. the tangent of the shear angle, by which lines parallel to the heading of the turtle are sheared.如果未给出剪切:返回当前剪切因子,即剪切角的切线,通过该切线,平行于海龟头部的线被剪切。

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

anglea number数字

Rotate the turtleshape by angle from its current tilt-angle, but do not change the turtle’s heading (direction of movement).将海龟形状从当前倾斜角度旋转一个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)
Parameters参数

anglea number数字

Rotate the turtleshape to point in the direction specified by angle, regardless of its current tilt-angle. 旋转turtleshape,使其指向角度指定的方向,而不考虑其当前的倾斜角度。Do not change the turtle’s heading (direction of movement).不要改变海龟的方向(移动方向)。

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

Deprecated since version 3.1.自版本3.1以来已弃用。

turtle.tiltangle(angle=None)
Parameters参数

anglea number (optional)数字(可选)

Set or return the current tilt-angle. 设置或返回当前倾斜角度。If angle is given, rotate the turtleshape to point in the direction specified by angle, regardless of its current tilt-angle. 如果给定了角度,则将turtleshape旋转到角度指定的方向,而不考虑其当前的倾斜角度。Do not change the turtle’s heading (direction of movement). 不要改变海龟的方向(移动方向)。If angle is not given: return the current tilt-angle, i. e. the angle between the orientation of the turtleshape and the heading of the turtle (its direction of movement).如果没有给出角度:返回当前的倾斜角度,即龟形的方向和龟的头部(移动方向)之间的角度。

>>> 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)
Parameters参数
  • t11a number (optional)数字(可选)

  • t12a number (optional)数字(可选)

  • t21a number (optional)数字(可选)

  • t12a number (optional)数字(可选)

Set or return the current transformation matrix of the turtle shape.设置或返回海龟形状的当前变换矩阵。

If none of the matrix elements are given, return the transformation matrix as a tuple of 4 elements. 如果没有给出任何矩阵元素,则将转换矩阵作为4个元素的元组返回。Otherwise set the given elements and transform the turtleshape according to the matrix consisting of first row t11, t12 and second row t21, t22. 否则,设置给定元素并根据由第一行t11、t12和第二行t21、t22组成的矩阵变换turtleshapeThe determinant t11 * t22 - t12 * t21 must not be zero, otherwise an error is raised. 行列式t11 * t22 - t12 * t21不能为零,否则会产生错误。Modify stretchfactor, shearfactor and tiltangle according to the given matrix.根据给定矩阵修改拉伸因子、剪切因子和倾斜角。

>>> 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 current shape polygon as tuple of coordinate pairs. 将当前形状多边形作为坐标对的元组返回。This can be used to define a new shape or components of a compound shape.这可用于定义新形状或复合形状的组件。

>>> turtle.shape("square")
>>> turtle.shapetransform(4, -1, 0, 2)
>>> turtle.get_shapepoly()
((50, -20), (30, 20), (-50, 20), (-30, -20))

Using events使用事件

turtle.onclick(fun, btn=1, add=None)
Parameters参数
  • funa function with two arguments which will be called with the coordinates of the clicked point on the canvas具有两个参数的函数,将使用画布上单击点的坐标调用该函数

  • btnnumber of the mouse-button, defaults to 1 (left mouse button)鼠标按钮数,默认为1(鼠标左键)

  • addTrue or Falseif True, a new binding will be added, otherwise it will replace a former binding如果为True,将添加新绑定,否则将替换以前的绑定

Bind fun to mouse-click events on this turtle. If fun is None, existing bindings are removed. fun绑定到此海龟上的鼠标点击事件。如果funNone,则删除现有绑定。Example for the anonymous turtle, i.e. the procedural way:匿名海龟的例子,即程序方法:

>>> 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)
Parameters参数
  • funa function with two arguments which will be called with the coordinates of the clicked point on the canvas具有两个参数的函数,将使用画布上单击点的坐标调用该函数

  • btnnumber of the mouse-button, defaults to 1 (left mouse button)鼠标按钮数,默认为1(鼠标左键)

  • addTrue or Falseif True, a new binding will be added, otherwise it will replace a former binding如果为True,将添加新绑定,否则将替换以前的绑定

Bind fun to mouse-button-release events on this turtle. fun绑定到此海龟上的鼠标按钮释放事件。If fun is None, existing bindings are removed.如果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)
Parameters参数
  • funa function with two arguments which will be called with the coordinates of the clicked point on the canvas具有两个参数的函数,将使用画布上单击点的坐标调用该函数

  • btnnumber of the mouse-button, defaults to 1 (left mouse button)鼠标按钮数,默认为1(鼠标左键)

  • addTrue or Falseif True, a new binding will be added, otherwise it will replace a former binding如果为True,将添加新绑定,否则将替换以前的绑定

Bind fun to mouse-move events on this turtle. fun绑定到这只海龟的鼠标移动事件上。If fun is None, existing bindings are removed.如果funNone,则删除现有绑定。

Remark: Every sequence of mouse-move-events on a turtle is preceded by a mouse-click event on that turtle.备注:海龟上的每个鼠标移动事件序列之前都会有一个鼠标单击事件。

>>> turtle.ondrag(turtle.goto)

Subsequently, clicking and dragging the Turtle will move it across the screen thereby producing handdrawings (if pen is down).随后,单击并拖动海龟将其在屏幕上移动,从而生成手绘(如果笔已放下)。

Special Turtle methods特殊海龟方法

turtle.begin_poly()

Start recording the vertices of a polygon. 开始记录多边形的顶点。Current turtle position is first vertex of polygon.当前海龟位置是多边形的第一个顶点。

turtle.end_poly()

Stop recording the vertices of a polygon. Current turtle position is last vertex of polygon. 停止记录多边形的顶点。当前海龟位置是多边形的最后一个顶点。This will be connected with the first vertex.这将与第一个顶点连接。

turtle.get_poly()

Return the last recorded polygon.返回上次录制的多边形。

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

Create and return a clone of the turtle with same position, heading and turtle properties.创建并返回具有相同位置、标题和海龟属性的海龟克隆。

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

Return the Turtle object itself. 返回海龟对象本身。Only reasonable use: as a function to return the “anonymous turtle”:仅合理使用:作为返回“匿名海龟”的函数:

>>> pet = getturtle()
>>> pet.fd(50)
>>> pet
<turtle.Turtle object at 0x...>
turtle.getscreen()

Return the TurtleScreen object the turtle is drawing on. 返回海龟正在绘制的TurtleScreen对象。TurtleScreen methods can then be called for that object.然后可以为该对象调用TurtleScreen方法。

>>> ts = turtle.getscreen()
>>> ts
<turtle._Screen object at 0x...>
>>> ts.bgcolor("pink")
turtle.setundobuffer(size)
Parameters参数

size – an integer or None

Set or disable undobuffer. 设置或禁用undobufferIf size is an integer, an empty undobuffer of given size is installed. 如果size是整数,则安装给定大小的空undobuffersize gives the maximum number of turtle actions that can be undone by the undo() method/function. size提供了undo()方法/函数可以撤消的最大海龟操作数。If size is None, the undobuffer is disabled.如果sizeNone,则禁用undobuffer

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

Return number of entries in the undobuffer.返回undobuffer中的条目数。

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

Compound shapes复合形状

To use compound turtle shapes, which consist of several polygons of different color, you must use the helper class Shape explicitly as described below:要使用由多个不同颜色的多边形组成的复合海龟形状,必须明确使用助手类Shape,如下所述:

  1. Create an empty Shape object of type “compound”.创建类型为“复合”的空形状对象。

  2. Add as many components to this object as desired, using the addcomponent() method.使用addcomponent()方法,根据需要向该对象添加尽可能多的组件。

    For example:

    >>> 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. Now add the Shape to the Screen’s shapelist and use it:现在将形状添加到屏幕的形状列表并使用它:

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

Note

The Shape class is used internally by the register_shape() method in different ways. register_shape()方法以不同的方式在内部使用Shape类。The application programmer has to deal with the Shape class only when using compound shapes like shown above!应用程序程序员只有在使用如上所示的复合形状时才能处理Shape类!

Methods of TurtleScreen/Screen and corresponding functionsTurtleScreen/Screen的方法及相应的功能

Most of the examples in this section refer to a TurtleScreen instance called screen.本节中的大多数示例都涉及一个名为screenTurtleScreen实例。

Window control窗口控件

turtle.bgcolor(*args)
Parameters参数

argsa color string or three numbers in the range 0..colormode or a 3-tuple of such numbers一个颜色字符串,或三个0..colormode范围内的数字,或此类数字的三元组

Set or return background color of the TurtleScreen.设置或返回TurtleScreen的背景色。

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

picnamea string, name of a gif-file or "nopic", or None字符串、gif文件名或"nopic",或None

Set background image or return name of current backgroundimage. 设置背景图像或返回当前背景图像的名称。If picname is a filename, set the corresponding image as background. 如果picname是文件名,请将相应的图像设置为背景。If picname is "nopic", delete background image, if present. 如果picname"nopic",请删除背景图像(如果存在)。If picname is None, return the filename of the current backgroundimage.如果picnameNone,则返回当前背景图像的文件名。

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

Note

This TurtleScreen method is available as a global function only under the name clearscreen. TurtleScreen方法仅在clearscreen名称下作为全局函数可用。The global function clear is a different one derived from the Turtle method clear.全局函数clear是从Turtle方法clear派生的另一个函数。

turtle.clearscreen()

Delete all drawings and all turtles from the TurtleScreen. 从TurtleScreen中删除所有图形和所有turtles。Reset the now empty TurtleScreen to its initial state: white background, no background image, no event bindings and tracing on.将现在已空的TurtleScreen重置为其初始状态:白色背景、无背景图像、无事件绑定和跟踪打开。

turtle.reset()

Note

This TurtleScreen method is available as a global function only under the name resetscreen. TurtleScreen方法仅在resetscreen名称下作为全局函数可用。The global function reset is another one derived from the Turtle method reset.全局函数reset是从Turtle方法reset派生的另一个函数。

turtle.resetscreen()

Reset all Turtles on the Screen to their initial state.将屏幕上的所有海龟重置为其初始状态。

turtle.screensize(canvwidth=None, canvheight=None, bg=None)
Parameters参数
  • canvwidthpositive integer, new width of canvas in pixels正整数,画布的新宽度(像素)

  • canvheightpositive integer, new height of canvas in pixels正整数,画布的新高度(像素)

  • bgcolorstring or color-tuple, new background colorcolorstringcolor元组,新背景色

If no arguments are given, return current (canvaswidth, canvasheight). 如果没有给定参数,则返回当前值(canvaswidthcanvasheight)。Else resize the canvas the turtles are drawing on. 否则,调整海龟正在绘制的画布的大小。Do not alter the drawing window. 请勿更改绘图窗口。To observe hidden parts of the canvas, use the scrollbars. 要观察画布的隐藏部分,请使用滚动条。With this method, one can make visible those parts of a drawing which were outside the canvas before.使用此方法,可以使以前在画布之外的图形部分可见。

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

e.g. to search for an erroneously escaped turtle ;-)例如,寻找一只误逃的海龟;-)

turtle.setworldcoordinates(llx, lly, urx, ury)
Parameters参数
  • llxa number, x-coordinate of lower left corner of canvas数字,画布左下角的x坐标

  • llya number, y-coordinate of lower left corner of canvas画布左下角的数字y坐标

  • urxa number, x-coordinate of upper right corner of canvas数字,画布右上角的x坐标

  • urya number, y-coordinate of upper right corner of canvas画布右上角的数字y坐标

Set up user-defined coordinate system and switch to mode “world” if necessary. 设置用户定义的坐标系,必要时切换到“世界”模式。This performs a screen.reset(). 这将执行screen.reset()If mode “world” is already active, all drawings are redrawn according to the new coordinates.如果模式“world”已处于活动状态,则将根据新坐标重新绘制所有图形。

ATTENTION: in user-defined coordinate systems angles may appear distorted.:在用户定义的坐标系中,角度可能会扭曲。

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

Animation control动画控件

turtle.delay(delay=None)
Parameters参数

delay – positive integer

Set or return the drawing delay in milliseconds. 设置或返回绘图delay(毫秒)。(This is approximately the time interval between two consecutive canvas updates.) (这大约是两次连续画布更新之间的时间间隔。)The longer the drawing delay, the slower the animation.绘制延迟越长,动画速度越慢。

Optional argument:可选参数:

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

  • delaynonnegative integer非负整数

Turn turtle animation on/off and set delay for update drawings. 打开/关闭海龟动画并设置更新图形的延迟。If n is given, only each n-th regular screen update is really performed. 如果给定n,则只执行第n次常规屏幕更新。(Can be used to accelerate the drawing of complex graphics.) (可用于加速复杂图形的绘制。)When called without arguments, returns the currently stored value of n. 在没有参数的情况下调用时,返回当前存储的值nSecond argument sets delay value (see delay()).第二个参数设置延迟值(请参见delay())。

>>> screen.tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
... fd(dist)
... rt(90)
... dist += 2
turtle.update()

Perform a TurtleScreen update. 执行TurtleScreen更新。To be used when tracer is turned off.当跟踪器关闭时使用。

See also the RawTurtle/Turtle method speed().另请参见RawTurtle/Turtle方法speed()

Using screen events使用屏幕事件

turtle.listen(xdummy=None, ydummy=None)

Set focus on TurtleScreen (in order to collect key-events). 将焦点设置在TurtleScreen上(以收集关键事件)。Dummy arguments are provided in order to be able to pass listen() to the onclick method.提供伪参数是为了能够将listen()传递给onclick方法。

turtle.onkey(fun, key)
turtle.onkeyrelease(fun, key)
Parameters参数
  • funa function with no arguments or None无参数或参数为None的函数

  • keya string: key (e.g. “a”) or key-symbol (e.g. “space”)字符串:键(如"a")或键符号(如"space")

Bind fun to key-release event of key. fun绑定到key的键释放事件。If fun is None, event bindings are removed. Remark: in order to be able to register key-events, TurtleScreen must have the focus. 如果funNone,则移除事件绑定。备注:为了能够注册关键事件,TurtleScreen必须具有焦点。(See method listen().)(请参阅方法listen()。)

>>> def f():
... fd(50)
... lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
turtle.onkeypress(fun, key=None)
Parameters参数
  • funa function with no arguments or None无参数或参数为None的函数

  • keya string: key (e.g. “a”) or key-symbol (e.g. “space”)字符串:键(如"a")或键符号(如"space")

Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given. 如果给定了键,则将fun绑定到键的按键事件,如果未给定键,则绑定到任何按键事件。Remark: in order to be able to register key-events, TurtleScreen must have focus. 备注:为了能够注册关键事件,TurtleScreen必须具有焦点。(See method listen().)(请参阅方法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)
Parameters参数
  • funa function with two arguments which will be called with the coordinates of the clicked point on the canvas具有两个参数的函数,将使用画布上单击点的坐标调用该函数

  • btnnumber of the mouse-button, defaults to 1 (left mouse button)鼠标按钮数,默认为1(鼠标左键)

  • addTrue or Falseif True, a new binding will be added, otherwise it will replace a former binding如果为True,将添加新绑定,否则将替换以前的绑定

Bind fun to mouse-click events on this screen. fun绑定到此屏幕上的鼠标单击事件。If fun is None, existing bindings are removed.如果funNone,则删除现有绑定。

Example for a TurtleScreen instance named screen and a Turtle instance named turtle:名为screenTurtleScreen实例和名为turtleTurtle实例的示例:

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

Note

This TurtleScreen method is available as a global function only under the name onscreenclick. TurtleScreen方法仅在onscreenclick名称下作为全局函数可用。The global function onclick is another one derived from the Turtle method onclick.全局函数onclick是从海龟方法onclick派生的另一个函数。

turtle.ontimer(fun, t=0)
Parameters参数
  • funa function with no arguments没有参数的函数

  • ta number >= 0>=0的数字

Install a timer that calls fun after t milliseconds.安装一个在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()

Starts event loop - calling Tkinter’s mainloop function. 启动事件循环-调用Tkinter的mainloop函数。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 (No subprocess) - for interactive use of turtle graphics.如果脚本在空闲in-n模式(无子进程)下运行,则不得使用该脚本以交互使用turtle图形。

>>> screen.mainloop()

Input methods输入方法

turtle.textinput(title, prompt)
Parameters参数
  • title – string

  • prompt – string

Pop up a dialog window for input of a string. 弹出一个用于输入字符串的对话框窗口。Parameter title is the title of the dialog window, prompt is a text mostly describing what information to input. 参数标题是对话框窗口的标题,提示是一个主要描述要输入哪些信息的文本。Return the string input. 返回字符串输入。If the dialog is canceled, return None.如果对话框被取消,则返回None

>>> screen.textinput("NIM", "Name of first player:")
turtle.numinput(title, prompt, default=None, minval=None, maxval=None)
Parameters参数
  • title – string

  • prompt – string

  • defaultnumber (optional)数字(可选)

  • minvalnumber (optional)数字(可选)

  • maxvalnumber (optional)数字(可选)

Pop up a dialog window for input of a number. 弹出一个用于输入数字的对话框窗口。title is the title of the dialog window, prompt is a text mostly describing what numerical information to input. 标题是对话框窗口的标题,提示是一个文本,主要描述要输入的数字信息。default: default value, minval: minimum value for input, maxval: maximum value for input The number input must be in the range minval .. maxval if these are given. 默认值:默认值,最小值:输入的最小值,最大值:输入的最大值输入的数字必须在最小值..最大值范围内(如果给定)。If not, a hint is issued and the dialog remains open for correction. 否则,将发出提示,对话框将保持打开状态以进行更正。Return the number input. 返回输入的数字。If the dialog is canceled, return None.如果对话框被取消,则返回None

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

Settings and special methods设置和特殊方法

turtle.mode(mode=None)
Parameters参数

modeone of the strings “standard”, “logo” or “world”字符串“standard”、“logo”或“world”之一

Set turtle mode (“standard”, “logo” or “world”) and perform reset. 设置海龟模式(“标准”、“徽标”或“世界”)并执行重置。If mode is not given, current mode is returned.如果未给定模式,则返回当前模式。

Mode “standard” is compatible with old turtle. 模式“standard”与old turtle兼容。Mode “logo” is compatible with most Logo turtle graphics. 模式“徽标”与大多数徽标海龟图形兼容。Mode “world” uses user-defined “world coordinates”. 模式“世界”使用用户定义的“世界坐标”。Attention: in this mode angles appear distorted if x/y unit-ratio doesn’t equal 1.:在此模式下,如果x/y单位比不等于1,则角度会出现扭曲。

Mode模式

Initial turtle heading初始海龟头

positive angles正角度

“standard”

to the right (east)向右(东)

counterclockwise逆时针方向的

“logo”

upward (north)

clockwise顺时针方向的

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

cmodeone of the values 1.0 or 255值1.0或255之一

Return the colormode or set it to 1.0 or 255. 返回颜色模式或将其设置为1.0或255。Subsequently r, g, b values of color triples have to be in the range 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()

Return the Canvas of this TurtleScreen. 返回此TurtleScreen的画布。Useful for insiders who know what to do with a Tkinter Canvas.对于知道如何使用Tkinter画布的内部人员非常有用。

>>> cv = screen.getcanvas()
>>> cv
<turtle.ScrolledCanvas object ...>
turtle.getshapes()

Return a list of names of all currently available turtle shapes.返回当前所有可用海龟形状的名称列表。

>>> screen.getshapes()
['arrow', 'blank', 'circle', ..., 'turtle']
turtle.register_shape(name, shape=None)
turtle.addshape(name, shape=None)

There are three different ways to call this function:有三种不同的方法调用此函数:

  1. name is the name of a gif-file and shape is None: Install the corresponding image shape.name是gif文件的名称,shapeNone:安装相应的图像形状。

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

    Note

    Image shapes do not rotate when turning the turtle, so they do not display the heading of the turtle!翻转海龟时,图像形状不会旋转,因此它们不会显示海龟的头部!

  2. name is an arbitrary string and shape is a tuple of pairs of coordinates: Install the corresponding polygon shape.name是一个任意字符串,shape是一对坐标的元组:安装相应的多边形形状。

    >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
  3. name is an arbitrary string and shape is a (compound) Shape object: Install the corresponding compound shape.是任意字符串和形状是(复合)Shape对象:安装相应的复合形状。

Add a turtle shape to TurtleScreen’s shapelist. 将海龟形状添加到TurtleScreen的形状列表中。Only thusly registered shapes can be used by issuing the command shape(shapename).通过发出命令shape(shapename),只能使用已注册的形状。

turtle.turtles()

Return the list of turtles on the screen.返回屏幕上的海龟列表。

>>> for turtle in screen.turtles():
... turtle.color("red")
turtle.window_height()

Return the height of the turtle window.返回海龟窗口的高度。

>>> screen.window_height()
480
turtle.window_width()

Return the width of the turtle window.返回turtle窗口的宽度。

>>> screen.window_width()
640

Methods specific to Screen, not inherited from TurtleScreen特定于Screen的方法,而不是从TurtleScreen继承的方法

turtle.bye()

Shut the turtlegraphics window.关闭turtlegraphics窗口。

turtle.exitonclick()

Bind bye() method to mouse clicks on the Screen.bye()方法绑定到屏幕上的鼠标单击。

If the value “using_IDLE” in the configuration dictionary is False (default value), also enter mainloop. 如果配置字典中的值“using_IDLE”为False(默认值),也请输入mainloopRemark: If IDLE with the -n switch (no subprocess) is used, this value should be set to True in turtle.cfg. 备注:如果使用带-n开关的IDLE(无子进程),则在turtlecfg中应将此值设置为TrueIn this case IDLE’s own mainloop is active also for the client script.在这种情况下,IDLE自己的mainloop对于客户端脚本也是活动的。

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

Set the size and position of the main window. 设置主窗口的大小和位置。Default values of arguments are stored in the configuration dictionary and can be changed via a turtle.cfg file.参数的默认值存储在配置字典中,可以通过turtle.cfg文件进行更改。

Parameters参数
  • widthif an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen如果是整数,则为像素大小,如果是浮点,则为屏幕的分数;默认值为屏幕的50%

  • heightif an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen如果是整数,高度以像素为单位,如果是浮点,则为屏幕的分数;默认值为屏幕的75%

  • startxif positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if None, center window horizontally如果为正,则从屏幕左边缘开始,以像素为单位;如果为负,则从右边缘开始;如果为None,则将窗口水平居中

  • startyif positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if None, center window vertically如果为正,则从屏幕上边缘开始的位置(以像素为单位),如果为负,则从下边缘开始,如果为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)
Parameters参数

titlestringa string that is shown in the titlebar of the turtle graphics window显示在turtle图形窗口标题栏中的字符串

Set title of turtle window to titlestring.将turtle窗口的标题设置为titlestring

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

Public classes公共课程

classturtle.RawTurtle(canvas)
classturtle.RawPen(canvas)
Parameters参数

canvas – a tkinter.Canvas, a ScrolledCanvas or a TurtleScreen

Create a turtle. 创建一只海龟。The turtle has all methods described above as “methods of Turtle/RawTurtle”.海龟拥有上述所有方法,即“海龟/生海龟的方法”。

classturtle.Turtle

Subclass of RawTurtle, has the same interface but draws on a default Screen object created automatically when needed for the first time.RawTurtle的子类具有相同的界面,但在第一次需要时会使用自动创建的默认Screen对象。

classturtle.TurtleScreen(cv)
Parameters参数

cv – a tkinter.Canvas

Provides screen oriented methods like setbg() etc. that are described above.提供上述面向屏幕的方法,如setbg()等。

classturtle.Screen

Subclass of TurtleScreen, with four methods added.TurtleScreen的子类,添加了四种方法

classturtle.ScrolledCanvas(master)
Parameters参数

mastersome Tkinter widget to contain the ScrolledCanvas, i.e. a Tkinter-canvas with scrollbars added一些Tkinter小部件包含ScrolledCanvas,即添加了滚动条的Tkinter画布

Used by class Screen, which thus automatically provides a ScrolledCanvas as playground for the turtles.由类屏幕使用,从而自动提供一个滚动画布作为海龟的游乐场。

classturtle.Shape(type_, data)
Parameters参数

type_one of the strings “polygon”, “image”, “compound”字符串"polygon""image""compound"之一

Data structure modeling shapes. 数据结构建模形状。The pair (type_, data) must follow this specification:配对(type_, data)必须遵循此规范:

type_

data

“polygon”

a polygon-tuple, i.e. a tuple of pairs of coordinates多边形元组,即坐标对的元组

“image”

an image (in this form only used internally!)图像(此格式仅限内部使用!)

“compound”

None (a compound shape has to be constructed using the addcomponent() method)(必须使用addcomponent()方法构造复合形状)

addcomponent(poly, fill, outline=None)
Parameters参数
  • polya polygon, i.e. a tuple of pairs of numbers多边形,即数对的元组

  • filla color the poly will be filled with多边形将填充的颜色

  • outlinea color for the poly’s outline (if given)多边形轮廓的颜色(如果给定)

Example:示例:

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

See Compound shapes.请参见复合形状

classturtle.Vec2D(x, y)

A two-dimensional vector class, used as a helper class for implementing turtle graphics. 一个二维向量类,用作实现海龟图形的辅助类。May be useful for turtle graphics programs too. 可能对海龟图形程序也有用。Derived from tuple, so a vector is a tuple!源于元组,所以向量就是元组!

Provides (for a, b vectors, k number):提供(对于ab矢量和k数):

  • a + b vector addition矢量加法

  • a - b vector subtraction矢量减法

  • a * b inner product内部产品

  • k * a and a * k multiplication with scalar标量乘法

  • abs(a) absolute value of aa的绝对值

  • a.rotate(angle) rotation旋转

Help and configuration帮助和配置

How to use help如何使用帮助

The public methods of the Screen and Turtle classes are documented extensively via docstrings. Screen和Turtle类的公共方法通过docstring进行了广泛的记录。So these can be used as online-help via the Python help facilities:因此,这些可以通过Python帮助工具用作在线帮助:

  • When using IDLE, tooltips show the signatures and first lines of the docstrings of typed in function-/method calls.使用IDLE时,工具提示将显示签名和键入的函数/方法调用的docstrings的第一行。

  • Calling help() on methods or functions displays the docstrings:对方法或函数调用help()将显示docstring:

    >>> 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()
  • The docstrings of the functions which are derived from methods have a modified form:从方法派生的函数的docstring具有修改后的形式:

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

These modified docstrings are created automatically together with the function definitions that are derived from the methods at import time.这些修改后的docstring与导入时从方法派生的函数定义一起自动创建。

Translation of docstrings into different languages将docstring翻译成不同的语言

There is a utility to create a dictionary the keys of which are the method names and the values of which are the docstrings of the public methods of the classes Screen and Turtle.有一个实用程序可以创建一个字典,字典的键是方法名,值是Screen和Turtle类的公共方法的docstring。

turtle.write_docstringdict(filename='turtle_docstringdict')
Parameters参数

filenamea string, used as filename用作文件名的字符串

Create and write docstring-dictionary to a Python script with the given filename. 使用给定的文件名创建docstring字典并将其写入Python脚本。This function has to be called explicitly (it is not used by the turtle graphics classes). 必须显式调用此函数(turtle graphics类不使用此函数)。The docstring dictionary will be written to the Python script filename.py. docstring字典将写入Python脚本filename.pyIt is intended to serve as a template for translation of the docstrings into different languages.它旨在作为将docstring翻译成不同语言的模板。

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的在线帮助,您必须翻译docstrings并将生成的文件保存为例如turtle_docstringdict_german.py

If you have an appropriate entry in your turtle.cfg file this dictionary will be read in at import time and will replace the original English docstrings.如果您的turtle.cfg文件中有适当的条目,则将在导入时读入此词典,并将替换原始英文docstring。

At the time of this writing there are docstring dictionaries in German and in Italian. 在撰写本文时,有德语和意大利语的docstring词典。(Requests please to glingl@aon.at.)

How to configure Screen and Turtles如何配置Screen和Turtles

The built-in default configuration mimics the appearance and behaviour of the old turtle module in order to retain best possible compatibility with it.内置默认配置模仿旧turtle模块的外观和行为,以保持与它的最佳兼容性。

If you want to use a different configuration which better reflects the features of this module or which better fits to your needs, e.g. for use in a classroom, you can prepare a configuration file turtle.cfg which will be read at import time and modify the configuration according to its settings.如果您想使用更好地反映本模块功能或更适合您需要的不同配置,例如在教室中使用,您可以准备一个配置文件turtle.cfg,该文件将在导入时读取,并根据其设置修改配置。

The built in configuration would correspond to the following turtle.cfg:内置配置将对应以下turtlecfg:

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

Short explanation of selected entries:所选条目的简短说明:

  • The first four lines correspond to the arguments of the Screen.setup() method.前四行对应于Screen.setup()方法的参数。

  • Line 5 and 6 correspond to the arguments of the method Screen.screensize().第5行和第6行对应于Screen.screensize()方法的参数。

  • shape can be any of the built-in shapes, e.g: arrow, turtle, etc. shape可以是任何内置形状,如箭头、海龟等。For more info try help(shape).有关更多信息,请尝试help(shape)

  • If you want to use no fillcolor (i.e. make the turtle transparent), you have to write fillcolor = "" (but all nonempty strings must not have quotes in the cfg-file).

  • If you want to reflect the turtle its state, you have to use resizemode = auto.如果要反映海龟的状态,必须使用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.例如,如果设置language = italian,docstringdict 将在导入时加载code>turtle_docstringdict_italian.py(如果存在于导入路径上,例如与turtle位于同一目录中)。

  • The entries exampleturtle and examplescreen define the names of these objects as they occur in the docstrings. 条目exampleturtleexamplescreen定义了这些对象在文档字符串中出现时的名称。The transformation of method-docstrings to function-docstrings will delete these names from the docstrings.将方法docstrings转换为函数docstrings将从docstrings中删除这些名称。

  • using_IDLE: Set this to True if you regularly work with IDLE and its -n switch (“no subprocess”). :如果您经常使用IDLE及其-n开关(“无子进程”),则将其设置为TrueThis will prevent exitonclick() to enter the mainloop.这将阻止exitonclick()进入主循环。

There can be a turtle.cfg file in the directory where turtle is stored and an additional one in the current working directory. 在存储turtle的目录中可以有一个turtle.cfg文件,在当前工作目录中可以有一个额外的文件。The latter will override the settings of the first one.后者将覆盖第一个的设置。

The Lib/turtledemo directory contains a turtle.cfg file. Lib/turtledemo目录包含一个turtle.cfg文件。You can study it as an example and see its effects when running the demos (preferably not from within the demo-viewer).您可以将其作为示例进行研究,并在运行演示时查看其效果(最好不要从演示查看器中查看)。

turtledemoDemo scripts演示脚本

The turtledemo package includes a set of demo scripts. turtledemo包包括一组演示脚本。These scripts can be run and viewed using the supplied demo viewer as follows:可以使用提供的演示查看器运行和查看这些脚本,如下所示:

python -m turtledemo

Alternatively, you can run the demo scripts individually. 或者,您可以单独运行演示脚本。For example,例如

python -m turtledemo.bytedesign

The turtledemo package directory contains:turtledemo包目录包含:

  • A demo viewer __main__.py which can be used to view the sourcecode of the scripts and run them at the same time.演示查看器__main__.py,可用于查看脚本的源代码并同时运行它们。

  • Multiple scripts demonstrating different features of the turtle module. 演示turtle模块不同功能的多个脚本。Examples can be accessed via the Examples menu. They can also be run standalone.可以通过示例菜单访问示例。它们也可以独立运行。

  • A turtle.cfg file which serves as an example of how to write and use such files.一个turtle.cfg文件,作为如何编写和使用此类文件的示例。

The demo scripts are:演示脚本包括:

Name名称

Description描述

Features特征

bytedesign

complex classical turtle graphics pattern复杂的经典海龟图案

tracer(), delay, ,延迟,update()

chaos

graphs Verhulst dynamics, shows that computer’s computations can generate results sometimes against the common sense expectationsVerhulst dynamics的图表显示,计算机的计算有时会产生违背常识预期的结果

world coordinates世界坐标

clock

analog clock showing time of your computer显示计算机时间的模拟时钟

turtles as clock’s hands, ontimer乌龟是时钟的指针

colormixer

experiment with r, g, b用r、g、b进行试验

ondrag()

forest

3 breadth-first trees3棵宽度优先的树

randomization

fractalcurves

Hilbert & Koch curvesHilbert和Koch曲线

recursion递归

lindenmayer

ethnomathematics (indian kolams)民族数学(印度科拉姆)

L-System

minimal_hanoi

Towers of Hanoi河內之塔

Rectangular Turtles as Hanoi discs (shape, shapesize)矩形海龟作为河内圆盘(形状,形状大小)

nim

play the classical nim game with three heaps of sticks against the computer.用三堆棍子与电脑玩经典的尼姆游戏。

turtles as nimsticks, event driven (mouse, keyboard)海龟作为nimsticks,事件驱动(鼠标、键盘)

paint

super minimalistic drawing program超简约绘图程序

onclick()

peace

elementary初级的

turtle: appearance and animation海龟:外观和动画

penrose

aperiodic tiling with kites and darts带风筝和飞镖的非周期瓷砖

stamp()

planet_and_moon

simulation of gravitational system重力系统模拟

compound shapes, 复合形状,Vec2D

round_dance

dancing turtles rotating pairwise in opposite direction舞动的海龟两两朝相反方向旋转

compound shapes, clone shapesize, tilt, get_shapepoly, update复合形状、克隆形状大小、倾斜、get_shapepoly、更新

sorting_animate

visual demonstration of different sorting methods不同分拣方法的可视化演示

simple alignment, randomization简单对齐,随机化

tree

a (graphical) breadth first tree (using generators)(图形)宽度优先树(使用生成器)

clone()

two_canvases

simple design简单的设计

turtles on two canvases两幅画布上的海龟

wikipedia

a pattern from the wikipedia article on turtle graphics维基百科关于海龟图形的文章中的模式

clone(), undo()

yinyang

another elementary example另一个基本示例

circle()

Have fun!玩得高兴

Changes since Python 2.6自Python 2.6以来的更改

  • The methods Turtle.tracer(), Turtle.window_width() and Turtle.window_height() have been eliminated. 方法Turtle.tracer()Turtle.window_width()Turtle.window_height()已被删除。Methods with these names and functionality are now available only as methods of Screen. 具有这些名称和功能的方法现在只能作为Screen的方法使用。The functions derived from these remain available. 由此派生的函数仍然可用。(In fact already in Python 2.6 these methods were merely duplications of the corresponding TurtleScreen/Screen-methods.)(事实上,在Python 2.6中,这些方法仅仅是相应TurtleScreen/Screen方法的复制。)

  • The method Turtle.fill() has been eliminated. 方法Turtle.fill()已被删除。The behaviour of begin_fill() and end_fill() have changed slightly: now every filling-process must be completed with an end_fill() call.begin_fill()end_fill()的行为略有变化:现在每个填充过程都必须通过end_fill()调用完成。

  • A method Turtle.filling() has been added. 添加了一个方法Turtle.filling()It returns a boolean value: True if a filling process is under way, False otherwise. 它返回一个布尔值:如果填充过程正在进行,则为True,否则为FalseThis behaviour corresponds to a fill() call without arguments in Python 2.6.这种行为对应于Python 2.6中不带参数的fill()调用。

Changes since Python 3.0自Python 3.0以来的变化

  • The methods Turtle.shearfactor(), Turtle.shapetransform() and Turtle.get_shapepoly() have been added. 添加了Turtle.shearfactor()Turtle.shapetransform()Turtle.get_shapepoly()方法。Thus the full range of regular linear transforms is now available for transforming turtle shapes. 因此,现在可以使用各种常规线性变换来变换海龟形状。Turtle.tiltangle() has been enhanced in functionality: it now can be used to get or set the tiltangle. 在功能上得到了增强:现在可以使用它来获取或设置倾斜角度。Turtle.settiltangle() has been deprecated.已被弃用。

  • The method Screen.onkeypress() has been added as a complement to Screen.onkey() which in fact binds actions to the keyrelease event. Screen.onkeypress()方法是Screen.onkey()的补充,它实际上将操作绑定到keyrelease事件。Accordingly the latter has got an alias: Screen.onkeyrelease().因此,后者有一个别名:Screen.onkeyrelease()

  • The method Screen.mainloop() has been added. 添加了Screen.mainloop()方法。So when working only with Screen and Turtle objects one must not additionally import mainloop() anymore.因此,当只处理Screen和Turtle对象时,不能再额外导入mainloop()

  • Two input methods has been added Screen.textinput() and Screen.numinput(). 添加了两个输入方法Screen.textinput()Screen.numinput()These popup input dialogs and return strings and numbers respectively.这些弹出式输入对话框分别返回字符串和数字。

  • Two example scripts tdemo_nim.py and tdemo_round_dance.py have been added to the Lib/turtledemo directory.