在python turtle graphics绘制的图形_Python——Turtle绘图/图形库

关于绘制图形库turtle

#画布上,默认有一个坐标原点为画布中心的坐标轴(0,0),默认"standard"模式坐标原点上有一只面朝x轴正方向小乌龟

一:海龟箭头Turtle相关方法

#############################

#1.绘制的运动 #

#############################

a).移动和绘制

#turtle.forward(distance) | turtle.fd(distance)

#画笔向绘制方向的当前方向移动distance(integer or float)的pixels距离,

#例如:

turtle.fd(150)

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

# 画笔向绘制方向的相反方向移动distance(integer or float)的pixels距离

# 例如:

turtle.backward(200)

# turtle.right(angle) | turtle.rt(angle)

# 绘制方向向右旋转angle度

# 例如:

turtle.rt(45)

# turtle.left(angle) | turtle.lt(angle)

# 绘制方向向左旋转angle度

# 例如:

turtle.lt(45)

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

# 移动到绝对位置,如果画笔按下,就画线

# 参数x(a number or a pair/vector of numbers)

# 参数y(a number or None)

# 如果y为None,x必须是a pair of coordinates or a Vec2D

# 例如:

turtle.setpos((20,80))

turtle.setposition(120,20)

turtle.goto(60,30)

# turtle.setx(x)

# y纵向坐标不变,更改x横向坐标,x(integer or float)

# 例如:

turtle.setx(15)

# turtle.sety(y)

# x横向坐标不变,更改y纵向坐标,y(integer or float)

# 例如:

turtle.sety(15)

# turtle.seth(to_angle) | turtle.setheading(to_angle)

# 将方向设置成to_angle.to_angle(integer or float)to_angle的值在不同模式下含义如下

"standard"模式逆时针 "logo"模式顺时针

0 - east 0 - north

90 - north 90 - east

180 - west 180 - south

270 - south 270 - west

如下图“standard”模式时(默认0时表示x方向向右即向东);“logo”模式时(默认0时表示y方向向上即向北)

y“logo”时

^

|

|

|

(0,0)——————> x“standard”时

# 例如:

# “standard”模式时角度为逆时针,所以90度表示向北;logo”模式时角度为顺时针,所以90度表示向东

turtle.setheading(90)

# turtle.home()

# 将位置和方向恢复到初始状态,位置初始坐标为(0,0),方向初始为("standard"模式为right向右即东,"logo"模式是up向上即北)

# 例如:

turtle.home()

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

# 按给定的半径画圆,当前位置为圆的初始端点

Parameters:

radius(a number,圆半径,为正数则逆时针画,为负数则顺时针画,方向随着轨迹的变化而变化)

extent(a number or None,一个角度,决定哪部分圆圈被绘制,不提供extent表示画完整的圆)

steps(an integer or None,指定半径radius前提下,完成extent的角度时,分了几步,如画正5边形时turtle.circle(40, None, 5))

# 例如:

copycode.gif

turtle.home()

# 当前位置(0,0)开始逆时针画半径为30的圆

turtle.circle(30)

# 逆时针画半径为50的半圆

turtle.circle(50, 180)

# 方向值为180,“standard”模式时方向向左,“logo”模式方向向下

print(turtle.heading())

turtle.circle(-50, 180)

print(turtle.heading())

# 逆时针方向半径为40画五边形(5步画接近整圆的图形)

turtle.circle(40, None, 5)

copycode.gif

# turtle.dot(size=None, *color)

# 按给定直径size画圆点(None[未提供时取pensize+4 和 2*pensize中的最大值] 或 >= 1的整数),color圆点颜色

# 例如:

copycode.gif

turtle.home()

# 当前画笔大小为1

print(turtle.pensize())

# 未提供取最大直径值为pensize+4 = 5

turtle.dot()

turtle.fd(50)

# 以直径为5画蓝色圆点

turtle.dot(5, "blue")

turtle.fd(50)

# 以直径为20画红色圆点

turtle.dot(20, "red")

turtle.fd(50)

print(turtle.position())

print(turtle.heading())

copycode.gif

# turtle.stamp()和turtle.clearstamp(stamp_id)和turtle.clearstamps(n=None)

# turtle.stamp()是在当前位置拷贝一份此时箭头的形状,返回一个stamp_id(int型),

# turtle.clearstamp(stamp_id)用来删除指定stamp_id的箭头形状

# turtle.clearstamps(n=None),n为None时表示删除所有拷贝的箭头形状;为0不删除;n > 0 表示删除前n个,n < 0 表示删除后n个

# 例如:

copycode.gif

# 画笔颜色设成红色

turtle.color("red")

num = 0

while num < 5:

# 当前位置拷贝一份箭头形状

stamp_id = turtle.stamp()

turtle.fd(50)

num += 1

# 改变画笔颜色为黑

turtle.color("black")

# 删除拷贝的箭头形状(此处id最后一次复制的stamp_id)

turtle.clearstamp(stamp_id)

# 删除前1个

turtle.clearstamps(1)

# 删除后1个

turtle.clearstamps(-1)

# 全部删除

turtle.clearstamps()

# 不删除

# turtle.clearstamps(0)

copycode.gif

# turtle.undo()

# (每调用一次就)撤销最后的一次动作,需要撤销所有可通过while turtle.undobufferentries(),turtle.undobufferentries()返回当前可撤销次数

# 例如:

