非常教程

Python参考手册

Tk

turtle

1.介绍

Turtle graphics是向孩子们介绍编程的一种流行方式。它是Wally Feurzig和Seymour Papert于1966年开发的原始Logo编程语言的一部分。

想象一下robotic turtle从x-y平面的(0,0)开始。 在导入乌龟后,给它命令turtle.forward(15),它在它面对的方向上移动(在屏幕上)15个像素,在它移动时画一条线。 给它命令turtle.right(25),它顺时针旋转25度。

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

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

它试图保持旧乌龟模块的优点,并且(几乎)100%兼容它。这首先意味着学习程序员可以交互式地使用所有命令,类和方法-n

turtle模块以面向对象和面向过程的方式提供turtle图形基元。 由于它使用Tkinter作为底层图形,因此需要安装Tk支持的Python版本。

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

TurtleScreen类将绘图窗口定义为绘图turtle的操场。 它的构造函数需要一个Tkinter.Canvas或一个ScrolledCanvas作为参数。 当应用程序使用turtle时应该使用它。

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

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

  1. RawTurtle(别名:)RawPen定义了绘制的Turtle对象TurtleScreen。它的构造函数需要Canvas,ScrolledCanvas或TurtleScreen作为参数,所以RawTurtle对象知道在哪里绘制。

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

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

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

要使用多个turtle,必须使用面向对象的界面。

注意

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

2.概述了可用的turtle和屏幕方法

2.1 turtle方法

Turtle motionMove and drawTell Turtle's stateSetting and measurementPen control绘图状态颜色控制填充更多绘图控制驼背状态可见性外观使用事件特殊的turtle法

2.2 TurtleScreen / Screen的方法

窗口控制动画控制使用屏幕事件设置和特殊方法特定于屏幕的方法

3. RawTurtle / Turtle的方法和相应的功能

本节中的大部分示例都涉及一个叫做Turtle的实例。

3.1 turtle议案

turtle.forward(distance)turtle.fd(distance)

参数:

距离 - 一个数字(整数或浮点数)

turtle.back(distance)turtle.bk(distance)turtle.backward(distance)

参数:

距离 - 一个数字

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

参数:

角度 - 一个数字(整数或浮点数)

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

参数:

角度 - 一个数字(整数或浮点数)

turtle.goto(x, y=None)turtle.setpos(x, y=None)turtle.setposition(x, y=None)

参数:

x - 一个数字或一对数字y的数字 - 一个数字或无

  • x - 一个数字或一对数字
  • y - 一个数字或None
