python标准库《turtle》

FUNCTIONS
Screen()
Return the singleton screen object.
If none exists at the moment, create a new one and return it,
else return the existing one.

addshape(name, shape=None)
Adds a turtle shape to TurtleScreen‘s shapelist.

Arguments:
(1) name is the name of a gif-file and shape is None.
Installs the corresponding image shape.
!! 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. Installs the corresponding
polygon shape
(3) name is an arbitrary string and shape is a
(compound) Shape object. Installs the corresponding
compound shape.
To use a shape, you have to issue the command shape(shapename).

call: register_shape("turtle.gif")
--or: register_shape("tri", ((0,0), (10,10), (-10,10)))

Example:
>>> register_shape("triangle", ((5,-3),(0,5),(-5,-3)))

back(distance)
Move the turtle backward by distance.

Aliases: back | backward | bk

Argument:
distance -- a number

Move the turtle backward by distance ,opposite to the direction the
turtle is headed. Do not change the turtle‘s heading.

Example:
>>> position()
(0.00, 0.00)
>>> backward(30)
>>> position()
(-30.00, 0.00)

backward(distance)
Move the turtle backward by distance.

Aliases: back | backward | bk

Argument:
distance -- a number

Move the turtle backward by distance ,opposite to the direction the
turtle is headed. Do not change the turtle‘s heading.

Example:
>>> position()
(0.00, 0.00)
>>> backward(30)
>>> position()
(-30.00, 0.00)

begin_fill()
Called just before drawing a shape to be filled.

No argument.

Example:
>>> color("black", "red")
>>> begin_fill()
>>> circle(60)
>>> end_fill()

begin_poly()
Start recording the vertices of a polygon.

No argument.

Start recording the vertices of a polygon. Current turtle position
is first point of polygon.

Example:
>>> begin_poly()

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‘

bgpic(picname=None)
Set background image or return name of current backgroundimage.

Optional argument:
picname -- a string, name of a gif-file or "nopic".

If picname is a filename, set the corresponding image as background.
If picname is "nopic", delete backgroundimage, if present.
If picname is None, return the filename of the current backgroundimage.

Example:
>>> bgpic()
‘nopic‘
>>> bgpic("landscape.gif")
>>> bgpic()
‘landscape.gif‘

bk(distance)
Move the turtle backward by distance.

Aliases: back | backward | bk

Argument:
distance -- a number

Move the turtle backward by distance ,opposite to the direction the
turtle is headed. Do not change the turtle‘s heading.

Example:
>>> position()
(0.00, 0.00)
>>> backward(30)
>>> position()
(-30.00, 0.00)

bye()
Shut the turtlegraphics window.

Example:
>>> bye()

circle(radius, extent=None, steps=None)
Draw a circle with given radius.

Arguments:
radius -- a number
extent (optional) -- a number
steps (optional) -- an integer

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

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

call: circle(radius) # full circle
--or: circle(radius, extent) # arc
--or: circle(radius, extent, steps)
--or: circle(radius, steps=6) # 6-sided polygon

Example:
>>> circle(50)
>>> circle(120, 180) # semicircle

clear()
Delete the turtle‘s drawings from the screen. Do not move

No arguments.

Delete the turtle‘s drawings from the screen. Do not move
State and position of the turtle as well as drawings of other
turtles are not affected.

Examples:
>>> clear()

clearscreen()
Delete all drawings and all turtles from the TurtleScreen.

No argument.

Reset empty TurtleScreen to its initial state: white background,
no backgroundimage, no eventbindings and tracing on.

Example:
>>> clear()

Note: this method is not available as function.

clearstamp(stampid)
Delete stamp with given stampid

Argument:
stampid - an integer, must be return value of previous stamp() call.

Example:
>>> color("blue")
>>> astamp = stamp()
>>> fd(50)
>>> clearstamp(astamp)

clearstamps(n=None)
Delete all or first/last n of turtle‘s stamps.

Optional argument:
n -- an integer

If n is None, delete all of pen‘s stamps,
else if n > 0 delete first n stamps
else if n < 0 delete last n stamps.

Example:
>>> for i in range(8):
... stamp(); fd(30)
...
>>> clearstamps(2)
>>> clearstamps(-2)
>>> clearstamps()

clone()
Create and return a clone of the

No argument.

Create and return a clone of the turtle with same position, heading
and turtle properties.

Example (for a Turtle instance named mick):
mick = Turtle()
joe = mick.clone()

color(*args)
Return or set the pencolor and fillcolor.

Arguments:
Several input formats are allowed.
They use 0, 1, 2, or 3 arguments as follows:

color()
Return the current pencolor and the current fillcolor
as a pair of color specification strings as are returned
by pencolor and fillcolor.
color(colorstring), color((r,g,b)), color(r,g,b)
inputs as in pencolor, set both, fillcolor and pencolor,
to the given value.
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.

If turtleshape is a polygon, outline and interior of that polygon
is drawn with the newly set colors.
For more info see: pencolor, fillcolor