# 一直撤销最后一个动作直到不可撤销

while turtle.undobufferentries():

# 撤销最后的一次动作

turtle.undo()

# turtle.speed(speed=None)

Parameters:

peed为0-10的整数(1-10越来越快,0表示最快,参数为小数会被自动置为整数)或如下内置的速度字符串,如果>10或小于0.5则被置为0;为>=0.5的小数时被置为四舍五入的值。speed未设置则返回当前速度

# 内置的速度字符串:

“fastest”: 0

“fast”: 10

“normal”: 6

“slow”: 3

“slowest”: 1

# 例如:

copycode.gif

# 速度为0,表示速度最快

turtle.speed(0)

# <0.5速度会被置为0,表示速度最快

turtle.speed(0.4)

# >10速度会被置为0,表示速度最快

turtle.speed(20)

# 速度字符串fastest,表示速度最快

turtle.speed("fastest")

# 速度最慢

turtle.speed("slowest")

# 速度为9

turtle.speed(9)

copycode.gif

b).获取(海龟)箭头的状态

# position() | pos()

# 返回(海龟)箭头当前位置坐标

# 例如:

turtle.pos()

# turtle.towards(x, y=None)

# 返回(海龟)箭头当前位置指向(x,y)位置连线的向量的角度(取决于当前模式,“standard”/”world”默认方向向右(即东)逆时针开始;“logo”模式默认方向向上(即北)顺时针开始)

Parameters:

x:x可以是一个number或一个pair/vector of numbers或一个turtle instance

y:x是一个number,y就是一个number;否则y为None

# 例如:

copycode.gif

turtle.goto(20, 20)

# 移动后,位置为(20,20),两个向量分别是(20,20)点到(0, 0)点的向量和(20, 20)点到箭头当前方向的向量("standard"模式默认向右,逆时针算角度,"logo"模式默认向上,顺时针算角度)

angle = turtle.towards(0, 0)

print("两向量角度:", angle)

# turtle.towards((0, 0), None)

angle = turtle.towards((0, 0))

print("两向量角度:", angle)

# turtle箭头当前位置与turtle1箭头当前位置连线的向量到turtle箭头当前位置与turtle当前方向连线的向量角度

turtle1 = turtle.Turtle()

turtle1.setpos(0, 0)

angle = turtle.towards(turtle1)

# "standard"模式逆时针算角度,所以towards()后的角度angle是225,不是135

print("两向量角度:", angle)

copycode.gif

# turtle.xcor() 和 turtle.ycor()

# turtle.xcor()是返回(海龟)箭头的x坐标,turtle.ycor()是返回(海龟)箭头的y坐标

# 例如:

copycode.gif

turtle.lt(50)

turtle.fd(100)

# 打印箭头当前坐标(64.28,76.60)

print(turtle.pos())

# 原数据64.27876096865394,保留5位后打印64.27876

print(round(turtle.xcor(), 5))

# 原数据76.60444431189781,保留5位后打印76.60444

print(round(turtle.ycor(), 5))

copycode.gif

# turtle.heading()

# 返回当前箭头方向角度,取决于当前模式mode,“standard”模式时默认方向向右逆时针计算角度;“logo”模式默认方向向上,顺时针计算角度

# 例如:

见turtle.circle中的例子

# turtle.distance(x, y=None)

# 返回当前(海龟)箭头坐标与坐标(x,y)间距离或当前(海龟)箭头坐标与另一个(海龟)箭头坐标间距离

Parameters:

x:x可以是一个number或一个pair/vector of numbers或一个turtle instance

y:x是一个number,y就是一个number;否则y为None

# 例如:

copycode.gif

turtle.home()

# 距离为50

print(turtle.distance(30,40))

# 距离为50

print(turtle.distance((30,40)))

joe = turtle.Turtle()

joe.setpos(30, 40)

# 距离为50

print(turtle.distance(joe))

copycode.gif

# c).设置与测量

# turtle.degrees(fullcircle=360.0) 和 turtle.radians()

# turtle.degrees表示设置一个完整圆的“度数”。默认值为360度,参数fullcircle(number类型),如果是360度时的90度,假如改成整圆为400度则此时角度应该是90/360*400

# turtle.radians()表示将一个完整圆的“度数”设置成2π,如果是360度时的90度则此时角度应该是90/360*(2π)

# 例如:

copycode.gif

turtle.home()

turtle.left(90)

# 输出(360份里的90份)90.0

print(turtle.heading())

# 将一个完整圆的“度数”从360度改成400度

turtle.degrees(400.0)

# 输出(400份里的100份)100.0

print(turtle.heading())

# 将一个完整圆的“度数”设置成360度

turtle.degrees(360)

# 输出(360份里的90份)90.0

print(turtle.heading())

turtle.radians()

# 输出(2π份里的1.5707963267948966份)1.5707963267948966

print(turtle.heading())

copycode.gif

#############################

# 2.画笔控制 #

#############################

# a).画笔绘制状态

# 旧方法 turtle.penup() | turtle.up() | turtle.pu()

# 画笔抬起,此时移动不会进行绘制操作

# 例如:

turtle.pu()

# 旧方法 turtle.pendown() | turtle.down() | turtle.pd()

# 画笔按下,此时移动会进行绘制操作

# 例如:

turtle.pd()

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

