python学习笔记 turtle库

turtle(海龟)是Python重要的标准库之一,它能够进行基本的图形绘制。turtle图形绘制的概念诞生于1969年,成功应用于LOGO编程语言。
turtle库绘制图形有一个基本框架:一个小海龟在坐标系中爬行,其爬行轨迹形成了绘制图形。刚开始绘制时,小海龟位于画布正中央,此处坐标为(0,0),前进方向为水平右方。

一、用import保留字对turtle库的引用有如下3种方式,效果相同:

1.import turtle

 对turtle库中函数调用采用turtle.<函数名>( )形式:

2.from turtle import * (当程序中有多个库时容易混淆产生错误)

对turtle库中函数调用采用<函数名>( )形式,不再使用turtle.作为前导:

3. import turtle as t

保留字as将turtle库给予别名t, 则对turtle库中函数调用采用更简洁的t.<函数名>( )形式:

 

 

二、绘图的基础知识

1.绘图窗口设置命令

turtle.setup(400,300,200,100):参数以此(宽,高,距离屏幕左边距离,距离屏幕上方距离),屏幕左上角原点,单位像素。

2.运动命令

turtle.goto(x,y):直接跳转到(x,y)点,以绘图窗口中心为原点,向右为x轴,以上为y轴。

turtle.fd(d)、turtle.forward(d):以当前方向,往前行进d像素。

turtle.bk(d)、turtle.backword(d):保持当前方向不变,往后退行d像素。

turtle.circle(r,angle):从当前位置以r为半径圆的angle角度旋转。

3.方向设置命令

turtle.seth(angle):以x轴方向为起点将方向偏转为angle度,逆时针为正。只改变行进方向但不行进。

turtle.left(angle):在当前行进方向的基础上,向左旋转angle度。

turtle.right(angle):在当前行进方向的基础上,向右旋转angle度。

4.画笔控制命令

turtle.penup():抬笔

turtle.pendown():落笔

turtle.pensize(width):画笔粗细

turtle.pencolor(颜色名red/RGB三元组/颜色编码):画笔颜色

turtle.fillcolor(colorstring):绘制图形的填充颜色

turtle.begin_fill():开始填充

turtle.end_fill():结束填充

turtle.filling():返回当前是否在填充状态

5.全局控制命令

turtle.clear():清空turtle窗口,但是turtle的位置和状态不会改变

turtle.reset():清空窗口,重置turtle状态为起始状态

turtle.undo():撤销上一个turtle动作

turtle.isvisible():返回当前turtle是否可见
stamp():复制当前图形
turtle.write(s[,font=("font-name",font_size,"font_type")]):写文本,s为文本内容,font是字体的参数,里面分别为字体名称,大小和类型;font为可选项, font的参数也是可选项
 

 三、绘图例子

兔の绘图代码如下:

#绘制大耳朵兔
from turtle import *
speed(10)
 
#小兔的面部
color('pink')
pensize(5)
circle(radius=100)#
 
#眼睛
pencolor('black')
#左眼
pu()
goto(-45,92)
pd()
begin_fill()
color((0,0,0),(0,0,0.1))
circle(radius=15)
#右眼
pu()
goto(45,92)
pd()
circle(radius=15)
end_fill()
 
#鼻子
pu()
goto(20,60)
color('pink')
pd()
begin_fill()
goto(-20,60)
goto(0,45)
goto(20,60)
end_fill()
 
#
goto(0,45)
goto(0,40)
seth(-90)
circle(10,120)
pu()
goto(0,40)
seth(-90)
pd()
circle(-10,120)
 
 
#小兔的耳朵
#左耳
pu()
goto(-60,180)#
seth(200)
pd()
circle(radius=350,extent=90)
goto(-98,110)
#右耳
pu()
goto(60,180)#
seth(-20)
pd()
circle(radius=-350,extent=90)
goto(98,110)
 
#小兔的身体
pu()
goto(20,3)
seth(-25)
pd()
circle(radius=-250,extent=25)
circle(radius=-135,extent=260)
seth(50)
circle(radius=-250,extent=25)
 
##小兔的胳膊
#左臂
pu()
seth(180)
goto(-30,-3)
pd()
#小短胳膊
##circle(radius=270,extent=20)
##circle(radius=20,extent=190)
circle(radius=248,extent=30)
circle(radius=29,extent=185)
#右臂
pu()
seth(0)
goto(30,-3)
pd()
circle(radius=-248,extent=30)
circle(radius=-27,extent=184)
 
##小兔的脚
##左脚
pu()
goto(-162,-260)#
pd()
seth(0)
circle(radius=41)
#右脚
pu()
goto(164,-260)
pd()
circle(radius=41)
 
done()

图片:

 

posted @ 2020-10-26 19:51  唯闻卿卿  阅读(445)  评论(0编辑  收藏  举报