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

树的绘制

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

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

作者:码农大表哥
链接:

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

-END-


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

Python标准库 之 turtle(海龟绘图)的更多相关文章

  1. 小白学Python(20)—— Turtle 海龟绘图

    Turtle库是Python语言中一个很流行的绘制图像的函数库,想象一个小乌龟,在一个横轴为x.纵轴为y的坐标系原点,(0,0)位置开始,它根据一组函数指令的控制,在这个平面坐标系中移动,从而在它爬行 ...

  2. Python标准库: turtle--海龟绘图。

    turtle --- 海龟绘图 (点击查看官方文档.) 简介 import turtle # 调用该库.Turtle的实例对象,默认命名为turtle. turtle.forward(10) from ...

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

    转自:http://blog.csdn.net/jurbo/article/details/52334345 写这个的起因是,还是因为在做Python challenge的时候,有的时候想解决问题,连 ...

  4. python第六天 函数 python标准库实例大全

    今天学习第一模块的最后一课课程--函数: python的第一个函数: 1 def func1(): 2 print('第一个函数') 3 return 0 4 func1() 1 同时返回多种类型时, ...

  5. 转--Python标准库之一句话概括

    作者原文链接 想掌握Python标准库,读它的官方文档很重要.本文并非此文档的复制版,而是对每一个库的一句话概括以及它的主要函数,由此用什么库心里就会有数了. 文本处理 string: 提供了字符集: ...

  6. python 标准库大全

    python 标准库 文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata:Unicode字符数据库 string ...

  7. Python标准库、第三方库和外部工具汇总

    导读:Python数据工具箱涵盖从数据源到数据可视化的完整流程中涉及到的常用库.函数和外部工具.其中既有Python内置函数和标准库,又有第三方库和工具. 这些库可用于文件读写.网络抓取和解析.数据连 ...

  8. Python 标准库、第三方库

    Python 标准库.第三方库 Python数据工具箱涵盖从数据源到数据可视化的完整流程中涉及到的常用库.函数和外部工具.其中既有Python内置函数和标准库,又有第三方库和工具.这些库可用于文件读写 ...

  9. 140种Python标准库、第三方库和外部工具

    导读:Python数据工具箱涵盖从数据源到数据可视化的完整流程中涉及到的常用库.函数和外部工具.其中既有Python内置函数和标准库,又有第三方库和工具. 这些库可用于文件读写.网络抓取和解析.数据连 ...

随机推荐

  1. 一款基于jQuery的图片分组切换焦点图插件

    这是一款基于jQuery的图片切换焦点图插件,这款jQuery焦点图插件的特点是图片可以分组切换,也就是说一次可以切换多张图片,相比其他焦点图插件,它能节省更多的空间,可以向用户展示更多的图片,非常实 ...

  2. oozie常见错误问题

    1.  Error: HTTP error code: 404 : Not Found 原因: 在环境变量中配置的OOZIE_URL有问题配置成了 export OOZIE_URL=http://dw ...

  3. python的卸载方式和运行yum报错:No module named yum

    公司测试机环境不知道给我卸了什么包,导致yum运行报错状况: 系统版本:Red Hat Enterprise Linux Server release 6.2 (Santiago) 内核版本:2.6. ...

  4. URL 重写

    转载自:http://www.cnblogs.com/knowledgesea/archive/2012/10/08/2715350.html 一. 为了页面更有利于seo优化,url重写程序需要做出 ...

  5. 关于Unity中的新手编码技巧

    写代码遇到报错,问题怎么办?怎么查看unity代码的接口?函数参数不记得了怎么办? 解决方法: 1.选择不懂的函数或类,按F12,跳转到代码的定义,自己去看就可知道了. 2.有的时候,选择一个函数,按 ...

  6. jsp中9个内置对象与servlet对应关系及四个作用域

    参考:  <jsp&servlet学习笔记.第2版.林信良><JSR-245 JavaServer Pages 2.2 Maintenance Release Specifi ...

  7. 程序生成word与PDF文档的方法(python)

    程序导出word文档的方法 将web/html内容导出为world文档,再java中有很多解决方案,比如使用Jacob.Apache POI.Java2Word.iText等各种方式,以及使用free ...

  8. jQuery学习笔记2——表单操作

    一.获取和设置表单的值:val()和text() 1. 获取表单的值: $("#username").val(); 2. 设置表单的值: $("#username&quo ...

  9. 【BZOJ】1068: [SCOI2007]压缩(dp)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1068 发现如果只设一维的话无法转移 那么我们开第二维,发现对于前i个来说,如果确定了M在哪里,第i个 ...

  10. jQuery制作简洁的多级联动Select下拉框

    今天我们要来分享一款很实用的jQuery插件,它是一个基于jQuery多级联动的省市地区Select下拉框,并且值得一提的是,这款联动下拉框是经过自定义美化过的,外观比浏览器自带的要漂亮许多.另外,这 ...