Python标准库 之 turtle(海龟绘图)

时间:2024-03-14 17:42:11

turtle库介绍

首先,turtle库是一个点线面的简单图像库(也被人们成为海龟绘图),在Python2.6之后被引入进来,能够完成一些比较简单的几何图像可视化。它就像一个小乌龟,在一个横轴为x、纵轴为y的坐标系原点,(0,0)位置开始,它根据一组函数指令的控制,在这个平面坐标系中移动,从而在它爬行的路径上绘制了图形。

turtle库基础知识

1.画布(canvas)

画布就是turtle为我们展开用于绘图区域默认大小(400, 300),我们可以设置它的大小和初始位置。

1.1设置画布大小:

turtle.screensize(canvwidth=None, canvheight=None, bg=None),参数分别为画布的宽(单位像素), 高, 背景颜色。
如:
turtle.screensize(800,600, "green")
turtle.screensize() #返回默认大小(400, 300)
turtle.setup(width=0.5, height=0.75, startx=None, starty=None),参数:width, height: 输入宽和高为整数时, 表示像素; 为小数时, 表示占据电脑屏幕的比例,(startx, starty): 这一坐标表示矩形窗口左上角顶点的位置, 如果为空,则窗口位于屏幕中心。

如:

turtle.setup(width=0.6,height=0.6)
turtle.setup(width=800,height=800, startx=100, starty=100)

2.画笔(pen)

2.1 画笔的状态
在画布上,默认有一个坐标原点为画布中心的坐标轴,坐标原点上有一只面朝x轴正方向小乌龟。这里我们描述小乌龟时使用了两个词语:坐标原点(位置),面朝x轴正方向(方向), turtle绘图中,就是使用位置方向描述小乌龟(画笔)的状态。

2.2 画笔的属性
画笔(画笔的属性,颜色、画线的宽度等)

1) turtle.pensize():设置画笔的宽度;

2) turtle.pencolor():没有参数传入,返回当前画笔颜色,传入参数设置画笔颜色,可以是字符串如"green", "red",也可以是RGB 3元组。

3) turtle.speed(speed):设置画笔移动速度,画笔绘制的速度范围[0,10]整数,数字越大越快。

2.3 绘图命令
操纵海龟绘图有着许多的命令,这些命令可以划分为3种:一种为运动命令,一种为画笔控制命令,还有一种是全局控制命令。

2.3.1 画笔运动命令:

命令 说明
turtle.home() 将turtle移动到起点(0,0)和向东
turtle.speed(speed) 画笔绘制的速度范围[0,10]整数
turtle.forward(distance) 向当前画笔方向移动distance像素长
turtle.backward(distance) 向当前画笔相反方向移动distance像素长度
turtle.right(degree) 顺时针移动degree°
turtle.left(degree) 逆时针移动degree°
turtle.pendown() 移动时绘制图形放下笔,,默认绘制
turtle.penup() 移动时不绘制图形,提起笔,用于另起一个地方绘制时用
turtle.circle(r,extent,step) 绘制一个指定半径、弧度范围、阶数(正多边形)的圆
turtle.dot(diameter,color) 绘制一个指定直径和颜色的圆

 

  2.3.2 画笔控制命令:

