turtle
— Turtle 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:面向对象接口基本上使用两个+两个类:
TheTurtleScreen
class defines graphics windows as a playground for the drawing turtles.TurtleScreen
类将图形窗口定义为绘制海龟的游乐场。Its constructor needs a它的构造函数需要tkinter.Canvas
or aScrolledCanvas
as argument.tkinter.Canvas
或ScrolledCanvas
作为参数。It should be used when当turtle
is used as part of some application.turtle
被用作某些应用程序的一部分时,应该使用它。The function函数Screen()
returns a singleton object of aTurtleScreen
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
的所有方法也作为功能存在,即作为面向过程的界面的一部分。RawTurtle
(alias:(别名:RawPen
) defines Turtle objects which draw on aTurtleScreen
.RawPen
)定义在TurtleScreen
上绘制的Turtle对象。Its constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle objects know where to draw.它的构造函数需要一个Canvas
、ScrolledCanvas
或TurtleScreen
作为参数,以便RawTurtle
对象知道在哪里绘制。Derived from RawTurtle is the subclass派生自RawTurtle的子类Turtle
(alias:Pen
), which draws on “the”Screen
instance which is automatically created, if not already present.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
. Screen
和Turtle
类的方法派生的函数。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可用Turtle
和Screen
方法概述¶
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参数-
distance –
a 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参数-
distance –
a 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参数-
angle –
a number (integer or float)数字(整数或浮点)
Turn turtle right by angle units.以angle单位向右旋转海龟。(Units are by default degrees, but can be set via the(单位默认为度,但可以通过degrees()
andradians()
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参数-
angle –
a number (integer or float)数字(整数或浮点)
Turn turtle left by angle units.以angle单位向左旋转海龟。(Units are by default degrees, but can be set via the(单位默认为度,但可以通过degrees()
andradians()
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参数x –
a number or a pair/vector of numbers数字或数字对/数字向量y –
a number or数字或None
None
If y is如果y为None
, x must be a pair of coordinates or aVec2D
(e.g. as returned bypos()
).None
,则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参数-
x –
a 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参数-
y –
a 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_angle –
a number (integer or float)数字(整数或浮点)
Set the orientation of the turtle to to_angle.将海龟的方向设置为to_angle。Here 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将海龟移动到原点坐标(0,0),并将其航向设置为起始方向(取决于模式,请参阅mode()
).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参数radius –
a number一个数字extent –
a number (or数字(或None
)None
)steps –
an 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)
color –
a 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返回该戳记的stamp_id,可通过调用clearstamp(stamp_id)
.clearstamp(stamp_id)
将其删除。>>> turtle.color("blue")
>>> turtle.stamp()
11
>>> turtle.fd(50)
-
turtle.
clearstamp
(stampid)¶ Parameters参数-
stampid –
an integer, must be return value of previous整数,必须是上一个stamp()
callstamp()
调用的返回值
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参数-
n –
an integer (or整数(或None
)None
)
Delete all or first/last n of turtle’s stamps.删除所有或第一/最后n个海龟邮票。If n is如果n为None
, delete all stamps, if n > 0 delete first n stamps, else if n < 0 delete last n stamps.None
,则删除所有戳记,如果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参数-
speed –
an 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返回海龟的当前位置(x,y)(作为Vec2D
vector).Vec2D
向量)。>>> turtle.pos()
(440.00,-0.00)
-
turtle.
towards
(x, y=None)¶ Parameters参数x –
a number or a pair/vector of numbers or a turtle instance数字或数字对/向量或海龟实例y –
a number if x is a number, else如果x是数字,则为数字,否则为None
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参数x –
a number or a pair/vector of numbers or a turtle instance数字或数字对/向量或海龟实例y –
a number if x is a number, else如果x是数字,则为数字,否则为None
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参数-
fullcircle –
a 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.
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参数pen –
a dictionary with some or all of the below listed keys包含以下部分或全部键的字典pendict –
one 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
设置为由r、g和b的元组表示的RGB颜色。Each of r, g, and b must be in the range 0..colormode, where colormode is either 1.0 or 255 (seer、g和b中的每一个都必须在colormode()
).0..colormode
的范围内,其中colormode
为1.0或255(请参见colormode()
)。pencolor(r, g, b)
Set pencolor to the RGB color represented by r, g, and b.将pencolor
设置为由r、g和b表示的RGB颜色。Each of r, g, and b must be in the range 0..colormode.r、g和b中的每一个都必须在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
设置为由r、g和b的元组表示的RGB颜色。其中r、g和b的每个值都必须在0..colormode
范围内,其中colormode
为1.0或255(请参见colormode()
)。fillcolor(r, g, b)
Set fillcolor to the RGB color represented by r, g, and b.将fillcolor
设置为由r、g和b表示的RGB颜色。Each of r, g, and b must be in the range 0..colormode.r、g和b中的每一个都必须在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和当前fillcolor作为一对颜色规范字符串或元组返回,由pencolor()
andfillcolor()
.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()
中输入,将fillcolor
和pencolor
都设置为给定值。color(colorstring1, colorstring2)
,color((r1,g1,b1), (r2,g2,b2))
Equivalent to与pencolor(colorstring1)
andfillcolor(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参数arg –
object to be written to the TurtleScreen要写入TurtleScreen
的对象move –
True/FalseTrue
/False
align –
one of the strings “left”, “center” or right”字符串"left"
、"center"
或"right"
之一font –
a triple (fontname, fontsize, fonttype)三元组(fontname
、fontsize
、fonttype
)
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.如果move为true
,则笔将移动到文本的右下角。By default, move is默认情况下,move为False
.False
。>>> 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.
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参数-
name –
a 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参数-
rmode –
one 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,则返回当前resizemode
。Different 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_wid –
positive number正数,正数stretch_len –
positive number正数,正数outline –
positive 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参数-
shear –
a 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参数-
angle –
a 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参数-
angle –
a 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参数-
angle –
a 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参数t11 –
a number (optional)数字(可选)t12 –
a number (optional)数字(可选)t21 –
a number (optional)数字(可选)t12 –
a 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组成的矩阵变换turtleshape
。The 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参数fun –
a function with two arguments which will be called with the coordinates of the clicked point on the canvas具有两个参数的函数,将使用画布上单击点的坐标调用该函数btn –
number of the mouse-button, defaults to 1 (left mouse button)鼠标按钮数,默认为1(鼠标左键)add –
True
or或False
–if如果为True
, a new binding will be added, otherwise it will replace a former bindingTrue
,将添加新绑定,否则将替换以前的绑定
Bind fun to mouse-click events on this turtle. If fun is将fun绑定到此海龟上的鼠标点击事件。如果fun为None
, existing bindings are removed.None
,则删除现有绑定。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参数fun –
a function with two arguments which will be called with the coordinates of the clicked point on the canvas具有两个参数的函数,将使用画布上单击点的坐标调用该函数btn –
number of the mouse-button, defaults to 1 (left mouse button)鼠标按钮数,默认为1(鼠标左键)add –
True
or或False
–if如果为True
, a new binding will be added, otherwise it will replace a former bindingTrue
,将添加新绑定,否则将替换以前的绑定
Bind fun to mouse-button-release events on this turtle.将fun绑定到此海龟上的鼠标按钮释放事件。If fun is如果fun为None
, existing bindings are removed.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) # clicking on turtle turns fillcolor red,
>>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
-
turtle.
ondrag
(fun, btn=1, add=None)¶ Parameters参数fun –
a function with two arguments which will be called with the coordinates of the clicked point on the canvas具有两个参数的函数,将使用画布上单击点的坐标调用该函数btn –
number of the mouse-button, defaults to 1 (left mouse button)鼠标按钮数,默认为1(鼠标左键)add –
True
orFalse
–if如果为True
, a new binding will be added, otherwise it will replace a former bindingTrue
,将添加新绑定,否则将替换以前的绑定
Bind fun to mouse-move events on this turtle.将fun绑定到这只海龟的鼠标移动事件上。If fun is如果fun为None
, existing bindings are removed.None
,则删除现有绑定。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.设置或禁用undobuffer
。If size is an integer, an empty undobuffer of given size is installed.如果size是整数,则安装给定大小的空undobuffer
。size gives the maximum number of turtle actions that can be undone by thesize提供了undo()
method/function.undo()
方法/函数可以撤消的最大海龟操作数。If size is如果size为None
, the undobuffer is disabled.None
,则禁用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
,如下所述:
Create an empty Shape object of type “compound”.创建类型为“复合”的空形状对象。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")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
.screen
的TurtleScreen
实例。
Window control窗口控件¶
-
turtle.
bgcolor
(*args)¶ Parameters参数-
args –
a 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参数-
picname –
a string, name of a gif-file or字符串、gif文件名或"nopic"
, orNone
"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如果picname为"nopic"
, delete background image, if present."nopic"
,请删除背景图像(如果存在)。If picname is如果picname为None
, return the filename of the current backgroundimage.None
,则返回当前背景图像的文件名。>>> 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 methodclear
.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 methodreset
.reset
是从Turtle
方法reset
派生的另一个函数。
-
turtle.
resetscreen
()¶ Reset all Turtles on the Screen to their initial state.将屏幕上的所有海龟重置为其初始状态。
-
turtle.
screensize
(canvwidth=None, canvheight=None, bg=None)¶ Parameters参数canvwidth –
positive integer, new width of canvas in pixels正整数,画布的新宽度(像素)canvheight –
positive integer, new height of canvas in pixels正整数,画布的新高度(像素)bg –
colorstring or color-tuple, new background colorcolorstring
或color
元组,新背景色
If no arguments are given, return current (canvaswidth, canvasheight).如果没有给定参数,则返回当前值(canvaswidth
、canvasheight
)。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参数llx –
a number, x-coordinate of lower left corner of canvas数字,画布左下角的x坐标lly –
a number, y-coordinate of lower left corner of canvas画布左下角的数字y坐标urx –
a number, x-coordinate of upper right corner of canvas数字,画布右上角的x坐标ury –
a 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参数n –
nonnegative integer非负整数delay –
nonnegative 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.在没有参数的情况下调用时,返回当前存储的值n。Second 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参数fun –
a function with no arguments or无参数或参数为None
None
的函数key –
a 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如果fun为None
, event bindings are removed. Remark: in order to be able to register key-events, TurtleScreen must have the focus.None
,则移除事件绑定。备注:为了能够注册关键事件,TurtleScreen
必须具有焦点。(See method(请参阅方法listen()
.)listen()
。)>>> def f():
... fd(50)
... lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
-
turtle.
onkeypress
(fun, key=None)¶ Parameters参数fun –
a function with no arguments or无参数或参数为None
None
的函数key –
a 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参数fun –
a function with two arguments which will be called with the coordinates of the clicked point on the canvas具有两个参数的函数,将使用画布上单击点的坐标调用该函数btn –
number of the mouse-button, defaults to 1 (left mouse button)鼠标按钮数,默认为1(鼠标左键)add –
True
orFalse
–if如果为True
, a new binding will be added, otherwise it will replace a former bindingTrue
,将添加新绑定,否则将替换以前的绑定
Bind fun to mouse-click events on this screen.将fun绑定到此屏幕上的鼠标单击事件。If fun is如果fun为None
, existing bindings are removed.None
,则删除现有绑定。Example for a TurtleScreen instance named名为screen
and a Turtle instance namedturtle
:screen
的TurtleScreen
实例和名为turtle
的Turtle
实例的示例:>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>> # make the turtle move to the clicked point.
>>> screen.onclick(None) # remove event binding againNote
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 methodonclick
.onclick
是从海龟方法onclick
派生的另一个函数。
-
turtle.
ontimer
(fun, t=0)¶ Parameters参数fun –
a function with no arguments没有参数的函数t –
a 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
default –
number (optional)数字(可选)minval –
number (optional)数字(可选)maxval –
number (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参数-
mode –
one 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模式“standard”与oldturtle
.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参数-
cmode –
one 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:有三种不同的方法调用此函数:name is the name of a gif-file and shape isname是gif文件的名称,shape是None
: Install the corresponding image shape.None
:安装相应的图像形状。>>> 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!翻转海龟时,图像形状不会旋转,因此它们不会显示海龟的头部!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)))
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如果配置字典中的值“using_IDLE”为False
(default value), also enter mainloop.False
(默认值),也请输入mainloop
。Remark: If IDLE with the备注:如果使用带-n
switch (no subprocess) is used, this value should be set toTrue
inturtle.cfg
.-n
开关的IDLE(无子进程),则在turtlecfg中应将此值设置为True
。In 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参数width –
if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen如果是整数,则为像素大小,如果是浮点,则为屏幕的分数;默认值为屏幕的50%height –
if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen如果是整数,高度以像素为单位,如果是浮点,则为屏幕的分数;默认值为屏幕的75%startx –
if positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if如果为正,则从屏幕左边缘开始,以像素为单位;如果为负,则从右边缘开始;如果为None
, center window horizontallyNone
,则将窗口水平居中starty –
if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if如果为正,则从屏幕上边缘开始的位置(以像素为单位),如果为负,则从下边缘开始,如果为None
, center window verticallyNone
,则垂直居中窗口
>>> 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参数-
titlestring –
a 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公共课程¶
-
class
turtle.
RawTurtle
(canvas)¶ -
class
turtle.
RawPen
(canvas)¶ Parameters参数-
canvas – a
tkinter.Canvas
, aScrolledCanvas
or aTurtleScreen
Create a turtle.创建一只海龟。The turtle has all methods described above as “methods of Turtle/RawTurtle”.海龟拥有上述所有方法,即“海龟/生海龟的方法”。
-
class
turtle.
Turtle
¶ Subclass of RawTurtle, has the same interface but draws on a defaultScreen
object created automatically when needed for the first time.RawTurtle
的子类具有相同的界面,但在第一次需要时会使用自动创建的默认Screen
对象。
-
class
turtle.
TurtleScreen
(cv)¶ Parameters参数-
cv – a
tkinter.Canvas
Provides screen oriented methods like提供上述面向屏幕的方法,如setbg()
etc. that are described above.setbg()
等。
-
class
turtle.
Screen
¶ Subclass of TurtleScreen, with four methods added.TurtleScreen
的子类,添加了四种方法。
-
class
turtle.
ScrolledCanvas
(master)¶ Parameters参数-
master –
some 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.由类屏幕使用,从而自动提供一个滚动画布作为海龟的游乐场。
-
class
turtle.
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参数poly –
a polygon, i.e. a tuple of pairs of numbers多边形,即数对的元组fill –
a color the poly will be filled with多边形将填充的颜色outline –
a 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.请参见复合形状。
-
class
turtle.
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):提供(对于a、b矢量和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参数-
filename –
a 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 scriptdocstring字典将写入Python脚本filename.py
.filename.py
。It 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第5行和第6行对应于Screen.screensize()
.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 docstringdictturtle_docstringdict_italian.py
will be loaded at import time (if present on the import path, e.g. in the same directory asturtle
.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.条目exampleturtle和examplescreen定义了这些对象在文档字符串中出现时的名称。The transformation of method-docstrings to function-docstrings will delete these names from the docstrings.将方法docstrings转换为函数docstrings将从docstrings中删除这些名称。using_IDLE
: Set this to:如果您经常使用IDLE及其-n开关(“无子进程”),则将其设置为True
if you regularly work with IDLE and its -n switch (“no subprocess”).True
。This 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).您可以将其作为示例进行研究,并在运行演示时查看其效果(最好不要从演示查看器中查看)。
turtledemo
— Demo 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:演示脚本包括:
|
|
|
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
L-System |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Have fun!玩得高兴
Changes since Python 2.6自Python 2.6以来的更改¶
The methods方法Turtle.tracer()
,Turtle.window_width()
andTurtle.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(事实上,在Python 2.6中,这些方法仅仅是相应TurtleScreen
/Screen
-methods.)TurtleScreen
/Screen
方法的复制。)The method方法Turtle.fill()
has been eliminated.Turtle.fill()
已被删除。The behaviour ofbegin_fill()
andend_fill()
have changed slightly: now every filling-process must be completed with anend_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
,否则为False
。This behaviour corresponds to a这种行为对应于Python 2.6中不带参数的fill()
call without arguments in Python 2.6.fill()
调用。
Changes since Python 3.0自Python 3.0以来的变化¶
The methods添加了Turtle.shearfactor()
,Turtle.shapetransform()
andTurtle.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 methodScreen.onkeypress()
has been added as a complement toScreen.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因此,当只处理Screen和Turtle对象时,不能再额外导入mainloop()
anymore.mainloop()
。Two input methods has been added添加了两个输入方法Screen.textinput()
andScreen.numinput()
.Screen.textinput()
和Screen.numinput()
。These popup input dialogs and return strings and numbers respectively.这些弹出式输入对话框分别返回字符串和数字。Two example scripts
tdemo_nim.py
andtdemo_round_dance.py
have been added to theLib/turtledemo
directory.