# 设置或返回线的粗细(width=None时表示返回,不为None表示设置),注意如果resizemode设置成"auto"并且绘制的是多边形,则多边形绘制时使用相同的线条粗细

# 例如:

# 设置线条粗细为5

turtle.pensize(5)

# 返回线条粗细为5

turtle.pensize()

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

# 设置或返回画笔字典中对应的画笔属性(一个键值对)

Parameters:

(pendict)画笔字典键值对如下

“fillcolor”: color-string or color-tuple

“outline”: positive number

“pencolor”: color-string or color-tuple

“pendown”: True/False

“pensize”: positive number

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

“shearfactor”: number

“shown”: True/False

“speed”: number in range 0..10

“stretchfactor”: (positive number, positive number)

“tilt”: number

# 例如:

copycode.gif

# 打印{'shown': True, 'pendown': True, 'pencolor': 'black', 'fillcolor': 'black', 'pensize': 1, 'speed': 3, 'resizemode': 'noresize', 'stretchfactor': (1.0, 1.0), 'shearfactor': 0.0, 'outline': 1, 'tilt': 0.0}

print(turtle.pen())

turtle.pen(fillcolor="black", pencolor="red", pensize=10)

# 打印排序后的为 [('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'), ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'), ('shearfactor', 0.0), ('shown', True), ('speed', 3), ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)]

print(sorted(turtle.pen().items()))

turtle.fd(100)

penstate=turtle.pen()

turtle.pen(penstate, fillcolor="green")

copycode.gif

# turtle.isdown()

# 获取画笔是否按下,按下返回True,否则返回False

# 例如:

copycode.gif

turtle.pu()

# 打印False

print(turtle.isdown())

turtle.pd()

# 打印True

print(turtle.isdown())

copycode.gif

# b).画笔颜色控制

# turtle.pencolor(*args)

# 设置或返回画笔颜色(设置后海龟箭头的外轮廓也是这个颜色)

# 例如:

copycode.gif

# 返回画笔颜色

turtle.pencolor()

# pencolor(colorstring)语法设置画笔颜色

turtle.pencolor("red")

turtle.fd(50)

# pencolor(colorstring)语法设置画笔颜色

turtle.pencolor("#33cc8c")

turtle.fd(50)

# pencolor(r, g, b)或pencolor((r, g, b))语法设置画笔颜色,取决于颜色模式,colormode颜色模式取值1.0或255,colormode为1.0时r,g,b取值范围0-1.0小数;colormode为255时r,g,b取值范围0-255的整数

turtle.getscreen().colormode(1.0)

# 打印颜色模式为1.0

print(turtle.getscreen().colormode())

turtle.pencolor(0.1, 0.2, 0)

turtle.fd(50)

turtle.getscreen().colormode(255)

# 打印颜色模式为255

print(turtle.getscreen().colormode())

turtle.pencolor(30, 210, 180)

turtle.fd(50)

copycode.gif

# turtle.fillcolor(*args)

# 返回或设置画笔填充颜色(设置后海龟箭头内部填充也是这个颜色)

# 用法同turtle.pencolor(*args)方法

# 例如:

copycode.gif

print(turtle.fillcolor())

screen = turtle.getscreen()

# pencolor(colorstring)语法设置画笔颜色

turtle.fillcolor("red")

turtle.fd(50)

# fillcolor(colorstring)语法设置画笔颜色

turtle.fillcolor("#33cc8c")

turtle.fd(50)

# fillcolor(r, g, b)fillcolor((r, g, b))语法设置画笔颜色,取决于颜色模式,colormode颜色模式取值1.0或255,colormode为1.0时r,g,b取值范围0-1.0小数;colormode为255时r,g,b取值范围0-255的整数

screen.colormode(1.0)

# 打印颜色模式为1.0

print(screen.colormode())

turtle.fillcolor(0.1, 0.2, 0)

turtle.fd(50)

screen.colormode(255)

# 打印颜色模式为255

print(screen.colormode())

turtle.fillcolor(30, 210, 180)

turtle.fd(50)

copycode.gif

# turtle.color(*args)

# 设置或返回pencolor和fillcolor

# 例如:

copycode.gif

# 返回pencolor和fillcolor ('black','black')

print(turtle.color())

# color(colorstring)或color((r,g,b))或color(r,g,b)将pencolor和fillcolor都设置成红色

turtle.color("red")

# 返回pencolor和fillcolor ('red','red')

print(turtle.color())

# color(colorstring1, colorstring2)或color((r1,g1,b1), (r2,g2,b2))分别设置pencolor和fillcolor

turtle.color("red", "yellow")

# 返回pencolor和fillcolor ('red','yellow')

print(turtle.color())

turtle.color("#285078", "#a0c8f0")

# 返回pencolor和fillcolor ((0.1568627450980392, 0.3137254901960784, 0.47058823529411764), (0.6274509803921569, 0.7843137254901961, 0.9411764705882353))

print(turtle.color())

copycode.gif

# c).填充

# turtle.filling()返回填充状态(填充状态则返回True,否则返回False)、开始填充图形之前先调用turtle.begin_fill()、填充完图形后调用turtle.end_fill()

# 例如:

copycode.gif

# 返回False

print(turtle.filling())

# 绘制shape之前先准备开始fill

turtle.begin_fill()

# 返回True

print(turtle.filling())

turtle.circle(20, None, 6)

# 绘制完shape之后结束fill

turtle.end_fill()

# 返回False