Example:
>>> color(‘red‘, ‘green‘)
>>> color()
(‘red‘, ‘green‘)
>>> colormode(255)
>>> color((40, 80, 120), (160, 200, 240))
>>> color()
(‘#285078‘, ‘#a0c8f0‘)

colormode(cmode=None)
Return the colormode or set it to 1.0 or 255.

Optional argument:
cmode -- one of the values 1.0 or 255

r, g, b values of colortriples have to be in range 0..cmode.

Example:
>>> colormode()
1.0
>>> colormode(255)
>>> pencolor(240,160,80)

degrees(fullcircle=360.0)
Set angle measurement units to degrees.

Optional argument:
fullcircle - a number

Set angle measurement units, i. e. set number
of ‘degrees‘ for a full circle. Dafault value is
360 degrees.

Example:
>>> left(90)
>>> heading()
90

Change angle measurement unit to grad (also known as gon,
grade, or gradian and equals 1/100-th of the right angle.)
>>> degrees(400.0)
>>> heading()
100

delay(delay=None)
Return or set the drawing delay in milliseconds.

Optional argument:
delay -- positive integer

Example:
>>> delay(15)
>>> delay()
15

distance(x, y=None)
Return the distance from the turtle to (x,y) in turtle step units.

Arguments:
x -- a number or a pair/vector of numbers or a turtle instance
y -- a number None None

call: distance(x, y) # two coordinates
--or: distance((x, y)) # a pair (tuple) of coordinates
--or: distance(vec) # e.g. as returned by pos()
--or: distance(mypen) # where mypen is another turtle

Example:
>>> pos()
(0.00, 0.00)
>>> distance(30,40)
50.0
>>> pen = Turtle()
>>> pen.forward(77)
>>> distance(pen)
77.0

done = mainloop()
Starts event loop - calling Tkinter‘s mainloop function.

No argument.

Must be 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.

Example:
>>> mainloop()

dot(size=None, *color)
Draw a dot with diameter size, using color.

Optional arguments:
size -- an integer >= 1 (if given)
color -- a colorstring or a numeric color tuple

Draw a circular dot with diameter size, using color.
If size is not given, the maximum of pensize+4 and 2*pensize is used.

Example:
>>> dot()
>>> fd(50); dot(20, "blue"); fd(50)

down()
Pull the pen down -- drawing when moving.

Aliases: pendown | pd | down

No argument.

Example:
>>> pendown()

end_fill()
Fill the shape drawn after the call begin_fill().

No argument.

Example:
>>> color("black", "red")
>>> begin_fill()
>>> circle(60)
>>> end_fill()

end_poly()
Stop recording the vertices of a polygon.

No argument.

Stop recording the vertices of a polygon. Current turtle position is
last point of polygon. This will be connected with the first point.

Example:
>>> end_poly()

exitonclick()
Go into mainloop until the mouse is clicked.

No arguments.

Bind bye() method to mouseclick on TurtleScreen.
If "using_IDLE" - value in configuration dictionary is False
(default value), enter mainloop.
If IDLE with -n switch (no subprocess) is used, this value should be
set to True in turtle.cfg. In this case IDLE‘s mainloop
is active also for the client script.

This is a method of the Screen-class and not available for
TurtleScreen instances.

Example:
>>> exitonclick()

fd(distance)
Move the turtle forward by the specified distance.

Aliases: forward | fd

Argument:
distance -- a number (integer or float)

Move the turtle forward by the specified distance, in the direction
the turtle is headed.

Example:
>>> position()
(0.00, 0.00)
>>> forward(25)
>>> position()
(25.00,0.00)
>>> forward(-75)
>>> position()
(-50.00,0.00)

fillcolor(*args)
Return or set the fillcolor.

Arguments:
Four input formats are allowed:
- fillcolor()
Return the current fillcolor as color specification string,
possibly in hex-number format (see example).
May be used as input to another color/pencolor/fillcolor call.
- fillcolor(colorstring)
s is a Tk color specification string, such as "red" or "yellow"
- fillcolor((r, g, b))
*a tuple* of r, g, and b, which represent, an RGB color,
and each of r, g, and b are in the range 0..colormode,
where colormode is either 1.0 or 255
- fillcolor(r, g, b)
r, g, and b represent an RGB color, and each of r, g, and b
are in the range 0..colormode

If turtleshape is a polygon, the interior of that polygon is drawn
with the newly set fillcolor.

Example:
>>> fillcolor(‘violet‘)
>>> col = pencolor()
>>> fillcolor(col)
>>> fillcolor(0, .5, 0)

filling()
Return fillstate (True if filling, False else).

No argument.

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

forward(distance)
Move the turtle forward by the specified distance.

Aliases: forward | fd

Argument:
distance -- a number (integer or float)

Move the turtle forward by the specified distance, in the direction
the turtle is headed.

Example:
>>> position()
(0.00, 0.00)
>>> forward(25)
>>> position()
(25.00,0.00)
>>> forward(-75)
>>> position()
(-50.00,0.00)

get_poly()
Return the lastly recorded polygon.

No argument.

Example:
>>> p = get_poly()
>>> register_shape("myFavouriteShape", p)

get_shapepoly()
Return the current shape polygon as tuple of coordinate pairs.

No argument.

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

getcanvas()
Return the Canvas of this TurtleScreen.

No argument.

Example:
>>> cv = getcanvas()
>>> cv
<turtle.ScrolledCanvas instance at 0x010742D8>

getpen()
Return the Turtleobject itself.

No argument.

Only reasonable use: as a function to return the ‘anonymous turtle‘:

Example:
>>> pet = getturtle()
>>> pet.fd(50)
>>> pet
<Turtle object at 0x0187D810>
>>> turtles()
[<Turtle object at 0x0187D810>]

getscreen()
Return the TurtleScreen object, the turtle is drawing on.

No argument.

Return the TurtleScreen object, the turtle is drawing on.
So TurtleScreen-methods can be called for that object.

Example:
>>> ts = getscreen()
>>> ts
<TurtleScreen object at 0x0106B770>
>>> ts.bgcolor("pink")

getshapes()
Return a list of names of all currently available turtle shapes.

No argument.

Example:
>>> getshapes()
[‘arrow‘, ‘blank‘, ‘circle‘, ... , ‘turtle‘]

getturtle()
Return the Turtleobject itself.

No argument.

Only reasonable use: as a function to return the ‘anonymous turtle‘:

Example:
>>> pet = getturtle()
>>> pet.fd(50)
>>> pet
<Turtle object at 0x0187D810>
>>> turtles()
[<Turtle object at 0x0187D810>]

goto(x, y=None)
Move turtle to an absolute position.

Aliases: setpos | setposition | goto:

Arguments:
x -- a number or a pair/vector of numbers
y -- a number None

call: goto(x, y) # two coordinates
--or: goto((x, y)) # a pair (tuple) of coordinates
--or: goto(vec) # e.g. as returned by pos()

Move turtle to an absolute position. If the pen is down,
a line will be drawn. The turtle‘s orientation does not change.

Example:
>>> tp = pos()
>>> tp
(0.00, 0.00)
>>> setpos(60,30)
>>> pos()
(60.00,30.00)
>>> setpos((20,80))
>>> pos()
(20.00,80.00)
>>> setpos(tp)
>>> pos()
(0.00,0.00)

heading()
Return the turtle‘s current heading.

No arguments.

Example:
>>> left(67)
>>> heading()
67.0

hideturtle()
Makes the turtle invisible.

Aliases: hideturtle | ht

No argument.

It‘s a good idea to do this while you‘re in the
middle of a complicated drawing, because hiding
the turtle speeds up the drawing observably.

Example:
>>> hideturtle()

home()
Move turtle to the origin - coordinates (0,0).

No arguments.

Move turtle to the origin - coordinates (0,0) and set its
heading to its start-orientation (which depends on mode).

Example:
>>> home()

ht()
Makes the turtle invisible.

Aliases: hideturtle | ht

No argument.

It‘s a good idea to do this while you‘re in the
middle of a complicated drawing, because hiding
the turtle speeds up the drawing observably.

Example:
>>> hideturtle()

isdown()
Return True if pen is down, False if it‘s up.

No argument.

Example:
>>> penup()
>>> isdown()
False
>>> pendown()
>>> isdown()
True

isvisible()
Return True if the Turtle is shown, False if it‘s hidden.

No argument.

Example:
>>> hideturtle()
>>> print isvisible():
False

left(angle)
Turn turtle left by angle units.

Aliases: left | lt

Argument:
angle -- a number (integer or float)

Turn turtle left by angle units. (Units are by default degrees,
but can be set via the degrees() and radians() functions.)
Angle orientation depends on mode. (See this.)

Example:
>>> heading()
22.0
>>> left(45)
>>> heading()
67.0

listen(xdummy=None, ydummy=None)
Set focus on TurtleScreen (in order to collect key-events)

No arguments.
Dummy arguments are provided in order
to be able to pass listen to the onclick method.

Example:
>>> listen()

lt(angle)
Turn turtle left by angle units.

Aliases: left | lt

Argument:
angle -- a number (integer or float)

Turn turtle left by angle units. (Units are by default degrees,
but can be set via the degrees() and radians() functions.)
Angle orientation depends on mode. (See this.)

Example:
>>> heading()
22.0
>>> left(45)
>>> heading()
67.0

mainloop()
Starts event loop - calling Tkinter‘s mainloop function.

No argument.

Must be 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.

Example:
>>> mainloop()

mode(mode=None)
Set turtle-mode (‘standard‘, ‘logo‘ or ‘world‘) and perform reset.

Optional argument:
mode -- one of the strings ‘standard‘, ‘logo‘ or ‘world‘

Mode ‘standard‘ is compatible with turtle.py.
Mode ‘logo‘ is compatible with most Logo-Turtle-Graphics.
Mode ‘world‘ uses userdefined ‘worldcoordinates‘. *Attention*: in
this mode angles appear distorted if x/y unit-ratio doesn‘t equal 1.
If mode is not given, return the current mode.

Mode Initial turtle heading positive angles
------------|-------------------------|-------------------
‘standard‘ to the right (east) counterclockwise
‘logo‘ upward (north) clockwise

Examples:
>>> mode(‘logo‘) # resets turtle heading to north
>>> mode()
‘logo‘

numinput(title, prompt, default=None, minval=None, maxval=None)
Pop up a dialog window for input of a number.

Arguments: 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 imput
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.

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

onclick(fun, btn=1, add=None)
Bind fun to mouse-click event on this turtle on canvas.

Arguments:
fun -- a function with two arguments, to which will be assigned
the coordinates of the clicked point on the canvas.
num -- number of the mouse-button defaults to 1 (left mouse button).
add -- True or False. If True, new binding will be added, otherwise
it will replace a former binding.

Example for the anonymous turtle, i. e. the procedural way:

>>> def turn(x, y):
... left(360)
...
>>> onclick(turn) # Now clicking into the turtle will turn it.
>>> onclick(None) # event-binding will be removed

ondrag(fun, btn=1, add=None)
Bind fun to mouse-move event on this turtle on canvas.

Arguments:
fun -- a function with two arguments, to which will be assigned
the coordinates of the clicked point on the canvas.
num -- number of the mouse-button defaults to 1 (left mouse button).

Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that

Example:
>>> ondrag(goto)

Subsequently clicking and dragging a Turtle will move it
across the screen thereby producing handdrawings (if pen is
down).

onkey(fun, key)
Bind fun to key-release event of key.

Arguments:
fun -- a function with no arguments
key -- a string: key (e.g. "a") or key-symbol (e.g. "space")

In order to be able to register key-events, TurtleScreen
must have focus. (See method listen.)

Example:

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

Subsequently the turtle can be moved by repeatedly pressing
the up-arrow key, consequently drawing a hexagon

onkeypress(fun, key=None)
Bind fun to key-press event of key if key is given,
or to any key-press-event if no key is given.

Arguments:
fun -- a function with no arguments
key -- a string: key (e.g. "a") or key-symbol (e.g. "space")

In order to be able to register key-events, TurtleScreen
must have focus. (See method listen.)

Example (for a TurtleScreen instance named screen
and a Turtle instance named turtle):

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

Subsequently the turtle can be moved by repeatedly pressing
the up-arrow key, or by keeping pressed the up-arrow key.
consequently drawing a hexagon.

onkeyrelease(fun, key)
Bind fun to key-release event of key.

Arguments:
fun -- a function with no arguments
key -- a string: key (e.g. "a") or key-symbol (e.g. "space")

In order to be able to register key-events, TurtleScreen
must have focus. (See method listen.)

Example:

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

Subsequently the turtle can be moved by repeatedly pressing
the up-arrow key, consequently drawing a hexagon

onrelease(fun, btn=1, add=None)
Bind fun to mouse-button-release event on this turtle on canvas.

Arguments:
fun -- a function with two arguments, to which will be assigned
the coordinates of the clicked point on the canvas.
num -- number of the mouse-button defaults to 1 (left mouse button).

Example (for a MyTurtle instance named joe):
>>> class MyTurtle(Turtle):
... def glow(self,x,y):
... self.fillcolor("red")
... def unglow(self,x,y):
... self.fillcolor("")
...
>>> joe = MyTurtle()
>>> joe.onclick(joe.glow)
>>> joe.onrelease(joe.unglow)

Clicking on joe turns fillcolor red, unclicking turns it to
transparent.

onscreenclick(fun, btn=1, add=None)
Bind fun to mouse-click event on canvas.

Arguments:
fun -- a function with two arguments, the coordinates of the
clicked point on the canvas.
num -- the number of the mouse-button, defaults to 1

Example (for a TurtleScreen instance named screen)

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

ontimer(fun, t=0)
Install a timer, which calls fun after t milliseconds.

Arguments:
fun -- a function with no arguments.
t -- a number >= 0

Example:

>>> running = True
>>> def f():
... if running:
... fd(50)
... lt(60)
... ontimer(f, 250)
...
>>> f() # makes the turtle marching around
>>> running = False

pd()
Pull the pen down -- drawing when moving.

Aliases: pendown | pd | down

No argument.

Example:
>>> pendown()

pen(pen=None, **pendict)
Return or set the pen‘s attributes.

Arguments:
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
"resizemode" : "auto" or "user" or "noresize"
"stretchfactor": (positive number, positive number)
"shearfactor": number
"outline" : positive number
"tilt" : number

This dictionary can be used as argument for a subsequent
pen()-call to restore the former pen-state. 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.

Examples:
>>> pen(fillcolor="black", pencolor="red", pensize=10)
>>> pen()
{‘pensize‘: 10, ‘shown‘: True, ‘resizemode‘: ‘auto‘, ‘outline‘: 1,
‘pencolor‘: ‘red‘, ‘pendown‘: True, ‘fillcolor‘: ‘black‘,
‘stretchfactor‘: (1,1), ‘speed‘: 3, ‘shearfactor‘: 0.0}
>>> penstate=pen()
>>> color("yellow","")
>>> penup()
>>> pen()
{‘pensize‘: 10, ‘shown‘: True, ‘resizemode‘: ‘auto‘, ‘outline‘: 1,
‘pencolor‘: ‘yellow‘, ‘pendown‘: False, ‘fillcolor‘: ‘‘,
‘stretchfactor‘: (1,1), ‘speed‘: 3, ‘shearfactor‘: 0.0}
>>> p.pen(penstate, fillcolor="green")
>>> p.pen()
{‘pensize‘: 10, ‘shown‘: True, ‘resizemode‘: ‘auto‘, ‘outline‘: 1,
‘pencolor‘: ‘red‘, ‘pendown‘: True, ‘fillcolor‘: ‘green‘,
‘stretchfactor‘: (1,1), ‘speed‘: 3, ‘shearfactor‘: 0.0}

pencolor(*args)
Return or set the pencolor.

Arguments:
Four input formats are allowed:
- pencolor()
Return the current pencolor as color specification string,
possibly in hex-number format (see example).
May be used as input to another color/pencolor/fillcolor call.
- pencolor(colorstring)
s is a Tk color specification string, such as "red" or "yellow"
- pencolor((r, g, b))
*a tuple* of r, g, and b, which represent, an RGB color,
and each of r, g, and b are in the range 0..colormode,
where colormode is either 1.0 or 255
- pencolor(r, g, b)
r, g, and b represent an RGB color, and each of r, g, and b
are in the range 0..colormode

If turtleshape is a polygon, the outline of that polygon is drawn
with the newly set pencolor.

Example:
>>> pencolor(‘brown‘)
>>> tup = (0.2, 0.8, 0.55)
>>> pencolor(tup)
>>> pencolor()
‘#33cc8c‘

pendown()
Pull the pen down -- drawing when moving.

Aliases: pendown | pd | down

No argument.

Example:
>>> pendown()

pensize(width=None)
Set or return the line thickness.

Aliases: pensize | width

Argument:
width -- positive number

Set the line thickness to width or return it. If resizemode is set
to "auto" and turtleshape is a polygon, that polygon is drawn with
the same line thickness. If no argument is given, current pensize
is returned.

Example:
>>> pensize()
1
>>> pensize(10) # from here on lines of width 10 are drawn

penup()
Pull the pen up -- no drawing when moving.

Aliases: penup | pu | up

No argument

Example:
>>> penup()

pos()
Return the turtle‘s current location (x,y), as a Vec2D-vector.

Aliases: pos | position

No arguments.

Example:
>>> pos()
(0.00, 240.00)

position()
Return the turtle‘s current location (x,y), as a Vec2D-vector.

Aliases: pos | position

No arguments.

Example:
>>> pos()
(0.00, 240.00)

pu()
Pull the pen up -- no drawing when moving.

Aliases: penup | pu | up

No argument

Example:
>>> penup()

radians()
Set the angle measurement units to radians.

No arguments.

Example:
>>> heading()
90
>>> radians()
>>> heading()
1.5707963267948966

register_shape(name, shape=None)
Adds a turtle shape to TurtleScreen‘s shapelist.

Arguments:
(1) name is the name of a gif-file and shape is None.
Installs the corresponding image shape.
!! 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. Installs the corresponding
polygon shape
(3) name is an arbitrary string and shape is a
(compound) Shape object. Installs the corresponding
compound shape.
To use a shape, you have to issue the command shape(shapename).

call: register_shape("turtle.gif")
--or: register_shape("tri", ((0,0), (10,10), (-10,10)))

Example:
>>> register_shape("triangle", ((5,-3),(0,5),(-5,-3)))

reset()
Delete the turtle‘s drawings and restore its default values.

No argument.

Delete the turtle‘s drawings from the screen, re-center the turtle
and set variables to the default values.

Example:
>>> position()
(0.00,-22.00)
>>> heading()
100.0
>>> reset()
>>> position()
(0.00,0.00)
>>> heading()
0.0

resetscreen()
Reset all Turtles on the Screen to their initial state.

No argument.

Example:
>>> reset()

resizemode(rmode=None)
Set resizemode to one of the values: "auto", "user", "noresize".

(Optional) Argument:
rmode -- one of the strings "auto", "user", "noresize"

Different resizemodes have the following effects:
- "auto" adapts the appearance of the turtle
corresponding to the value of pensize.
- "user" adapts the appearance of the turtle according to the
values of stretchfactor and outlinewidth (outline),
which are set by shapesize()
- "noresize" no adaption of the turtle‘s appearance takes place.
If no argument is given, return current resizemode.
resizemode("user") is called by a call of shapesize with arguments.

Examples:
>>> resizemode("noresize")
>>> resizemode()
‘noresize‘

right(angle)
Turn turtle right by angle units.

Aliases: right | rt

Argument:
angle -- a number (integer or float)

Turn turtle right by angle units. (Units are by default degrees,
but can be set via the degrees() and radians() functions.)
Angle orientation depends on mode. (See this.)

Example:
>>> heading()
22.0
>>> right(45)
>>> heading()
337.0

rt(angle)
Turn turtle right by angle units.

Aliases: right | rt

Argument:
angle -- a number (integer or float)

Turn turtle right by angle units. (Units are by default degrees,
but can be set via the degrees() and radians() functions.)
Angle orientation depends on mode. (See this.)

Example:
>>> heading()
22.0
>>> right(45)
>>> heading()
337.0

screensize(canvwidth=None, canvheight=None, bg=None)
Resize the canvas the turtles are drawing on.

Optional arguments:
canvwidth -- positive integer, new width of canvas in pixels
canvheight -- positive integer, new height of canvas in pixels
bg -- colorstring or color-tuple, new backgroundcolor
If no arguments are given, return current (canvaswidth, canvasheight)

Do not alter the drawing window. To observe hidden parts of
the canvas use the scrollbars. (Can make visible those parts
of a drawing, which were outside the canvas before!)

Example (for a Turtle instance named turtle):
>>> turtle.screensize(2000,1500)
>>> # e.g. to search for an erroneously escaped turtle ;-)

seth(to_angle)
Set the orientation of the turtle to to_angle.

Aliases: setheading | seth

Argument:
to_angle -- a number (integer or float)

Set the orientation of the turtle to 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

Example:
>>> setheading(90)
>>> heading()
90

setheading(to_angle)
Set the orientation of the turtle to to_angle.

Aliases: setheading | seth

Argument:
to_angle -- a number (integer or float)

Set the orientation of the turtle to 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

Example:
>>> setheading(90)
>>> heading()
90

setpos(x, y=None)
Move turtle to an absolute position.

Aliases: setpos | setposition | goto:

Arguments:
x -- a number or a pair/vector of numbers
y -- a number None

call: goto(x, y) # two coordinates
--or: goto((x, y)) # a pair (tuple) of coordinates
--or: goto(vec) # e.g. as returned by pos()

Move turtle to an absolute position. If the pen is down,
a line will be drawn. The turtle‘s orientation does not change.

Example:
>>> tp = pos()
>>> tp
(0.00, 0.00)
>>> setpos(60,30)
>>> pos()
(60.00,30.00)
>>> setpos((20,80))
>>> pos()
(20.00,80.00)
>>> setpos(tp)
>>> pos()
(0.00,0.00)

setposition(x, y=None)
Move turtle to an absolute position.

Aliases: setpos | setposition | goto:

Arguments:
x -- a number or a pair/vector of numbers
y -- a number None

call: goto(x, y) # two coordinates
--or: goto((x, y)) # a pair (tuple) of coordinates
--or: goto(vec) # e.g. as returned by pos()

Move turtle to an absolute position. If the pen is down,
a line will be drawn. The turtle‘s orientation does not change.

Example:
>>> tp = pos()
>>> tp
(0.00, 0.00)
>>> setpos(60,30)
>>> pos()
(60.00,30.00)
>>> setpos((20,80))
>>> pos()
(20.00,80.00)
>>> setpos(tp)
>>> pos()
(0.00,0.00)

settiltangle(angle)
Rotate the turtleshape to point in the specified direction

Argument: angle -- number

Rotate the turtleshape to point in the direction specified by angle,
regardless of its current tilt-angle. DO NOT change the turtle‘s
heading (direction of movement).

Examples:
>>> shape("circle")
>>> shapesize(5,2)
>>> settiltangle(45)
>>> stamp()
>>> fd(50)
>>> settiltangle(-45)
>>> stamp()
>>> fd(50)

setundobuffer(size)
Set or disable undobuffer.

Argument:
size -- an integer or None

If size is an integer an empty undobuffer of given size is installed.
Size gives the maximum number of turtle-actions that can be undone
by the undo() function.
If size is None, no undobuffer is present.

Example:
>>> setundobuffer(42)

setup(width=0.5, height=0.75, startx=None, starty=None)
Set the size and position of the main window.

Arguments:
width: as integer a size in pixels, as float a fraction of the
Default is 50% of
height: as integer the height in pixels, as float a fraction of the
Default is 75% of
startx: if positive, starting position in pixels from the left
edge of the screen, if negative from the right edge
Default, startx=None is to center window horizontally.
starty: if positive, starting position in pixels from the top
edge of the screen, if negative from the bottom edge
Default, starty=None is to center window vertically.

Examples:
>>> setup (width=200, height=200, startx=0, starty=0)

sets window to 200x200 pixels, in upper left of screen

>>> setup(width=.75, height=0.5, startx=None, starty=None)

sets window to 75% of screen by 50% of screen and centers

setworldcoordinates(llx, lly, urx, ury)
Set up a user defined coordinate-system.

Arguments:
llx -- a number, x-coordinate of lower left corner of canvas
lly -- a number, y-coordinate of lower left corner of canvas
urx -- a number, x-coordinate of upper right corner of canvas
ury -- a number, y-coordinate of upper right corner of canvas

Set up user coodinat-system and switch to mode ‘world‘ if necessary.
This performs a reset. If mode ‘world‘ is already active,
all drawings are redrawn according to the new coordinates.

But ATTENTION: in user-defined coordinatesystems angles may appear
distorted. (see Screen.mode())

Example:
>>> setworldcoordinates(-10,-0.5,50,1.5)
>>> for _ in range(36):
... left(10)
... forward(0.5)

setx(x)
Set the turtle‘s first coordinate to x

Argument:
x -- a number (integer or float)

Set the turtle‘s first coordinate to x, leave second coordinate
unchanged.

Example:
>>> position()
(0.00, 240.00)
>>> setx(10)
>>> position()
(10.00, 240.00)

sety(y)
Set the turtle‘s second coordinate to y

Argument:
y -- a number (integer or float)

Set the turtle‘s first coordinate to x, second coordinate remains
unchanged.

Example:
>>> position()
(0.00, 40.00)
>>> sety(-10)
>>> position()
(0.00, -10.00)

shape(name=None)
Set turtle shape to shape with given name / return current shapename.

Optional argument:
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.
Shape with name must exist in the TurtleScreen‘s shape dictionary.
Initially there are the following polygon shapes:
‘arrow‘, ‘turtle‘, ‘circle‘, ‘square‘, ‘triangle‘, ‘classic‘.
To learn about how to deal with shapes see Screen-method register_shape.

Example:
>>> shape()
‘arrow‘
>>> shape("turtle")
>>> shape()
‘turtle‘

shapesize(stretch_wid=None, stretch_len=None, outline=None)
Set/return turtle‘s stretchfactors/outline. Set resizemode to "user".

Optional arguments:
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".
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 orientation
stretch_len is stretchfactor in direction of turtles orientation.
outline determines the width of the shapes‘s outline.

Examples:
>>> resizemode("user")
>>> shapesize(5, 5, 12)
>>> shapesize(outline=8)

shapetransform(t11=None, t12=None, t21=None, t22=None)
Set or return the current transformation matrix of the turtle shape.

Optional arguments: t11, t12, t21, t22 -- numbers.

If none of the matrix elements are given, return the transformation
matrix.
Otherwise set the given elements and transform the turtleshape
according to the matrix consisting of first row t11, t12 and
second row t21, 22.
Modify stretchfactor, shearfactor and tiltangle according to the
given matrix.

Examples:
>>> shape("square")
>>> shapesize(4,2)
>>> shearfactor(-0.5)
>>> shapetransform()
(4.0, -1.0, -0.0, 2.0)

shearfactor(shear=None)
Set or return the current shearfactor.

Optional argument: shear -- number, tangent of the shear angle

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.

Examples:
>>> shape("circle")
>>> shapesize(5,2)
>>> shearfactor(0.5)
>>> shearfactor()
>>> 0.5

showturtle()
Makes the turtle visible.

Aliases: showturtle | st

No argument.

Example:
>>> hideturtle()
>>> showturtle()

speed(speed=None)
Return or set the turtle‘s speed.

Optional argument:
speed -- an integer in the range 0..10 or a speedstring (see below)

Set the turtle‘s speed to an integer value in the range 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.
Speedstrings are mapped to speedvalues in the following way:
‘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.

Attention:
speed = 0 : *no* animation takes place. forward/back makes turtle jump
and likewise left/right make the turtle turn instantly.

Example:
>>> speed(3)

st()
Makes the turtle visible.

Aliases: showturtle | st

No argument.

Example:
>>> hideturtle()
>>> showturtle()

stamp()
Stamp a copy of the turtleshape onto the canvas and return its id.

No argument.

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

Example:
>>> color("blue")
>>> stamp()
13
>>> fd(50)

textinput(title, prompt)
Pop up a dialog window for input of a string.

Arguments: 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.

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

tilt(angle)
Rotate the turtleshape by angle.

Argument:
angle - a number

Rotate the turtleshape by angle from its current tilt-angle,
but do NOT change the turtle‘s heading (direction of movement).

Examples:
>>> shape("circle")
>>> shapesize(5,2)
>>> tilt(30)
>>> fd(50)
>>> tilt(30)
>>> fd(50)

tiltangle(angle=None)
Set or return the current tilt-angle.

Optional argument: angle -- number

Rotate the turtleshape to point in the direction specified by angle,
regardless of its current tilt-angle. 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).

