turtle库的使用

概述:turtle(海龟)库是turtle绘图体系的python实现

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

turtle库的理解

-有一只海龟,其实在窗体正中心,在画布上游走

-走过的轨迹形成了绘制的图形

-海龟由程序控制,可以变换颜色,改变宽度

turtle的绘图窗体

turtle.setup(width,height,startx,starty)

Python-基本图形绘制及库引用 Python 第1张

-setup()设置窗体大小位置

-4个参数中后两个可选

-setup()不是必须的

例如:

turtle.setup(800,800,0,0)

Python-基本图形绘制及库引用 Python 第2张

turtle.setup(800,800)

Python-基本图形绘制及库引用 Python 第3张

 

turtle空间坐标体系(绝对坐标)

turtle.goto(x,y)

 

Python-基本图形绘制及库引用 Python 第4张

import turtle
turtle.goto(100,100)
turtle.goto(100,-100)
turtle.goto(-100,-100)
turtle.goto(-100,100)
turtle.goto(0,0)

Python-基本图形绘制及库引用 Python 第5张

turtle空间坐标体系(海龟坐标)

 Python-基本图形绘制及库引用 Python 第6张

Python-基本图形绘制及库引用 Python 第7张

turtle角度坐标体系(绝对坐标)

Python-基本图形绘制及库引用 Python 第8张

turtle.seth(angle)

-seth()改变海龟行进方向

-angle为绝对度数

-seth()只改变方向但不前进

例如

turtle.seth(45)

Python-基本图形绘制及库引用 Python 第9张

turtle.seth(-135)

Python-基本图形绘制及库引用 Python 第10张

turtle角度坐标体系(海龟角度)

Python-基本图形绘制及库引用 Python 第11张

import turtle
turtle.left(45)
turtle.fd(150)
turtle.right(135)
turtle.fd(300)
turtle.left(135)
turtle.fd(150)

Python-基本图形绘制及库引用 Python 第12张

turtle的RGB色彩模式

默认采用小数值 可切换为整数值

turtle.colormode(mode)

-1.0:RGB小数值模式

-255:RGB整数值模式

也可以用英文名 如

turtle.color("blue")

 

 

 

 库引用

扩充python程序功能的方式

-使用import保留字完成,采用<a>.<b>()编码风格

    import <库名>

    <库名>.<函数名>(<函数参数>)

import turtle    #引入turtle库

import更多用法

使用from和import保留字共同完成

from <库名> import <函数名>

from <库名> import *

<函数名>(<函数参数>)

(可能会出现函数重名问题)

import更更多用法(这个方法好)

使用import和as保留字共同完成

import <库名> as <库别名>

<库别名>.<函数名>(<函数参数>)

turtle画笔控制函数

画笔操作后一直有效,一般成对出现

画笔设置后一直有效,直至下次重新设置

turtle.penup() #别名 turtle.pu() 抬起画笔,海龟飞行
turtle.pendown() #别名 turtle.pd() 落下画笔,海龟在爬行
turtle.pensize(width) #别名 turtle.width(width) 画笔宽度,海龟的腰围
turtle.pencolor(color) #color为颜色字符串或rgb值  画笔颜色,海龟轨迹的颜色

pencolor(color)的color参与可以有三种形式

turtle.pencolor("purple") #颜色字符串
turtle.pencolor(0.63,0.13,0.94) #RGB的小数值
turtle.pencolor((0.63,0.13,0.94)) #RGB的元祖值

运动控制函数

控制海龟行进:走直线&走曲线

向前行进,海龟走直线:

turtle.forward(d) #别名 turtle.fd(d)

d:行进距离,可以为负数

根据半径r绘制extent角度弧形

turtle.circle(r,extent)

r:默认圆心在海龟左侧r距离的位置

extent:绘制角度,默认是360度整圆

turtle.circle(100)

Python-基本图形绘制及库引用 Python 第13张

turtle.circle(-100,90)

Python-基本图形绘制及库引用 Python 第14张

 

部分图片来自慕课https://www.icourse163.org/course/BIT-268001 若侵权请告知删除

  Python-基本图形绘制及库引用 Python 第15张       Python-基本图形绘制及库引用 Python 第16张       Python-基本图形绘制及库引用 Python 第17张    
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