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. -/bin/sh: /usr/bin/xxx: not found”

    运行/usr/bin/helloworld命 令是提示“-/bin/sh: /usr/bin/helloworld: not found”,一开始我以为是helloworld没有运行权限,不过我给了它 ...

  2. Gogs http和ssh地址显示localhost的问题

    问题描述: 如下图所示HTTP和SSH地址显示的是localhost而不是对应的域名或地址. 解决方案: 按以下方法修改Gogs配置文件并重启服务器 域名问题 RUN_USER = git DOMAI ...

  3. 关于Unity的C#基础学习(二)

    一.Debug的使用 int a=3; Debug.Log("a="+a); 二.整数的定义 int m; Debug.Log(m);  //C#比C更严谨,没有初始化的变量打印出 ...

  4. This表示当前对象

    This表示当前对象. Public void printNum(){ Int number=40: System.out.println(this.number); } 此时打印的是实例变量,而非局 ...

  5. C++之函数模板

    C++之函数模板与模版函数 直接上代码:  C++ Code  12345678910111213141516171819202122232425262728293031323334353637383 ...

  6. 响应式布局中为什么要使用em设置字体大小而不用px

    px像素(Pixel).相对长度单位.像素px是相对于不同设备显示器屏幕分辨率(pad/phone/pc)而言的.(引自CSS2.0手册) 1em指的是一个字体的大小,它会继承父级元素的字体大小,因此 ...

  7. Appium使用Python运行appium测试的实例

    Appium使用Python运行appium测试的实例 一.  Appium之介绍 https://testerhome.com/topics/8038 详情参考--https://testerhom ...

  8. Struts2_day01--课程安排_Struts2概述_入门

    Struts2_day01 Struts2课程安排 今天内容 Struts2概述 Struts2框架入门 导入源文件 Struts2执行过程 查看源代码 Struts2的核心配置文件 标签packag ...

  9. UE4与Visual Studio版本对应关系

    首先,要注意,Visual Studio 2015(VS2015)默认安装时并不包含 C++ 的工具.在安装 VS2015 时,需选择 自定义 安装并勾选 C++ 组件,这对之后的工作时必须的.如果已 ...

  10. 第十五篇:使用 FP-growth 算法高效挖掘海量数据中的频繁项集

    前言 对于如何发现一个数据集中的频繁项集,前文讲解的经典 Apriori 算法能够做到. 然而,对于每个潜在的频繁项,它都要检索一遍数据集,这是比较低效的.在实际的大数据应用中,这么做就更不好了. 本 ...