If _y_ is `None`, _x_ must be a pair of coordinates or a [`Vec2D`](about:blank#turtle.Vec2D) (e.g. as returned by [`pos()`](about:blank#turtle.pos)).

将turtle移到绝对位置。如果笔落下,画线。不要改变turtle的方向。

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

turtle.setx(x)

参数:

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

turtle.sety(y)

参数:

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

turtle.setheading(to_angle)turtle.seth(to_angle)

参数:

to_angle - 数字(整数或浮点数)

turtle.home()

将turtle移动到原点 - 坐标(0,0) - 并将其标题设置为其起始方向(取决于模式,请参阅参考资料mode())。

>>> turtle.heading()
90.0
>>> turtle.position()
(0.00,-10.00)
>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0

turtle.circle(radius, extent=None, steps=None)

参数:

半径 - 数字范围 - 数字(或无)步骤 - 整数(或无)

  • 半径 - 一个数字
  • 程度 - 一个数字(或None
  • 步骤 - 整数(或None
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_.

由于圆是用刻有正多边形的近似值,所以数决定了要使用的步数。如果没有给出,它会自动计算。可用于绘制正多边形。

turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.0 >>> turtle.circle(50) >>> turtle.position() (-0.00,0.00) >>> turtle.heading() 0.0 >>> turtle.circle(120, 180) # draw a semicircle >>> turtle.position() (0.00,240.00) >>> turtle.heading() 180.0

turtle.dot(size=None, *color)

参数:

size - 一个整数> = 1(如果给定)color - 一个颜色字符串或一个数字颜色元组

  • 大小 - 一个整数> = 1(如果给出)
  • 颜色 - 颜色字符串或数字颜色元组
Draw a circular dot with diameter _size_, using _color_. If _size_ is not given, the maximum of pensize+4 and 2\*pensize is used.

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

在当前turtle位置上将turtle形状的副本印到画布上。返回该邮票的stamp_id,可以通过调用将其删除clearstamp(stamp_id)

>>> turtle.color("blue")
>>> turtle.stamp()
11
>>> turtle.fd(50)

turtle.clearstamp(stampid)

参数:

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

turtle.clearstamps(n=None)

参数:

n - 整数(或无)

turtle.undo()

撤消(重复)最后的turtle动作。可用撤销操作的数量由不可扩展器的大小决定。

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

turtle.speed(speed=None)

参数:

速度 - 范围为0..10的整数或速度串(见下文)

  • “fastest”: 0
  • “fast”: 10
  • “normal”: 6
  • “slow”: 3
  • “slowest”: 1

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

注意:速度 = 0意味着没有动画发生。向前/向后使turtle跳跃,同样向左/向右使turtle立即转动。

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

3.2。告诉turtle的状态

turtle.position()turtle.pos()

返回turtle的当前位置(x,y)(作为Vec2D矢量)。

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

turtle.towards(x, y=None)

参数:

x - 一个数字或一对数字或一个乌龟实例的向量y - 一个数字,如果x是一个数字,否则无

  • x - 一个数字或一对数字或一个turtle实例的向量
  • y - 如果x是数字,则为数字,否则None
Return the angle between the line from turtle position to position specified by (x,y), the vector or the other turtle. 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()

返回turtle的x坐标。

>>> turtle.home()
>>> turtle.left(50)
>>> turtle.forward(100)
>>> turtle.pos()
(64.28,76.60)
>>> print turtle.xcor()
64.2787609687

turtle.ycor()

返回turtle的y坐标。

>>> turtle.home()
>>> turtle.left(60)
>>> turtle.forward(100)
>>> print turtle.pos()
(50.00,86.60)
>>> print turtle.ycor()
86.6025403784

turtle.heading()

返回turtle的当前标题(值取决于turtle模式,请参阅mode())。

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

turtle.distance(x, y=None)

参数:

x - 一个数字或一对数字或一个乌龟实例的向量y - 一个数字,如果x是一个数字,否则无

  • x - 一个数字或一对数字或一个turtle实例的向量
  • y - 如果x是数字,则为数字,否则None
Return the distance from the turtle to (x,y), the given vector, or the given other turtle, in turtle step units.

turtle.home() >>> turtle.distance(30,40) 50.0 >>> turtle.distance((30,40)) 50.0 >>> joe = Turtle() >>> joe.forward(77) >>> turtle.distance(joe) 77.0

3.3 测量设置

turtle.degrees(fullcircle=360.0)

参数:

全圆 - 一个数字

turtle.radians()

将角度测量单位设置为弧度。相当于degrees(2*math.pi)

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

3.4 笔控制

3.4.1 绘图状态

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

拉下笔 - 移动时绘图。

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

拉起笔 - 移动时无图。

turtle.pensize(width=None)turtle.width(width=None)

参数:

宽度 - 一个正数

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

参数:

笔 - 包含部分或全部下列键的字典pendict - 一个或多个关键字参数,其中以下列出的键为关键字

  • - 包含部分或全部下列键的字典
  • pendict - 一个或多个关键字参数,下面列出的关键字为关键字
Return or set the pen’s attributes in a “pen-dictionary” with the following key/value pairs:
  • “显示”:真/假
  • “pendown”:真/假
  • “pencolor”:颜色字符串或颜色元组
  • “fillcolor”:颜色字符串或颜色元组
  • “pensize”:正数
  • “速度”:范围为0..10的数字
  • “resizemode”:“auto”或“user”或“noresize”
  • “stretchfactor”:(正数,正数)
  • “outline”:正数
  • “tilt”:数字

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

turtle.pen(fillcolor="black", pencolor="red", pensize=10) >>> sorted(turtle.pen().items()) ('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'), ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'), ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0) >>> penstate=turtle.pen() >>> turtle.color("yellow", "") >>> turtle.penup() >>> sorted(turtle.pen().items()) ('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow'), ('pendown', False), ('pensize', 10), ('resizemode', 'noresize'), ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0) >>> turtle.pen(penstate, fillcolor="green") >>> sorted(turtle.pen().items()) ('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red'), ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'), ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0)

turtle.isdown()

如果笔向下,则返回True; 如果笔向上,则返回False。

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

3.4.2 颜色控制

turtle.pencolor(*args)

返回或设置pencolor。

允许四种输入格式:

pencolor()将当前的pencolor作为颜色指定字符串或作为元组返回(请参见示例)。 可用作另一种颜色的输入/ pencolor / fillcolor call.pencolor(colorstring)将pencolor设置为诸如“red”,“yellow”或“#33cc8c”.pencolor(( r,g,b))将pencolor设置为由r,g和b的元组表示的RGB颜色。 pencolor(r,g,b)将pencolor设置为由r表示的RGB颜色,其中r,g和b必须位于0..colormode范围内,其中colormode为1.0或255(参见colormode() g和b。 r,g和b中的每一个都必须在0 ... colormode范围内。

如果turtleshape是多边形,则使用新设置的pencolor绘制该多边形的轮廓。

>>> colormode()
1.0
>>> turtle.pencolor()
'red'
>>> turtle.pencolor("brown")
>>> turtle.pencolor()
'brown'
>>> tup = (0.2, 0.8, 0.55)
>>> turtle.pencolor(tup)
>>> turtle.pencolor()
(0.2, 0.8, 0.5490196078431373)
>>> colormode(255)
>>> turtle.pencolor()
(51, 204, 140)
>>> turtle.pencolor('#32c18f')
>>> turtle.pencolor()
(50, 193, 143)

turtle.fillcolor(*args)

返回或设置fillcolor。

允许四种输入格式:

fillcolor()返回当前的fillcolor作为颜色规格字符串,可能以元组格式(请参阅示例)。 可用作另一种颜色的输入/ pencolor / fillcolor call.fillcolor(colorstring)将fillcolor设置为诸如“red”,“yellow”或“#33cc8c”.fillcolor(( r,g,b))将fillcolor设置为由r,g和b的元组表示的RGB颜色。 fillcolor(r,g,b)将fillcolor设置为由r表示的RGB颜色,其中,颜色模式为1.0或255(参见colormode() g和b。 r,g和b中的每一个都必须在0 ... colormode范围内。

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

>>> turtle.fillcolor("violet")
>>> turtle.fillcolor()
'violet'
>>> col = turtle.pencolor()
>>> col
(50, 193, 143)
>>> turtle.fillcolor(col)
>>> turtle.fillcolor()
(50, 193, 143)
>>> turtle.fillcolor('#ffffff')
>>> turtle.fillcolor()
(255, 255, 255)

turtle.color(*args)

返回或设置pencolor和fillcolor。

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

color()返回当前的pencolor和当前的fillcolor作为由pencolor()和fillcolor().color(colorstring),color((r,g,b))返回的颜色指定字符串或元组, g,b)如pencolor()中的输入,将fillcolor和pencolor设置为给定的值.color(colorstring1,colorstring2),color((r1,g1,b1),(r2,g2,b2))Equivalent 到pencolor(colorstring1)和fillcolor(colorstring2),并且类似地使用其他输入格式。

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