Deprecated since Python 3.1

Examples:
>>> shape("circle")
>>> shapesize(5,2)
>>> tilt(45)
>>> tiltangle()

title(titlestring)
Set title of turtle-window

Argument:
titlestring -- a string, to appear in the titlebar of the
turtle graphics window.

This is a method of Screen-class. Not available for TurtleScreen-
objects.

Example:
>>> title("Welcome to the turtle-zoo!")

towards(x, y=None)
Return the angle of the line from the turtle‘s position to (x, y).

Arguments:
x -- a number or a pair/vector of numbers or a turtle instance
y -- a number None None

call: distance(x, y) # two coordinates
--or: distance((x, y)) # a pair (tuple) of coordinates
--or: distance(vec) # e.g. as returned by pos()
--or: distance(mypen) # where mypen is another turtle

Return the angle, between the line from turtle-position to position
specified by x, y and the turtle‘s start orientation. (Depends on
modes - "standard" or "logo")

Example:
>>> pos()
(10.00, 10.00)
>>> towards(0,0)
225.0

tracer(n=None, delay=None)
Turns turtle animation on/off and set delay for update drawings.

Optional arguments:
n -- nonnegative integer
delay -- nonnegative integer

If n is given, only each n-th regular screen update is really performed.
(Can be used to accelerate the drawing of complex graphics.)
Second arguments sets delay value (see RawTurtle.delay())

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