print(turtle.filling())

copycode.gif

# d).更多的绘制控制,注意screen其实是TurtleScreen对象的实例,使用screen时要先通过screen = turtle.getscreen()得到

# turtle.reset() | turtle.resetscreen() | screen.reset() | screen.resetscreen()

# 清屏并将画笔位置和方向恢复到初始状态,保持画笔形状不变,即位置恢复到原点(0, 0)位置,"standard"/"world"模式方向也恢复到默认的向右,"logo"模式方向恢复到默认的向上

# 例如:

turtle.reset()

# turtle.clear() | turtle.clearscreen() | screen.clear() | screen.clearscreen()

# 清屏并且画笔形状也恢复默认,保持画笔位置和方向不变

# 例如:

turtle.clear()

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

Parameters:

arg – object to be written to the TurtleScreen 待绘制的文本

move – True/False 设置是否绘制

align – one of the strings “left”, “center” or right”设置文本下方初始位置

font – a triple (fontname, fontsize, fonttype) 设置字体

# 绘制文本

# 例如:

# 绘制文本“Home = ”,move为True表示画笔从文本下边align所在位置一直绘制到文本右下方,默认False不绘制

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

turtle.write((0,0), True)

#############################

# 3.绘制状态 #

#############################

# a).显示/隐藏

# turtle.hideturtle() | turtle.ht()

# 隐藏画笔(即海龟箭头),此时只要画笔是按下状态,虽然隐藏了但是还是能绘制图形的,复杂的快速绘图时效果显著

# 例如:

turtle.hideturtle()

# turtle.showturtle() | turtle.st()

# 显示画笔(即海龟箭头)

# 例如:

turtle.showturtle()

# turtle.isvisible()

# 返回(海龟)画笔当前是否是可见状态,可见返回True,否则返回False

# 例如:

copycode.gif

turtle.hideturtle()

# 返回False

print(turtle.isvisible())

turtle.showturtle()

# 返回True

print(turtle.isvisible())

copycode.gif

# b).外观

# turtle.shape(name=None)

Parameters:

name – 形状名,必须在TurtleScreen的形状字典中,如(粗大箭头1)“arrow”,(海龟箭头) “turtle”, (实心圆箭头)“circle”, (实心方形箭头)“square”, (粗大箭头2)“triangle”, 默认的箭头“classic”

# 设置或返回(海龟)画笔箭头形状名

# 例如:

# 打印 'classic'

print(turtle.shape())

turtle.shape("turtle")

# 打印 'turtle'

print(turtle.shape())

# turtle.resizemode(rmode=None)

Parameters:

rmode – “auto”, “user”, “noresize”,3选1,具体说明如下

“auto”: 此模式下(海龟)画笔箭头随 pensize变化而变化.

“user”: 此模式下(海龟)画笔箭头大小取决于【通过shapesize()进行设置的】.stretchfactor和outlinewidth (outline)的值

“noresize”:此模式下(海龟)画笔箭头大小不变

# 设置或返回(海龟)画笔箭头大小的缩放模式

# 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 shape轮廓宽度值

# 返回或设置画笔x/y方向拉伸值和(或)shape轮廓宽度,仅当resizemode为“user”模式时有效

# 例如:

copycode.gif

# 设置外轮廓颜色为red,填充色为black

turtle.pen(pencolor="red", fillcolor="black")

# 返回, (1.0, 1.0, 1)表示垂直方向缩放到原来为1倍,水平方向缩放到原来1倍,外轮廓宽度1

print(turtle.shapesize())

# 设置resizemode为"user"模式

turtle.resizemode("user")

# 表示垂直方向缩放到原来为5倍,水平方向缩放到原来5倍,外轮廓宽度12

turtle.shapesize(5, 5, 12)

# 返回, (5, 5, 12)

print(turtle.shapesize())

# 设置轮廓宽度为8

turtle.shapesize(outline=8)

# 返回,(5, 5, 8)

print(turtle.shapesize())

copycode.gif

# turtle.shearfactor(shear=None)

Parameters:

shear – number (optional)

# 设置或返回剪切因子,

# 例如:

copycode.gif

# 箭头改成圆形

turtle.shape("circle")

# 垂直缩放到5倍,水平缩放到2倍

turtle.shapesize(5, 2)

print(turtle.shearfactor())

# 创建另一个(海龟)箭头,和原来的拉开距离

tl = turtle.Turtle()

tl.pu()

tl.fd(100)

tl.pd()

tl.shape("circle")

# 垂直缩放到5倍,水平缩放到2倍

tl.shapesize(5, 2)

# 设置shearfactor为0.5

tl.shearfactor(0.5)

print(tl.shearfactor())

copycode.gif

# turtle.tilt(angle)

Parameters:

angle – a number 箭头图标在现有角度基础上再旋转的角度,比如当前为45度,此基础45度变成90度

# 保持箭头方向不变的前提下,旋转箭头形状

# 例如:

copycode.gif

# 清屏并恢复原始坐标位置(0,0)恢复默认方向向右

turtle.reset()

# 改变箭头形状为圆形

turtle.shape("circle")

# 垂直缩放到5倍,水平缩放到2倍

turtle.shapesize(5, 2)

# 保持方向向右,圆形箭头图标旋转45度

turtle.tilt(45)

# 画线

turtle.fd(100)

# 拷贝一份箭头形状

turtle.stamp()