命令 说明
turtle.pencolor() 画笔颜色
turtle.pensize(width) 画笔宽度(绘制图形时的宽度)
turtle.color(color1, color2 同时设置pencolor=color1, fillcolor=color2
turtle.filling() 返回当前是否在填充状态
turtle.begin_fill() 准备开始填充图形
turtle.end_fill() 填充完成
turtle.hideturtle() 隐藏画笔的turtle形状
turtle.showturtle() 显示画笔的turtle形状

 

  2.3.3 全局控制命令

命令 说明
turtle.clear() 清空turtle窗口,但是turtle的位置和状态不会改变
turtle.reset() 清空窗口,重置turtle状态为起始状态
turtle.undo() 取消最后一个图的操作
turtle.isvisible() 返回当前turtle是否可见
turtle.stamp() 复制当前图形
turtle.write(s , [font=("font-name",font_size,"font_type")]) 写文本,s为文本内容,font是字体的参数,分别为字体名称,大小和类型;font为可选项,font参数也是可选项

  

  2.3.4 其他命令

命令 说明
turtle.mainloop()或turtle.done() 启动事件循环 -调用Tkinter的mainloop函数。必须是乌龟图形程序中的最后一个语句。
turtle.mode(mode=None) 设置乌龟模式(“standard”,“logo(向北或向上)”或“world()”)并执行重置。如果没有给出模式,则返回当前模式。
turtle.undo() 取消最后一个图的操作
turtle.isvisible() 返回当前turtle是否可见
turtle.stamp() 复制当前图形
turtle.write(s , [font=("font-name",font_size,"font_type")]) 写文本,s为文本内容,font是字体的参数,分别为字体名称,大小和类型;font为可选项,font参数也是可选项

实例

五角星图形

#五角星图形
from turtle import Turtle

p = Turtle()
p.speed(3)
p.pensize(5)
p.color("black", 'yellow')
#p.fillcolor("red")
p.begin_fill()
for i in range(5):
    p.forward(200)  #将箭头移到某一指定坐标 
    p.right(144)    #当前方向上向右转动角度
p.end_fill()

Python标准库 之 turtle(海龟绘图)

树的绘制

Python标准库 之 turtle(海龟绘图)

观察:对称树, 从主杆出发以一定角度向左向右生成对称的枝丫, 且每一棵枝杈上以相同的角度生成更小的左右枝杈,如此往复。
联系:所学内容,易想到利用递归程序实现;

# drawtree.py

from turtle import Turtle, mainloop

def tree(plist, l, a, f):
    """ plist is list of pens
    l is length of branch
    a is half of the angle between 2 branches
    f is factor by which branch is shortened
    from level to level."""
    if l > 5: #
        lst = []
        for p in plist:
            p.forward(l)#沿着当前的方向画画Move the turtle forward by the specified distance, in the direction the turtle is headed.
            q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
            p.left(a) #Turn turtle left by angle units
            q.right(a)#Turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
            lst.append(p)#将元素增加到列表的最后
            lst.append(q)
        tree(lst, l*f, a, f)



def main():
    p = Turtle()
    p.color("green")
    p.pensize(5)
    #p.setundobuffer(None)
    p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
                   #because hiding the turtle speeds up the drawing observably.

    p.getscreen().tracer(10,0)
        #Return the TurtleScreen object the turtle is drawing on.
        #TurtleScreen methods can then be called for that object.
    #p.speed(10)
    p.left(90)  #Turn turtle left by angle units. direction 调整画笔

    p.penup() #Pull the pen up – no drawing when moving.
    p.goto(0,-200)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
    p.pendown()# Pull the pen down – drawing when moving. 这三条语句是一个组合相当于先把笔收起来再移动到指定位置,再把笔放下开始画
    #否则turtle一移动就会自动的把线画出来

    #t = tree([p], 200, 65, 0.6375)
    t = tree([p], 200, 65, 0.6375)

main()

森林的绘制

如何画出多棵树,甚至整片森林呢? 
答案很简单,只要在画每棵树之前调整画笔的位置,调用画树程序,就可以从新位置生成一颗新树了。 
利用模块化的函数思想,调整代码: 
将每棵树的绘制以maketree函数封装,参数x,y为画树的起点位置即树根位置。在main函数中只要以不同的参数设置来调用maketree函数就可以完成多棵树的绘制了

# drawtree.py
from turtle import Turtle, mainloop

def tree(plist, l, a, f):
    """ plist is list of pens
    l is length of branch
    a is half of the angle between 2 branches
    f is factor by which branch is shortened
    from level to level."""
    if l > 5: #
        lst = []
        for p in plist:
            p.forward(l)#沿着当前的方向画画Move the turtle forward by the specified distance, in the direction the turtle is headed.
            q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
            p.left(a) #Turn turtle left by angle units
            q.right(a)#Turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
            lst.append(p)#将元素增加到列表的最后
            lst.append(q)
        tree(lst, l*f, a, f)

def maketree(x, y):
    p = Turtle()
    p.color("green")
    p.pensize(5)
    p.hideturtle()
    p.getscreen().tracer(30, 0)
    p.left(90)

    p.penup()
    p.goto(x, y)
    p.pendown()

    t = tree([p], 110, 65, 0.6375)
    print(len(p.getscreen().turtles())) #用了多少个turtle绘制

def main():
    maketree(-200, -200)
    maketree(0, 0)
    maketree(200, -200)

main()

Python标准库 之 turtle(海龟绘图)

作者:码农大表哥
链接:

https://www.jianshu.com/p/df81a110cdfd
來源:简书

-END-


Python标准库 之 turtle(海龟绘图)

                                   识别图中二维码,领取python全套视频资料