turtles()
Return the list of turtles on the

Example:
>>> turtles()
[<turtle.Turtle object at 0x00E11FB0>]

turtlesize(stretch_wid=None, stretch_len=None, outline=None)
Set/return turtle‘s stretchfactors/outline. Set resizemode to "user".

Optional arguments:
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".
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 orientation
stretch_len is stretchfactor in direction of turtles orientation.
outline determines the width of the shapes‘s outline.

Examples:
>>> resizemode("user")
>>> shapesize(5, 5, 12)
>>> shapesize(outline=8)

undo()
undo (repeatedly) the last turtle action.

No argument.

undo (repeatedly) the last turtle action.
Number of available undo actions is determined by the size of
the undobuffer.

Example:
>>> for i in range(4):
... fd(50); lt(80)
...
>>> for i in range(8):
... undo()
...

undobufferentries()
Return count of entries in the undobuffer.

No argument.

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

up()
Pull the pen up -- no drawing when moving.

Aliases: penup | pu | up

No argument

Example:
>>> penup()

update()
Perform a TurtleScreen update.

width(width=None)
Set or return the line thickness.

Aliases: pensize | width

Argument:
width -- positive number

Set the line thickness to width or return it. If resizemode is set
to "auto" and turtleshape is a polygon, that polygon is drawn with
the same line thickness. If no argument is given, current pensize
is returned.