# 保持方向向右,圆形箭头图标旋转45度

turtle.tilt(45)

# 画线

turtle.fd(100)

copycode.gif

# turtle.tiltangle(angle=None)

Parameters:

angle – a number 忽略箭头现在的旋转角度,旋转到指定的角度数,比如当前为45度,忽略此时角度45,直接旋转到45度

# 获取或设置(保持箭头方向不变的前提下,)旋转箭头形状的角度

# 例如:

copycode.gif

# 清屏并恢复原始坐标位置(0,0)恢复默认方向向右

turtle.reset()

# 改变箭头形状为圆形

turtle.shape("circle")

# 垂直缩放到5倍,水平缩放到2倍

turtle.shapesize(5, 2)

# 保持方向向右,圆形箭头图标旋转45度

turtle.tilt(45)

# 画线

turtle.fd(100)

# 拷贝一份箭头形状

turtle.stamp()

# 保持方向向右,忽略当前箭头旋转的角度,圆形箭头图标旋转到45度

turtle.tiltangle(45)

# 返回角度45度

print(turtle.tiltangle())

# 画线

turtle.fd(100)

copycode.gif

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

# 返回或设置箭头形状的当前变换矩阵

# 例如:

copycode.gif

# 返回 (1.0, 0.0, 0.0, 1.0)

print(turtle.shapetransform())

turtle.shape("square")

# 垂直方向缩放到4倍,水平缩放到2倍,正方形变长方形

turtle.shapesize(4, 2)

turtle.shearfactor(-0.5)

print(turtle.shapetransform())

copycode.gif

# turtle.get_shapepoly()

# 返回当前多边形的坐标对,一般用来定义一个新形状或作为一个复合形状的一部分

# 例如:

turtle.shape("square")

turtle.shapetransform(4, -1, 0, 2)

# 输出 ((50, -20), (30, 20), (-50, 20), (-30, -20))

print(turtle.get_shapepoly())

#############################

# 4.绘制使用的事件 #

#############################

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

Parameters:

fun – 一个有两个参数x,y的函数,画布上鼠标左键在当前海龟箭头位置按下时将点击的坐标作为参数,调用该方法

num – 鼠标按钮的数目,默认为1(鼠标左键)

add – True或False.如果是True,将添加一个新的绑定;否则将替换前绑定

# 画布上鼠标左键在当前海龟箭头位置按下时绑定一个函数;如果函数为None,则移除存在的绑定

# 例如:

copycode.gif

def turn(x, y):

turtle.lt(90)

# 打印当前坐标

print('x=', x, 'y=', y)

# 打印当前方向

print(turtle.heading())

# 清除绑定关系

turtle.onclick(None)

# 再次绑定

turtle.onclick(turn)

# 绑定turn方法

turtle.onclick(turn)

copycode.gif

# turtle.onrelease(fun, btn=1, add=None)

Parameters:

fun – 一个有两个参数x,y的函数,画布上鼠标左键在当前海龟箭头位置弹起时将点击的坐标作为参数,调用该方法

num – 鼠标按钮的数目,默认为1(鼠标左键)

add – True或False.如果是True,将添加一个新的绑定;否则将替换前绑定

# 画布上鼠标左键在当前海龟箭头位置弹起时绑定一个函数;如果函数为None,则移除存在的绑定

# 例如:

copycode.gif

def turn(x, y):

turtle.lt(90)

# 打印当前坐标

print('x=', x, 'y=', y)

print(turtle.heading())

# 清除绑定关系

turtle.onrelease(None)

# 再次绑定

turtle.onrelease(turn)

# 绑定turn方法

turtle.onrelease(turn)

copycode.gif

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

Parameters:

fun – 一个有两个参数x,y的函数,画布上鼠标左键在当前海龟箭头位置按下并拖动时将点击的坐标作为参数,调用该方法

num – 鼠标按钮的数目,默认为1(鼠标左键)

add – True或False.如果是True,将添加一个新的绑定;否则将替换前绑定

# 画布上鼠标左键在当前海龟箭头位置按下并拖动时绑定一个函数;如果函数为None,则移除存在的绑定

# 例如:

copycode.gif

def move(x, y):

# 海龟箭头移动到当前拖动位置

turtle.goto(x, y)

# 清除绑定关系

turtle.ondrag(None)

# 再次绑定

turtle.ondrag(move)

# 绑定turn方法

turtle.ondrag(move)

copycode.gif

#############################

# 5.特殊的绘制方法 #

#############################

# turtle.begin_poly()、turtle.end_poly()和turtle.get_poly()配合使用

# turtle.begin_poly()表示开始记录多边形第一个顶点

# turtle.end_poly()表示结束记录多边形顶点

# turtle.get_poly()表示获取最后记录的多边形

# 例如:

copycode.gif

turtle.home()

# 开始记录

turtle.begin_poly()

turtle.fd(100)

turtle.lt(20)

turtle.fd(30)

turtle.lt(60)

turtle.fd(50)

# 结束记录

turtle.end_poly()

# 返回记录的多边形

p = turtle.get_poly()

# ((0.00,0.00), (100.00,0.00), (128.19,10.26), (136.87,59.50))

print(p)

# 将“myFavouriteShape”Shape添加到TurtleScreen对象的shapelist中

turtle.register_shape("myFavouriteShape", p)

# 使用新添加的shape

turtle.shape("myFavouriteShape")