>>> turtle.color("red", "green")
>>> turtle.color()
('red', 'green')
>>> color("#285078", "#a0c8f0")
>>> color()
((40, 80, 120), (160, 200, 240))

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

3.4.3 填充

turtle.fill(flag)

参数:

标志 - 真/假(或分别为1/0)

turtle.begin_fill()

在绘制要填充的形状之前调用。相当于fill(True)

turtle.end_fill()

填写最后一次调用之后绘制的形状begin_fill()。相当于fill(False)

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

3.4.4 更多的绘图控制

turtle.reset()

从屏幕上删除turtle的图纸,重新将turtle居中并将变量设置为默认值。

>>> turtle.goto(0,-22)
>>> turtle.left(100)
>>> turtle.position()
(0.00,-22.00)
>>> turtle.heading()
100.0
>>> turtle.reset()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0

turtle.clear()

从屏幕上删除turtle的图纸。不要移动turtle。turtle的状态和位置以及其他turtle的图纸不受影响。

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

参数:

arg - 要写入TurtleScreen的对象移动 - True / False对齐 - 其中一个字符串“left”,“center”或right“font - 三元组(fontname,fontsize,fonttype)

  • arg - 要写入TurtleScreen的对象
  • move - 真/假
  • align - 其中一个字符串“左”,“中”或右“
  • font - 一个三元组(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`.

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

3.5 turtle状态

3.5.1 可见

turtle.hideturtle()turtle.ht()

使turtle无形。在做复杂绘图的过程中这样做是个好主意,因为隐藏turtle可以显着提高绘图速度。

>>> turtle.hideturtle()

turtle.showturtle()turtle.st()

使turtle可见。

>>> turtle.showturtle()

turtle.isvisible()

如果turtle显示则返回True,如果隐藏则返回False。

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

3.5.2 出现

turtle.shape(name=None)

参数:

名称 - 一个有效形状名称的字符串

turtle.resizemode(rmode=None)

参数:

rmode - 其中一个字符串“auto”,“user”,“noresize”

  • “auto”:根据pensize的值调整turtle的外观。
  • “用户”:根据由设置的stretchfactor和outlinewidth(outline)的值来调整turtle的外观shapesize()
  • “noresize”:没有适应turtle的外观发生。

resizemode(“user”)shapesize()在与参数一起使用时被调用。

turtle.resizemode() 'noresize' >>> turtle.resizemode("auto") >>> turtle.resizemode() 'auto'

turtle.shapesize(stretch_wid=None, stretch_len=None, outline=None)turtle.turtlesize(stretch_wid=None, stretch_len=None, outline=None)

参数:

stretch_wid - 正数stretch_len - 正数大纲 - 正数

  • stretch_wid - 正数
  • stretch_len - 正数
  • 大纲 - 正数
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 its orientation, _stretch\_len_ is stretchfactor in direction of its orientation, _outline_ determines the width of the shapes’s outline.

turtle.shapesize() (1, 1, 1) >>> turtle.resizemode("user") >>> turtle.shapesize(5, 5, 12) >>> turtle.shapesize() (5, 5, 12) >>> turtle.shapesize(outline=8) >>> turtle.shapesize() (5, 5, 8)

turtle.tilt(angle)

参数:

角度 - 一个数字

turtle.settiltangle(angle)

参数:

角度 - 一个数字

turtle.tiltangle()

返回当前的倾斜角度,即turtle的方向与turtle的方向(其移动方向)之间的角度。

>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(45)
>>> turtle.tiltangle()
45.0

3.6 使用事件

turtle.onclick(fun, btn=1, add=None)

参数:

fun - 一个带有两个参数的函数,将用画布上单击点的坐标调用num - 鼠标按钮的编号,默认为1(鼠标左键)add - True或False - 如果为True,则为新绑定将被添加,否则将取代以前的绑定

  • fun - 一个带有两个参数的函数,这些参数将与画布上单击点的坐标一起调用
  • num - 鼠标按钮的数量,默认为1(鼠标左键)
  • add - True或False - 如果为True,将添加新绑定,否则将替换以前的绑定
Bind _fun_ to mouse-click events on this turtle. If _fun_ is `None`, existing bindings are removed. 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)

参数:

fun - 一个带有两个参数的函数,将用画布上单击点的坐标调用num - 鼠标按钮的编号,默认为1(鼠标左键)add - True或False - 如果为True,则为新绑定将被添加,否则将取代以前的绑定

  • fun - 一个带有两个参数的函数,这些参数将与画布上单击点的坐标一起调用
  • num - 鼠标按钮的数量,默认为1(鼠标左键)
  • add - True或False - 如果为True,将添加新绑定,否则将替换以前的绑定
Bind _fun_ to mouse-button-release events on this turtle. If _fun_ is `None`, existing bindings are removed.

class MyTurtle(Turtle): ... def glow(self,x,y): ... self.fillcolor("red") ... def unglow(self,x,y): ... self.fillcolor("") ... >>> turtle = MyTurtle() >>> turtle.onclick(turtle.glow) # clicking on turtle turns fillcolor red, >>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.

turtle.ondrag(fun, btn=1, add=None)

参数:

fun - 一个带有两个参数的函数,将用画布上单击点的坐标调用num - 鼠标按钮的编号,默认为1(鼠标左键)add - True或False - 如果为True,则为新绑定将被添加,否则将取代以前的绑定

  • fun - 一个带有两个参数的函数,这些参数将与画布上单击点的坐标一起调用
  • num - 鼠标按钮的数量,默认为1(鼠标左键)
  • add - True或False - 如果为True,将添加新绑定,否则将替换以前的绑定
Bind _fun_ to mouse-move events on this turtle. If _fun_ is `None`, existing bindings are removed.

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

turtle.ondrag(turtle.goto)

随后,点击并拖动Turtle将在屏幕上移动,从而生成手绘图(如果笔落下)。

turtle.mainloop()turtle.done()

开始事件循环 - 调用Tkinter的mainloop函数。必须是Turtle图形程序中的最后一个语句。

>>> turtle.mainloop()

3.7 特殊的Turtle方法

turtle.begin_poly()

开始记录多边形的顶点。当前的Turtle位置是多边形的第一个顶点。

turtle.end_poly()

停止记录多边形的顶点。当前Turtle位置是多边形的最后一个顶点。这将与第一个顶点连接。

turtle.get_poly()

返回最后记录的多边形。

>>> turtle.home()
>>> turtle.begin_poly()
>>> turtle.fd(100)
>>> turtle.left(20)
>>> turtle.fd(30)
>>> turtle.left(60)
>>> turtle.fd(50)
>>> turtle.end_poly()
>>> p = turtle.get_poly()
>>> register_shape("myFavouriteShape", p)

turtle.clone()

创建并返回具有相同位置,标题和Turtle属性的Turtle的克隆。

>>> mick = Turtle()
>>> joe = mick.clone()

turtle.getturtle()turtle.getpen()

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

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

turtle.getscreen()

返回turtle正在绘制的TurtleScreen对象。 然后可以为该对象调用TurtleScreen方法。

>>> ts = turtle.getscreen()
>>> ts
<turtle._Screen object at 0x...>
>>> ts.bgcolor("pink")

turtle.setundobuffer(size)

参数:

大小 - 一个整数或None

turtle.undobufferentries()

返回undobuffer中的条目数。

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

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

相应的TurtleScreen方法的副本。

自2.6版以来已弃用。

turtle.window_width()turtle.window_height()

两者都是相应的TurtleScreen方法的副本。

自2.6版以来已弃用。

3.8 关于使用复合形状的附录

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

  1. 创建一个类型为“compound”的空Shape对象。
  1. 使用该addcomponent()方法,根据需要向该对象添加尽可能多的组件。

例如:

s = Shape("compound") >>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5)) >>> s.addcomponent(poly1, "red", "blue") >>> poly2 = ((0,0),(10,-5),(-10,-5)) >>> s.addcomponent(poly2, "blue", "red")

  1. 现在将Shape添加到屏幕的shapelist中并使用它:register_shape(“myshape”,s)>>> shape(“myshape”)注意Shape类由register_shape()方法以不同的方式在内部使用。只有在使用上面所示的复合形状时,应用程序员才能处理Shape类! TurtleScreen / Screen的方法和相应的函数本节中的大部分示例都涉及一个名为screen.4.1的TurtleScreen实例。 Window controlturtle.bgcolor(* args)参数:args - 颜色字符串或范围为0..colormode的三个数字或这样的数字的三元组.txt.txt(picname = None)参数:picname - 一个字符串,一个字符串的名称gif文件或“nopic”或Noneturtle.clear()turtle.clearscreen()从TurtleScreen中删除所有图形和所有的turtle。将现在为空的TurtleScreen重置为其初始状态:白色背景,无背景图像,无事件绑定和跟踪。注意此TurtleScreen方法仅在名称为clearscreen的情况下作为全局函数提供。全局函数清除是从Turtle方法派生的另一个方法clear.turtle.reset()turtle.resetscreen()将屏幕上的所有turtle重置为其初始状态。注意此TurtleScreen方法仅在名称为resetscreen的情况下作为全局函数提供。全局函数reset是从Turtle方法派生的另一个方法reset.turtle.screensize(canvwidth = None,canvheight = None,bg = None)参数:canvwidth - 正整数,画布的新宽度(以像素为单位)canvheight - 正整数,以像素为单位的画布bg - colorstring或color-tuple,新的背景颜色
  1. canvwidth - 正整数,画布的新宽度(以像素为单位)
  1. canvheight - 正整数,以像素为单位的画布新高度
  1. bg - colorstring或color-tuple,新的背景颜色
If no arguments are given, return current (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)

例如寻找一只错误转义的turtle ;-)

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

参数:

llx - 数字,画布左下角的x坐标lly - 数字,画布左下角的y坐标urx - 数字,画布右上角的x坐标ury - 数字,y坐标画布的右上角

  • llx - 一个数字,画布左下角的x坐标
  • lly - 画布左下角的数字,y坐标
  • urx - 一个数字,画布右上角的x坐标
  • ury - 画布右上角的数字,y坐标
Set up user-defined coordinate system and switch to mode “world” if necessary. This performs a `screen.reset()`. If mode “world” is already active, all drawings are redrawn according to the new coordinates.

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

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

4.2 动画控制

turtle.delay(delay=None)

参数:

延迟 - 正整数

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

参数:

n - 非负整数延迟 - 非负整数

  • n - 非负整数
  • 延迟 - 非负整数
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. (Can be used to accelerate the drawing of complex graphics.) Second argument sets delay value (see [`delay()`](about:blank#turtle.delay)).

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

turtle.update()

执行TurtleScreen更新。在示踪剂关闭时使用。

另见RawTurtle / Turtle方法speed()

4.3 使用屏幕事件

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

将注意力集中在TurtleScreen(为了收集关键事件)。提供虚拟参数是为了能够传递listen()给onclick方法。

turtle.onkey(fun, key)

参数:

fun - 一个没有参数或None键的函数 - 一个字符串:key(例如“a”)或者键符号(例如“space”)

  • fun - 一个没有参数或功能的函数None
  • - 字符串:键(例如“a”)或键符号(例如“空格”)
Bind _fun_ to key-release event of key. If _fun_ is `None`, event bindings are removed. Remark: in order to be able to register key-events, TurtleScreen must have the focus. (See method [`listen()`](about:blank#turtle.listen).)

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

turtle.onclick(fun, btn=1, add=None)turtle.onscreenclick(fun, btn=1, add=None)

参数:

fun - 一个带有两个参数的函数,将用画布上单击点的坐标调用num - 鼠标按钮的编号,默认为1(鼠标左键)add - True或False - 如果为True,则为新绑定将被添加,否则将取代以前的绑定

  • fun - 一个带有两个参数的函数,这些参数将与画布上单击点的坐标一起调用
  • num - 鼠标按钮的数量,默认为1(鼠标左键)
  • add - True或False - 如果为True,将添加新绑定,否则将替换以前的绑定
Bind _fun_ to mouse-click events on this screen. If _fun_ is `None`, existing bindings are removed.

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

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

注意

此TurtleScreen方法仅在名称下作为全局函数提供onscreenclick。全局函数onclick是从Turtle方法派生的另一个函数onclick

turtle.ontimer(fun, t=0)

参数:

fun - 一个没有参数的函数t - 一个数字> = 0

  • fun - 一个没有参数的函数
  • t - 数字> = 0
Install a timer that calls _fun_ after _t_ milliseconds.

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

4.4 设置和特殊方法

turtle.mode(mode=None)

参数:

模式 - 其中一个字符串“标准”,“标识”或“世界”

turtle.colormode(cmode=None)

参数:

cmode - 其中一个值为1.0或255

turtle.getcanvas()

返回此TurtleScreen的画布。对于知道如何处理Tkinter帆布的内部人士非常有用。

>>> cv = screen.getcanvas()
>>> cv
<turtle.ScrolledCanvas instance at 0x...>

turtle.getshapes()

返回所有当前可用turtle形状的名称列表。

>>> screen.getshapes()
['arrow', 'blank', 'circle', ..., 'turtle']

turtle.register_shape(name, shape=None)turtle.addshape(name, shape=None)

有三种不同的方法可以调用这个函数:

  1. name 是gif文件的名称,shapeNone:安装相应的图像shape.screen.register_shape(“turtle.gif”)注意转动turtle时图像形状旋转,因此它们不会显示turtle的标题!
  1. name是一个任意字符串,shape是坐标对的元组:安装相应的多边形形状。

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

名称是一个任意字符串,形状是一个(复合)形状对象:安装相应的复合形状。将turtle形添加到TurtleScreen的形状列表中。只有如此注册的形状可以通过发布命令形状(形状名称)来使用.turtle.turtles()返回屏幕上的turtle的列表。>>> for the screen in the screen.turtles():

... turtle.color(“red”)turtle.window_height()返回turtle窗口的高度>>> screen.window_height()

480turtle.window_width()返回turtle窗口的宽度>>> screen.window_width()

6404.5。特定于屏幕的方法,不从TurtleScreenturtle.bye()继承。关闭turtlegraphics window.turtle.exitonclick()在屏幕上绑定bye()方法以鼠标点击。如果配置字典中的值“using_IDLE”为False(默认值),也输入主循环。备注:如果使用带-n开关的IDLE(无子处理),则应在turtle.cfg中将此值设置为True。在这种情况下,IDLE自身的主循环也对客户端有效。script.turtle.setup(width = _CFG [“width”],height = _CFG [“height”],startx = _CFG [“leftright”],starty = _CFG [ topbottom“])设置主窗口的大小和位置。参数的默认值存储在配置字典中,并可通过turtle.cfg文件进行更改。参数:width - 如果是整数,则以像素为单位,如果是浮点,则为屏幕的一部分;默认是屏幕高度的50% - 如果是整数,高度以像素为单位,如果是浮点,则屏幕的一小部分;默认值是屏幕startx的75% - 如果是正值,则以屏幕左边缘的起始位置(以像素为单位),如果从右边缘为负,则如果为None,则中心窗口水平开始 - 如果为正值,则以屏幕,如果从底部边缘为负,如果无,垂直居中窗口

  1. 宽度 - 如果是整数,则以像素为单位,如果是浮点,屏幕的一部分; 默认为屏幕的50%
  1. 高度 - 如果是整数,高度以像素为单位,如果是浮点数,则为屏幕的一小部分; 默认是屏幕的75%
  1. startx - 如果为正值,则以屏幕左边缘的像素为起始位置,如果右边缘为负值,如果为None,中心窗口水平
  1. starty - 如果是正数,则从屏幕顶部边缘开始以像素为单位,如果底部边缘为负数,如果为None,垂直居中窗口
>>> screen.setup (width=200, height=200, startx=0, starty=0)
>>>              # sets window to 200x200 pixels, in upper left of screen
>>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
>>>              # sets window to 75% of screen by 50% of screen and centers

turtle.title(titlestring)

参数:

titlestring - 显示在 turtle 图形窗口的标题栏中的字符串

5.模块turtle的公共类

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

参数:

画布 - Tkinter.Canvas,ScrolledCanvas或TurtleScreen

class turtle.Turtle

RawTurtle的子类,具有相同的界面,但是Screen第一次需要时会自动创建一个默认对象。

class turtle.TurtleScreen(cv)

参数:

cv - 一个Tkinter.Canvas

class turtle.Screen

TurtleScreen的子类,添加了四种方法。

class turtle.ScrolledCanvas(master)

参数:

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

class turtle.Shape(type_, data)

Parameters:

type_ – one of the strings “polygon”, “image”, “compound”

  • poly - 一个多边形,即数字对的元组
  • 填充 - 聚合物 将填充的颜色
  • 轮廓 - poly的轮廓颜色(如果有的话)
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()

请参阅Excursus关于复合形状的使用。

class turtle.Vec2D(x, y)

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

Provides (for a, b vectors, k number):

  • a + b 矢量添加
  • a - b 矢量减法
  • a * b 内产物
  • k * aa * k标量相乘
  • abs(a) a的绝对值
  • a.rotate(angle) 回转

6.帮助和配置

6.1 如何使用帮助

Screen和Turtle类的公共方法通过文档大量记录。所以这些可以通过Python帮助工具作为在线帮助使用:

  • 使用IDLE时,工具提示将显示函数/方法调用中键入的文档字符串的签名和第一行。
  • 调用help()方法或函数显示文档字符串:

帮助(Screen.bgcolor)模块turtle中的方法bgcolor的帮助:bgcolor(self,* args)unbound turtle.Screen方法设置或返回TurtleScreen的backgroundcolor。参数(如果给出):一个颜色字符串或范围为0 ... colormode的三个数字或这种数字的三元组。>>> screen.bgcolor(“orange”)>>> screen.bgcolor()“orange”>>> screen.bgcolor(0.5,0,0.5)>>> screen.bgcolor()“#800080”>>>帮助(Turtle.penup)模块turtle中的方法penup的帮助:penup(self)unbound turtle.Turtle方法拉起笔 - 移动时不绘制。别名:penup | pu | up没有参数>>> turtle.penup()

从方法派生的函数的docstrings有一个修改后的形式:help(bgcolor)帮助模块turtle中的函数bgcolor:bgcolor(* args)设置或返回TurtleScreen的backgroundcolor。

参数(如果给出):一个颜色字符串或范围为0 ... colormode的三个数字或这种数字的三元组。

示例:: >>> bgcolor(“orange”)>>> bgcolor()“orange”>>> bgcolor(0.5,0,0.5)>>> bgcolor()“#800080”>>> help(penup)

帮助on模块中的函数penup turtle:penup()将笔向上拉 - 移动时不绘制。别名:penup | pu | up没有参数例如:>>> penup()这些修改后的文档字符串会与导入时从方法派生的函数定义一起自动创建。文档字符串翻译成不同的语言有一个实用程序来创建一个字典,其中的关键字是方法名称,其值是类的公共方法的文档字符串和Turtle.turtle.write_docstringdict(filename =“turtle_docstringdict”)参数:filename - 一个字符串,用作文件名如果您(或您的学生)希望在您的母语中使用带有联机帮助的turtle,则必须翻译文档字符串并将结果文件保存为例如turtle_docstringdict_german.py。如果在turtle.cfg文件中有适当的条目,则此字典将在导入时读入,并将取代原来的英文文档字符串。在撰写本文时,有德文和意大利文的docstring字典。 (请向glingl@aon.at。)6.3。如何配置屏幕和turtle内置的默认配置模仿旧turtle模块的外观和行为,以保持与它最好的兼容性。如果您想使用不同的配置,更好地反映此模块的功能或更好的符合您的需求,例如在教室中使用时,可以准备一个配置文件turtle.cfg,它将在导入时读取并根据其设置修改配置。内置配置将对应于以下turtle.cfg:width = 0.5

height = 0.75

leftright = None

topbottom = None

canvwidth = 400

canvheight = 300

mode = standard

colormode = 1.0

delay = 10

undobuffersize = 1000

shape = classic

pencolor = black

fillcolor = black

resizemode = noresize

visible = True

language = english

exampleturtle = turtle

examplescreen = screen

title = Python Turtle Graphics

using_IDLE = FalseShort explanation of selected entries:

  • 前四行对应于该Screen.setup()方法的参数。
  • 第5行和第6行对应于方法的参数Screen.screensize()
  • 形状 可以是任何内置形状,例如:箭头,乌龟等。欲了解更多信息,请尝试help(shape)
  • 如果你不想使用fillcolor(即使 turtle 透明),你必须写fillcolor = ""(但所有非空字符串不得在cfg文件中有引号)。
  • 如果你想反映 turtle 的状态,你必须使用resizemode = auto
  • 如果你设置了例如 language = italian docstringdict turtle_docstringdict_italian.py将在导入时加载(如果存在于导入路径中,例如与turtle相同的目录中)。
  • 条目exampleturtleexamplescreen定义了这些对象在文档中出现的名称。方法文档字符串到函数文档字符串的转换将从文档字符串中删除这些名称。
  • using_IDLE:如果您经常使用IDLE及其-n开关(“无子进程”),则将其设置为True。 这会阻止exitonclick()进入主循环。

在存储turtle的目录中可以有一个turtle.cfg文件,并且在当前工作目录中有一个额外的文件。 后者将覆盖第一个的设置。

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

7.演示脚本

Demo/turtle源分布目录中的turtledemo目录中有一组演示脚本。

它包含:

  • 一组15个演示脚本,演示新模块的不同功能 turtle
  • 一个演示查看器turtleDemo.py,可用于查看脚本的源代码并同时运行它们。可以通过示例菜单访问14个示例; 它们全部也可以独立运行。
  • 这个例子turtledemo_two_canvases.py演示了在turtle 模块中同时使用两个画布。因此它只能独立运行。
  • turtle.cfg这个目录中有一个文件,它也是如何编写和使用这些文件的例子。

演示文稿是:

名称

描述

特征

bytedesign

complex classical turtlegraphics pattern

tracer(), delay, update()

chaos

graphs Verhulst dynamics, shows that computer’s computations can generate results sometimes against the common sense expectations

world coordinates

clock

analog clock showing time of your computer

turtles as clock’s hands, ontimer

colormixer

experiment with r, g, b

ondrag()

fractalcurves

Hilbert & Koch curves

recursion

lindenmayer

ethnomathematics (indian kolams)

L-System

minimal_hanoi

Towers of Hanoi

Rectangular Turtles as Hanoi discs (shape, shapesize)

paint

super minimalistic drawing program

onclick()

peace

elementary

turtle: appearance and animation

penrose

aperiodic tiling with kites and darts

stamp()

planet_and_moon

simulation of gravitational system

compound shapes, Vec2D

tree

a (graphical) breadth first tree (using generators)

clone()

wikipedia

a pattern from the wikipedia article on turtle graphics

clone(), undo()

yingyang

another elementary example

circle()

Python

Python 是一种面向对象的解释型计算机程序设计语言,由荷兰人 Guido van Rossum 于1989年发明,第一个公开发行版发行于1991年。 Python 是纯粹的自由软件, 源代码和解释器 CPython 遵循 GPL 协议。Python 语法简洁清晰,特色之一是强制用空白符( white space )作为语句缩进。

主页 https://www.python.org/
源码 https://github.com/python/cpython
版本 2.7
发布版本 2.7.13

Python目录

1.内置常量 | Built-in Constants
2.内置例外 | Built-in Exceptions
3.内置函数 | Built-in Functions
4.内置类型 | Built-in Types
5.编译器 | Compiler
6.加密 | Cryptography
7.数据压缩 | Data Compression
8.数据持久性 | Data Persistence
9.数据类型 | Data Types
10.调试和分析 | Debugging & Profiling
11.开发工具 | Development Tools
12.文件和目录访问 | File & Directory Access
13.文件格式 | File Formats
14.构架 | Frameworks
15.输入 | Importing
16.输入/输出 | Input/ouput
17.国际化 | Internationalization
18.网络 | Internet
19.网络数据 | Internet Data
20.翻译 | Interpreters
21.语言 | Language
22.记录 | Logging
23.Mac OS
24.MS Windows
25.多媒体 | Multimedia
26.联网 | Networking
27.数字与数学 | Numeric & Mathematical
28.操作系统 | Operating System
29.可选操作系统 | Optional Operating System
30.限制执行 | Restricted Execution
31.运行 | Runtime
32.SGI IRIX
33.软件包装与分销 | Software Packaging & Distribution
34.字符串 | String
35.结构化标记 | Structured Markup
36.Tk
37.Unix
38.Python 简介
39.Python pass 语句
40.Python 循环嵌套
41.Python 运算符
42.Python log10() 函数
43.Python log() 函数
44.Python floor() 函数
45.Python fabs() 函数
46.Python exp() 函数
47.Python cmp() 函数
48.Python ceil() 函数
49.Python abs() 函数
50.Python Number(数字)
51.Python pow() 函数
52.Python modf() 函数
53.Python min() 函数
54.Python max() 函数
55.Python asin() 函数
56.Python acos() 函数
57.Python uniform() 函数
58.Python shuffle() 函数
59.Python seed() 函数
60.Python random() 函数
61.Python randrange() 函数
62.Python choice() 函数
63.Python sqrt() 函数
64.Python round() 函数
65.Python radians() 函数
66.Python degrees() 函数
67.Python tan() 函数
68.Python sin() 函数
69.Python hypot() 函数
70.Python cos() 函数
71.Python atan2() 函数
72.Python atan() 函数
73.Python 元组
74.Python 列表(List)
75.Python 字符串
76.Python 字典(Dictionary)
77.Python 日期和时间
78.Python 函数
79.Python 模块
80.Python capitalize()方法
81.Python center()方法
82.Python count() 方法
83.Python expandtabs()方法
84.Python endswith()方法
85.Python encode()方法
86.Python decode()方法
87.Python find()方法
88.Python index()方法
89.Python 异常处理
90.Python isspace()方法
91.Python isnumeric()方法
92.Python islower()方法
93.Python isdigit()方法
94.Python isalpha()方法
95.Python isalnum()方法
96.Python isupper()方法
97.Python istitle()方法
98.Python min()方法
99.Python max()方法
100.Python maketrans()方法