Example:
>>> pensize()
1
>>> pensize(10) # from here on lines of width 10 are drawn

window_height()
Return the height of the turtle window.

Example:
>>> window_height()
480

window_width()
Return the width of the turtle window.

Example:
>>> window_width()
640

write(arg, move=False, align=‘left‘, font=(‘Arial‘, 8, ‘normal‘))
Write text at the current turtle position.

Arguments:
arg -- info, which is to be written to the TurtleScreen
move (optional) -- True/False
align (optional) -- one of the strings "left", "center" or right"
font (optional) -- a triple (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.
If move is True, the pen is moved to the bottom-right corner
of the text. By default, move is False.

Example:
>>> write(‘Home = ‘, True, align="center")
>>> write((0,0), True)

write_docstringdict(filename=‘turtle_docstringdict‘)
Create and write docstring-dictionary to file.

Optional argument:
filename -- a string, used as filename
default value is turtle_docstringdict

Has to be called explicitly, (not used by the turtle-graphics classes)
The docstring dictionary will be written to the Python script <filname>.py
It is intended to serve as a template for translation of the docstrings
into different languages.

xcor()
Return the turtle‘s x coordinate.

No arguments.

Example:
>>> reset()
>>> left(60)
>>> forward(100)
>>> print xcor()
50.0

ycor()
Return the turtle‘s y coordinate
---
No arguments.

Example:
>>> reset()
>>> left(60)
>>> forward(100)
>>> print ycor()
86.6025403784

DATA
__all__ = [‘ScrolledCanvas‘, ‘TurtleScreen‘, ‘Screen‘, ‘RawTurtle‘, ‘T...

FILE
d:\python3.7\lib\turtle.py

原文地址:https://www.cnblogs.com/whxutao/p/9781086.html

时间: 2024-10-03 07:10:56

python标准库《turtle》的相关文章

Python标准库(机器汉化)

Python标准库 虽然"Python语言参考"描述了Python语言的确切语法和语义,但该库参考手册描述了使用Python分发的标准库.它还介绍了Python发行版中通常包含的一些可选组件. Python的标准库非常广泛,提供了下面列出的长表所示的各种设施.该库包含内置模块(用C语言编写),提供对Python程序员无法访问的系统功能(如文件I / O)的访问,以及使用Python编写的模块,为出现的许多问题提供标准化的解决方案日常编程.其中一些模块是明确设计的,通过将特定平台抽象为平

Python 标准库一览(Python进阶学习)

转自:http://blog.csdn.net/jurbo/article/details/52334345 写这个的起因是,还是因为在做Python challenge的时候,有的时候想解决问题,连应该用哪个类库都不知道,还要去百度(我不信就我一个人那么尴尬TvT) 好像自从学习了基础的Python 语法,看了几本Python经典的书,知道了一些常见的类库.在几本语法应用熟练的情况下,如果不做题,像是无法显著的提高自己的知识储备了(所以叫你去做python challenge啊,什么都不会~~

python标准库Beautiful Soup与MongoDb爬喜马拉雅电台的总结

Beautiful Soup标准库是一个可以从HTML/XML文件中提取数据的Python库,它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式,Beautiful Soup将会节省数小时的工作时间.pymongo标准库是MongoDb NoSql数据库与python语言之间的桥梁,通过pymongo将数据保存到MongoDb中.结合使用这两者来爬去喜马拉雅电台的数据... Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是

Python标准库 (pickle包,cPickle包)

在之前对Python对象的介绍中 (面向对象的基本概念,面向对象的进一步拓展),我提到过Python"一切皆对象"的哲学,在Python中,无论是变量还是函数,都是一个对象.当Python运行时,对象存储在内存中,随时等待系统的调用.然而,内存里的数据会随着计算机关机和消失,如何将对象保存到文件,并储存在硬盘上呢? 计算机的内存中存储的是二进制的序列 (当然,在Linux眼中,是文本流).我们可以直接将某个对象所对应位置的数据抓取下来,转换成文本流 (这个过程叫做serialize),

Python标准库14 数据库 (sqlite3)

Python标准库14 数据库 (sqlite3) 作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python自带一个轻量级的关系型数据库SQLite.这一数据库使用SQL语言.SQLite作为后端数据库,可以搭配Python建网站,或者制作有数据存储需求的工具.SQLite还在其它领域有广泛的应用,比如HTML5和移动端.Python标准库中的sqlite3提供该数据库的接口. 我将创建一个简单的关系型数据库,为一个书店存

【python标准库学习】thread,threading(二)多线程同步

继上一篇介绍了python的多线程和基本用法.也说到了python中多线程中的同步锁,这篇就来看看python中的多线程同步问题. 有时候很多个线程同时对一个资源进行修改,这个时候就容易发生错误,看看这个最简单的程序: import thread, time count = 0 def addCount(): global count for i in range(100000): count += 1 for i in range(10): thread.start_new_thread(ad

【python标准库学习】thread,threading(一)多线程的介绍和使用

在单个程序中我们经常用多线程来处理不同的工作,尤其是有的工作需要等,那么我们会新建一个线程去等然后执行某些操作,当做完事后线程退出被回收.当一个程序运行时,就会有一个进程被系统所创建,同时也会有一个线程运行,这个线程就是主线程main,在主线程中所创建的新的线程都是子线程,子线程通常都是做一些辅助的事.python中提供了thread和threading两个模块来支持多线程. python中使用线程有两种方式,第一种是用thread模块的start_new_thread函数,另一种是用threa

[python标准库]XML模块

1.什么是XML XML是可扩展标记语言(Extensible Markup Language)的缩写,其中的 标记(markup)是关键部分.您可以创建内容,然后使用限定标记标记它,从而使每个单词.短语或块成为可识别.可分类的信息. XML有以下几个特点. XML的设计宗旨是传输数据,而非显示数据. XML标签没有被预定义.您需要自行定义标签. XML被设计为具有自我描述性. XML是W3C的推荐标准. 其解析流程如下图: 2.常用解析XML的Python包 Python的标准库中,提供了6种

Python标准库04 文件管理 (部分os包,shutil包)

作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 在操作系统下,用户可以通过操作系统的命令来管理文件,参考linux文件管理相关命令.Python标准库则允许我们从Python内部管理文件.相同的目的,我们有了两条途径.尽管在Python调用标准库的方式不如操作系统命令直接,但有它自己的优势.你可以利用Python语言,并发挥其他Python工具,形成组合的文件管理功能.Python or Shell? 这是留给用户的选择.本文

[学习笔记] Python标准库简明教程 [转]

1 操作系统接口 os 模块提供了一系列与系统交互的模块: >>> os.getcwd() # Return the current working directory '/home/minix/Documents/Note/Programming/python/lib1' >>> os.chdir('~/python') # Change current working directory Traceback (most recent call last): File