copycode.gif

# turtle.clone()

# 创建和返回具有相同位置、方向和海龟箭头属性的海龟的克隆

# 例如:

mick = turtle.Turtle()

joe = mick.clone()

# turtle.getturtle() | turtle.getpen()

# 返回当前海龟屏幕上第一个海龟对象本身

# 例如:

pet = turtle.getturtle()

pet.fd(50)

print(pet)

# turtle.getscreen()

# 返回绘制着海龟的海龟屏幕对象,获取该对象后就可以调用海龟屏幕对象的一些方法了

# 例如:

# 获取海龟屏幕TurtleScreen对象

ts = turtle.getscreen()

print(ts)

# 调用海龟屏幕对象的bgcolor方法,设置背景颜色为粉红色

ts.bgcolor("pink")

# turtle.setundobuffer(size)

Parameters:

size – an integer【设置undo()可撤销的最大次数】或None【禁用undo()撤销功能】

# 设置或禁用撤销功能, size为None表示禁用撤销功能;否则设置多大,就可以通过调用undo()方法撤销多少次

# 例如:

turtle.setundobuffer(42)

# turtle.undobufferentries()

# 获取当前剩余可撤销次数

# 例如:

while turtle.undobufferentries(): # 判断是否可撤销

turtle.undo() # 执行撤销操作

二:海龟屏幕(TurtleScreen/Screen)的相关方法

首先需要通过screen = turtle.getscreen()获取到海龟屏幕TurtleScreen的对象并赋值给变量screen,下文中screen均表示该海龟屏幕TurtleScreen的对象

a)Window Control窗口控制

# screen.bgcolor(*args)

Parameters:

args – 一个颜色字符串或3个范围是0-colormode的数字或三个元祖

# 设置或返回海龟屏幕TurtleScreen的背景色

# 例如:

copycode.gif

screen = turtle.getscreen()

screen.bgcolor("orange")

# 打印 'orange'

print(screen.bgcolor())

screen.bgcolor("#800080")

# 打印(128.0, 0.0, 128.0)

print(screen.bgcolor())

copycode.gif

# screen.bgpic(picname=None)

Parameters:

picname – 一个gif的字符串名字或"nopic"字符串或None

git图片名:表示设置海龟屏幕TurtleScreen的背景图像

"nopic":表示删除海龟屏幕TurtleScreen的背景图像

None:表示返回海龟屏幕TurtleScreen的背景图像的名称

# 设置/删除背景图片或返回当前的背景图片名

# 例如:

copycode.gif

screen = turtle.getscreen()

# 打印当前背景图像名,打印结果为'nopic'

print(screen.bgpic())

# 设置背景图像,landscape.gif需要提前放到该文件同级目录

screen.bgpic("landscape.gif")

# 打印当前背景图像名,打印结果为"landscape.gif"

print(screen.bgpic())

screen.bgpic('nopic')

# 打印当前背景图像名,打印结果为'nopic'

print(screen.bgpic())

copycode.gif

# screen.clear() | screen.clearscreen() 和 screen.reset() | screen.resetscreen()

# 例如:见【2.画笔控制中->d).更多的绘制控制】中例子

# screen.screensize(canvwidth=None, canvheight=None, bg=None)

Parameters:

canvwidth – 画布宽度(正整数,单位为像素)

canvheight – 画布高度(正整数,单位为像素)

bg – 新的背景颜色(colorstring或颜色组)

# 如果没给出参数,则返回当前的画布大小(canvaswidth, canvasheight);否则表示调整画布大小

# 例如:

copycode.gif

screen = turtle.getscreen()

# 打印当前画布大小,结果为(400, 300)

print(screen.screensize())

# 调整画布大小,变大后出现了滚动条,可通过滑动滑块查看画布隐藏部分

screen.screensize(2000, 1500)

# 打印当前画布大小,结果为(2000, 1500)

print(screen.screensize())

copycode.gif

# screen.setworldcoordinates(llx, lly, urx, ury)

Parameters:

llx – 画布左下角x坐标(number型)

lly – 画布左下角y坐标(number型)

urx – 画布右上角x坐标(number型)

ury – 画布右上角y坐标(number型)

# 设置用户自定义的坐标系统,如果必要的话需要切换到“world”模式,如果“world”模式已经是活动的,则会根据新的坐标重绘图纸。

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

# 例如:

copycode.gif

screen = turtle.getscreen()

# 获取当前海龟模式,打印结果为 logo

print(screen.mode())

turtle.shape("turtle")

# 清屏,位置方向恢复初始状态,保持海龟箭头形状不变

screen.reset()

# 设置海龟模式为"world"模式,感觉设不设置"world"模式展现效果没啥区别

screen.mode("world")

screen.setworldcoordinates(-50, -7.5, 50, 7.5)

for _ in range(72):

turtle.lt(10)

for _ in range(8):

turtle.lt(45);turtle.fd(2)

copycode.gif

b)Animation Control动画控制

# screen.delay(delay=None)

Parameters:

delay – 正整数

# 设置或返回绘图延迟(单位:毫秒),绘图延迟越长,动画的速度越慢

# 例如:

copycode.gif

screen = turtle.getscreen()

# 获取绘图延迟毫秒数,打印结果为10

print(screen.delay())

# 设置绘图延迟

screen.delay(5)

# 获取绘图延迟毫秒数,打印结果为5

print(screen.delay())

copycode.gif

# screen.tracer(n=None, delay=None)

Parameters:

n – 非负整数

delay – 非负整数,见screen.delay(delay=None)

# 打开或关闭海龟动画,并设置绘制延迟

# 例如:

copycode.gif

screen = turtle.getscreen()

screen.tracer(8, 25)

dist = 2

for i in range(200):

turtle.fd(dist)

turtle.rt(90)

dist += 2

copycode.gif

# screen.update()

# 更新海龟屏幕TurtleScreen对象,tracer关闭时使用

c)Using screen events - 海龟屏幕TurtleScreen的相关事件

# screen.listen(xdummy=None, ydummy=None)

# 为了收集关键事件,让海龟屏幕TurtleScreen的对象获取焦点

# screen.onkey(fun, key) | screen.onkeyrelease(fun, key)

Parameters:

fun – 一个无参函数或None

key – 一个字符串键值: 普通按键 (例如:“a”) 或功能键 (例如:“space”)

# 键盘上key键key-release事件触发时(即按下并抬起)绑定一个无参函数;如果第一个参数fun为None,则移除绑定的函数

# 注意:前提是海龟屏幕TurtleScreen对象需要通过screen.listen()方法获取焦点了

# 例如:

copycode.gif

def f():

turtle.fd(50)

turtle.lt(60)

screen = turtle.getscreen()

# 点击up键绑定f函数

screen.onkey(f, "Up")

# 屏幕获取焦点

screen.listen()

copycode.gif

# screen.onkeypress(fun, key=None)

Parameters:

fun – 一个无参函数或None

key – 一个字符串键值: 普通按键 (例如:“a”) 或功能键 (例如:“space”),key为None表示任何按键按下都会触发

# 键盘上key键(如果key为None时表示任意按键)按下时即key-press事件触发时绑定一个无参函数;如果第一个参数fun为None,则移除绑定的函数。

# 例如:

copycode.gif

def f():

turtle.fd(50)

turtle.lt(60)

screen = turtle.getscreen()

# 按下"Up"键时绑定f函数

#screen.onkeypress(f, "Up")

# 按下任意键时绑定f函数

screen.onkeypress(f, None)

screen.listen()

copycode.gif

# screen.onclick(fun, btn=1, add=None) | screen.onscreenclick(fun, btn=1, add=None)

Parameters:

fun – 一个有两个参数x,y的函数,画布上鼠标左键按下时将点击的坐标作为参数,调用该方法

num – 鼠标按钮的数目,默认为1(鼠标左键)

add – True或False.如果是True,将添加一个新的绑定;否则将替换前绑定

# 画布上鼠标左键在按下时绑定一个函数;如果函数为None,则移除存在的绑定

# 例如:

copycode.gif

screen = turtle.getscreen()

def turn(x, y):

turtle.lt(90)

# 打印当前坐标

print('x=', x, 'y=', y)

print(turtle.heading())

# 清除绑定关系

screen.onclick(None)

# 再次绑定

screen.onclick(turn)

# 绑定turn方法

screen.onclick(turn)

copycode.gif

# screen.ontimer(fun, t=0)

Parameters:

fun – 一个无参的函数

t – 一个>=0的number

# 开启一个计时器,t毫秒后调用函数fun

# 例如:点击屏幕画多边形,再次点击停止绘制

copycode.gif

# 定义全局变量

running = False

def demo1():

screen = turtle.getscreen()

def f():

# 内部函数想修改或使用全局变量需要加global,否则认为是局部变量

global running

if running:

turtle.fd(100)

turtle.lt(45)

# 开启计时器,250毫秒后执行f函数

screen.ontimer(f, 250)

def change_status(x, y):

# 内部函数想修改或使用全局变量需要加global,否则认为是局部变量

global running

# bool取反操作

running = not running

f()

screen.onclick(change_status)

def my_main():

demo1()

turtle.mainloop()

if __name__ == '__main__':

my_main()

copycode.gif

# d)Input methods输入相关方法

# screen.textinput(title, prompt)

Parameters:

title – 弹框标题(一个string字符串)

prompt – 弹框提示(一个string字符串)

# 弹出一个输入文本的弹出框,点击Cancel取消按钮则返回None,点击Ok按钮返回输入的字符串

# 例如:

screen = turtle.getscreen()

# 弹出输入文本的弹出框

name = screen.textinput("欢迎框", "你的姓名是")

if (name != None and name != ""):

print(name, ",您好")

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

Parameters:

title – 弹框标题(一个string字符串)

prompt – 弹框提示(一个string字符串)

default – 默认值number类型 (可选)

minval – 最小值number类型 (可选)

maxval – 最大值number类型 (可选)

# 弹出一个输入数字的弹出框,点击Cancel取消按钮则返回None,点击Ok按钮返回输入的number

# 例如:

copycode.gif

screen = turtle.getscreen()

# 弹出输入数字的弹出框

age = screen.numinput("身高", "请输入您的身高(单位:米)", 0, 0, 2.5)

# 判空容错处理

if age != None and age > 0:

print("身高", age, "米")

copycode.gif

# e)Settings and special methods设置和特殊方法

# screen.mode(mode=None) | turtle.mode(mode=None)

Parameters:

mode – "standard"或 "logo"或"world" 3选1,各海龟模式含义如下

Mode 初始方向 角度方向

"standard" 向右 (东) 逆时针方向

"world" 向右 (东) 逆时针方向

"logo" 向上(北) 顺时针方向

# 设置或返回海龟模式,默认是"standard"标准模式."standard"模式是兼容旧版本;"logo"模式兼容大部分海龟图形标志;"world"模式使用用户自定义的“世界坐标”该模式下x/y的单位比不为1会出现扭曲

# 例如:见screen.setworldcoordinates(llx, lly, urx, ury)中例子

# screen.colormode(cmode=None) | turtle.colormode(cmode=None)

Parameters:

cmode – 1.0或255,二选一

# 返回或设置colormode的值为1.0或255,随后调用turtle.fillcolor(*args)、turtle.pencolor(*args)、turtle.color(*args)等方法设置画笔颜色时R,G,B三组颜色值范围必须是0-colormode值之间的数,否则会报异常

# 例如:见turtle.fillcolor(*args)、turtle.pencolor(*args)、turtle.color(*args)中例子

# screen.getcanvas() | turtle.getcanvas()

# 返回海龟屏幕TurtleScreen的画布对象实例

# 例如:

screen = turtle.getscreen()

screen.getcanvas()

# screen.getshapes() | turtle.getshapes()

# 获取当前可用海龟形状的名称列表

# 例如:

# 获取当前可用海龟形状的名称列表,打印结果 ['arrow', 'blank', 'circle', 'classic', 'square', 'triangle', 'turtle']

print(turtle.getscreen().getshapes())

# screen.register_shape(name, shape=None) | screen.addshape(name, shape=None) | turtle.register_shape(name, shape=None) | turtle.addshape(name, shape=None)

# 内存中添加注册海龟图形

# 例如:

copycode.gif

screen = turtle.getscreen()

方法1:

screen.register_shape("turtle.gif")

方法2:

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

方法3:shape_obj是一个shape对象见 【turtle.begin_poly()、turtle.end_poly()和turtle.get_poly()配合使用】中例子

screen.register_shape("myFavouriteShape", shape_obj)

copycode.gif

# screen.turtles() | turtle.turtles()

# 返回海龟屏幕TurtleScreen中所有的海龟箭头对象列表

# 例如:

for turtle in screen.turtles():

turtle.color("red")

# screen.window_height() | turtle.window_height() 和 screen.window_width() | turtle.window_width()

# 返回海龟绘图窗口的高/宽(单位:像素)

# 例如:

# 获取海龟绘图窗口高度(单位:像素), 打印 576

print(turtle.window_height())

# 获取海龟绘图窗口宽度(单位:像素), 打印 683

print(turtle.window_width())

# screen.bye() | turtle.bye()

# 关闭海龟图形窗口

# 例如:

turtle.bye()

# screen.exitonclick() | turtle.exitonclick()

# 运行后屏幕自动消失,调用这句后屏幕会保持,直到点击屏幕才会关闭海龟图形窗口

# 例如:

turtle.exitonclick()

# screen.mainloop() | screen.done() | turtle.mainloop() | turtle.done()

# 运行后屏幕自动消失,调用这句后屏幕会保持,直到主动关闭当前窗口(点击绘图窗口右上角的关闭按钮或程序调用screen.bye()或turtle.bye()函数),想使用的话必须作为图形绘制程序的最后一条语句

# 例如:

turtle.mainloop()

# screen.setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])

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

Parameters:

width – 一个整数(单位:像素)或一个小数(表示百分比),默认是屏幕宽的50%

height – 一个整数(单位:像素)或一个小数(表示百分比),默认是屏幕高的75%

startx – 如果是正数,则从屏幕左边缘开始向右(单位:像素) ;如果为负数则从屏幕右边缘开始向左;如果为None则窗口水平居中

starty – 如果是正数,则从屏幕顶部边缘开始向下(单位:像素) ;如果为负数则从屏幕底部边缘开始向上;如果为None则窗口垂直居中

# 设置默认展现的主窗口的大小和位置(宽或高比海龟绘图窗口小时对应方向上会出现滚动条)。参数的默认值存储在turtle.cfg配置文件中,如果需要可进行修改

# 例如:

screen = turtle.getscreen()

# 海龟绘图窗口宽高分别为576和683,此时将默认展现的主窗口的大小设置成了576和100,垂直方向因为占不全会出现滚动条

screen.setup(width=576, height=100, startx=0, starty=0)

# screen.setup(width=0.75, height=0.5, startx=None, starty=None)

# screen.title(titlestring) | turtle.title(titlestring)

# 设置海龟窗口标题

# 例如:

screen = turtle.getscreen()

# 设置窗口标题

screen.title("hello turtle")

# 补充

# 关于turtle、turtle.getturtle()、和turtle.Turtle()的理解

# 例如:

# turtle含义:

print("turtle含义:", turtle)

turtle0 = turtle.getturtle()

# turtle0含义: 认为turtle.getturtle()是获取默认的第一个Turtle对象实例

print("turtle0含义:", turtle0)

turtle1 = turtle.Turtle()

# turtle1含义: 认为turtle.Turtle()是创建一个新的Turtle实例对象并返回该实例对象

print("turtle1含义:", turtle1)

turtle2 = turtle.getturtle()

# turtle2含义:

print("turtle2含义:", turtle2)

turtle3 = turtle.Turtle()

# turtle3含义:

print("turtle3含义:", turtle3)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值