python基础之 turtle 库总结

python基础之 turtle 库总结

1. 准备工作

1.1 准备画布

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

第一种方法:设置画布大小: 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)

1.2 画笔设置

a. 画笔的状态

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

b. 画笔的控制

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

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

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

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

  4. pendown() | pd() | down(): 放下笔 ;移动的时候绘图。

  5. penup() | pu() | up() 提起笔;移动时无图。

  6. isdown() 如果笔停止返回True,反之False

  7. fillcolor() 笔的填充色。

  8. hideturtle() | ht() 删隐藏乌龟的形状,在做复杂绘图的时候隐藏的时候有利于提高绘图速度。

  9. showturtle() | st()显示乌龟的形状。

  10. isvisible():乌龟是否可见。如果可见返回True,反之则False。

  11. color():同时设置pencolor和fillcolor

  12. write():写文本。参数:arg-要写入的对象。move-是否移动。align-对齐方式:left,right,center。font-字体。fontname,fontsize,fonttype。

  13. shape(): 设置乌龟的图形形状,取值:“arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”

2. 画笔运动函数

2.1 向前:forward() | fd()

向前移动指定的距离。参数:一个数字(integer or float))。

turtle.forward(25)

2.2 向后:backward() | bk() | back()

向后移动指定的距离。参数:一个数字(integer or float))。

turtle.backward(30)

2.3 向右:right() | rt()

以角度单位向右转动。参数:一个数字(integer or float))。单位默认为度数,可以通过degrees()和radians()进行设置。

turtle.right(45)

2.4 向左:left() | lt()

以角度单位向左转动。参数:一个数字(integer or float))。单位默认为度数,可以通过degrees()和radians()进行设置。

turtle.left(45)  

2.5 到指定点:goto() | steps() | setposition()

移动到绝对位置,如果笔落下,画线,不改变方向。参数:x-一个数字或一对数字。y-一个数字或None。

turtle.setpos(60,30)

2.6 设置X方向:setx()

设置第一个坐标的值即X方向。参数:一个数字(integer or float))。

turtle.setx(10)

2.7 设置y方向:sety()

设置第二个坐标的值即Y方向。参数:一个数字(integer or float))。

turtle.sety(10)

2.8 设置方向:setheading() | seth()

将方向设置为to_angle.就是东西南北方向。具体如下:
标准模式:0 - 东 90 - 北 180 - 西 270 - 南 标志模式 0- 北 90- 东 180- 南 270 - 西

turtle.setheading(90)  # 将方向设置为向上

在这里插入图片描述

2.9 原点:home()

移动到原点 - 坐标(0,0):并将其标题设置为其起始方向(取决于模式)

turtle.home()

2.10 绘制圆:circle(radius,extent,steps)

绘制一个给定半径,制定对应圆心角的圆。三个参数 circle(radius,extent,steps):
radius:一个数字;
extent:一个角度,默认为360(如果值为正则逆时针,负数为顺时针);
steps: 执行的步数(数字越大越圆滑)。

turtle.circle(120,180,10)

2.11 绘制点:dot(size,color)

用颜色画出一个直径大小的圆点。两个参数dot(size,color):
size :一个大于1的整数,可None。默认用的是pensize+4和2*pensize的最大值;
color : 颜色值;

3 画笔属性函数

  • 3.1 返回当前的位置 :position() | pos()

  • 3.2 返回当前位置同指定位置之间的角度:towards()
    返回当前位置同指定位置之间的角度。参数:x-一个数字或一对数字或一个实例的向量,y-如果x是数字,则为数字,否则为None。

turtle.goto(10,10)
tw = turtle.towards(0,0)
print(tw)
# 225
  • 3.3 返回当前x坐标 xcor()

  • 3.4 返回当前y坐标 ycor()

  • 3.5 返回当前方向值 heading()

  • 3.6 返回距离 distance(),返回x,y两个点的直线距离

3. 画笔控制函数

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

4. 全局控制函数

函数说明
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参数也是可选项

5. 其他函数

5.1 启动事件循环turtle.mainloop()turtle.done()

启动事件循环 -调用Tkinter的mainloop函数。必须是乌龟图形程序中的最后一个语句。

5.2 模式设置 turtle.mode(mode=None)

设置乌龟模式(“standard”,“logo”或“world”)并执行重置。如果没有给出模式,则返回当前模式。

模式初始龟标题正角度
standard向右(东)逆时针
logo向上(北)顺时针

5.3 设置延时turtle.delay(delay=None)

turtle.delay(delay=None)

5.4 其他函数(不常用)

函数说明
turtle.begin_poly()开始记录多边形的顶点。当前的乌龟位置是多边形的第一个顶点。
turtle.end_poly()停止记录多边形的顶点。当前的乌龟位置是多边形的最后一个顶点。将与第一个顶点相连。
turtle.get_poly()返回最后记录的多边形。
resizemode()参数:rmode取值:“auto”,“user”,“noresize”.
shapesize()turtlesize()
shearfactor()设置或者返回但钱的剪切因子
tilt()旋转由turtle shape角度从当前的倾斜角度
settiltangle()无论当前的倾斜角度如何,旋转乌龟指向 angle 指定的方向。参数:angle -数字。已弃用
tiltangle()设置或者返回当前的倾斜角度。参数:angle - 数字
shapetransform()设置或返回乌龟的形状的当前转换矩阵
get_shapepoly()返回当前形状的坐标
onclick()鼠标点击事件。参数:fun-一个带有两个参数的函数,这些参数将与画布上单击点的坐标一个调用。num-鼠标按钮的数量,默认为1(左键)。add- True的时候将添加新的绑定。否则替换以前的绑定。
onrelease()鼠标释放事件。参数同点击事件。
ondrag()鼠标移动事件。参数同点击事件。
begin_poly()开始记录多边形的顶点
end_poly()停止记录多边形的顶点
get_poly()返回最后记录的多边形
clone()创建并返回具有相同位置等等属性的乌龟克隆。
getturtle()getpen()
getscreen()返回正在绘制的对象。
setundobuffer()设置或禁用中断器。参数: size-整数。如果大小是None,则禁用缓冲区。
undobufferentries()返回undobuffer中的条目数。
bgcolor()设置或者返回当前的TurtleScreen的背景颜色。
bgpic()设置背景图片。参数: picname-文件名。
delay()设置或返回以毫秒为单位的绘制延迟,延迟越大,绘图越慢。
ontimer()定时器。
mainloop()done()
textinput()numinput()
mode()三种方式:“standard”, “logo” or “world”

6 实例

6.1 小猪佩奇


import turtle as t
t.pensize(4)
t.hideturtle()
t.colormode(255)
t.color((255, 155, 192), "pink")
t.setup(840, 500)
t.speed(20)
# 鼻子
t.pu()   # 画笔别名
t.goto(-100, 100)
t.pd()    # pendown
t.seth(-30)   # 控制方向
t.begin_fill()
a = 0.4
for i in range(120):
    if 0 <= i < 30 or 60 <= i < 90:
        a = a + 0.08
        t.lt(3)  # 向左转3度
        t.fd(a)  # 向前走a的步长
    else:
        a = a - 0.08
        t.lt(3)
        t.fd(a)
t.end_fill()
t.pu()
t.seth(90)
t.fd(25)
t.seth(0)
t.fd(10)
t.pd()
t.pencolor(255, 155, 192)
# t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160, 82, 45)
t.end_fill()
t.pu()
t.seth(0)
t.fd(20)
t.pd()
t.pencolor(255, 155, 192)
t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160, 82, 45)
t.end_fill()
# 头
t.color((255, 155, 192), "pink")
t.pu()
t.seth(90)
t.fd(41)
t.seth(0)
t.fd(0)
t.pd()
t.begin_fill()
t.seth(180)
t.circle(300, -30)
t.circle(100, -60)
t.circle(80, -100)
t.circle(150, -20)
t.circle(60, -95)
t.seth(161)
t.circle(-300, 15)
t.pu()
t.goto(-100, 100)
t.pd()
t.seth(-30)
a = 0.4
for i in range(60):
    if 0 <= i < 30 or 60 <= i < 90:
        a = a + 0.08
        t.lt(3)  # 向左转3度
        t.fd(a)  # 向前走a的步长
    else:
        a = a - 0.08
        t.lt(3)
        t.fd(a)
t.end_fill()
# 耳朵
t.color((255, 155, 192), "pink")
t.pu()
t.seth(90)
t.fd(-7)
t.seth(0)
t.fd(70)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50, 50)
t.circle(-10, 120)
t.circle(-50, 54)
t.end_fill()
t.pu()
t.seth(90)
t.fd(-12)
t.seth(0)
t.fd(30)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50, 50)
t.circle(-10, 120)
t.circle(-50, 56)
t.end_fill()
# 眼睛
t.color((255, 155, 192), "white")
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-95)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill()
t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill()
t.color((255, 155, 192), "white")
t.pu()
t.seth(90)
t.fd(-25)
t.seth(0)
t.fd(40)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill()
t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill()
# 腮
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(-95)
t.seth(0)
t.fd(65)
t.pd()
t.begin_fill()
t.circle(30)
t.end_fill()
# 嘴
t.color(239, 69, 19)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(-100)
t.pd()
t.seth(-80)
t.circle(30, 40)
t.circle(40, 80)
# 身体
t.color("red", (255, 99, 71))
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-78)
t.pd()
t.begin_fill()
t.seth(-130)
t.circle(100, 10)
t.circle(300, 30)
t.seth(0)
t.fd(230)
t.seth(90)
t.circle(300, 30)
t.circle(100, 3)
t.color((255, 155, 192), (255, 100, 100))
t.seth(-135)
t.circle(-80, 63)
t.circle(-150, 24)
t.end_fill()
# 手
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(-40)
t.seth(0)
t.fd(-27)
t.pd()
t.seth(-160)
t.circle(300, 15)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-10)
t.circle(-20, 90)
t.pu()
t.seth(90)
t.fd(30)
t.seth(0)
t.fd(237)
t.pd()
t.seth(-20)
t.circle(-300, 15)
t.pu()
t.seth(90)
t.fd(20)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-170)
t.circle(20, 90)
# 脚
t.pensize(10)
t.color((240, 128, 128))
t.pu()
t.seth(90)
t.fd(-75)
t.seth(0)
t.fd(-180)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20)
t.pensize(10)
t.color((240, 128, 128))
t.pu()
t.seth(90)
t.fd(40)
t.seth(0)
t.fd(90)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20)
# 尾巴
t.pensize(4)
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(70)
t.seth(0)
t.fd(95)
t.pd()
t.seth(0)
t.circle(70, 20)
t.circle(10, 330)
t.circle(70, 30)
t.exitonclick()

来源:https://blog.csdn.net/July__July/article/details/99543992
在这里插入图片描述

6.2 钟表

import turtle as t
import datetime as d


def skip(step):  # 抬笔,跳到一个地方
    t.penup()
    t.forward(step)
    t.pendown()


def drawClock(radius):  # 画表盘
    t.speed(0)
    t.mode("logo")  # 以Logo坐标、角度方式
    t.hideturtle()
    t.pensize(7)
    t.home()  # 回到圆点
    for j in range(60):
        skip(radius)
        if (j % 5 == 0):
            t.forward(20)
            skip(-radius - 20)
        else:
            t.dot(5)
            skip(-radius)
        t.right(6)


def makePoint(pointName, len):  # 钟的指针,时针、分针、秒针
    t.penup()
    t.home()
    t.begin_poly()
    t.back(0.1 * len)
    t.forward(len * 1.1)
    t.end_poly()
    poly = t.get_poly()
    t.register_shape(pointName, poly)  # 注册为一个shape


def drawPoint():  # 画指针
    global hourPoint, minPoint, secPoint, fontWriter
    makePoint("hourPoint", 100)
    makePoint("minPoint", 120)
    makePoint("secPoint", 140)
    hourPoint = t.Pen()  # 每个指针是一只新turtle
    hourPoint.shape("hourPoint")
    hourPoint.shapesize(1, 1, 6)
    minPoint = t.Pen()
    minPoint.shape("minPoint")
    minPoint.shapesize(1, 1, 4)
    secPoint = t.Pen()
    secPoint.shape("secPoint")
    secPoint.pencolor('red')
    fontWriter = t.Pen()
    fontWriter.pencolor('gray')
    fontWriter.hideturtle()


def getWeekName(weekday):
    weekName = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
    return weekName[weekday]


def getDate(year, month, day):
    return "%s-%s-%s" % (year, month, day)


def realTime():
    curr = d.datetime.now()
    curr_year = curr.year
    curr_month = curr.month
    curr_day = curr.day
    curr_hour = curr.hour
    curr_minute = curr.minute
    curr_second = curr.second
    curr_weekday = curr.weekday()
    t.tracer(False)
    secPoint.setheading(360 / 60 * curr_second)
    minPoint.setheading(360 / 60 * curr_minute)
    hourPoint.setheading(360 / 12 * curr_hour + 30 / 60 * curr_minute)
    fontWriter.clear()
    fontWriter.home()
    fontWriter.penup()
    fontWriter.forward(80)
    # 用turtle写文字
    fontWriter.write(getWeekName(curr_weekday), align="center", font=("Courier", 14, "bold"))
    fontWriter.forward(-160)
    fontWriter.write(getDate(curr_year, curr_month, curr_day), align="center", font=("Courier", 14, "bold"))
    t.tracer(True)
    print(curr_second)
    t.ontimer(realTime, 100)  # 每隔100毫秒调用一次realTime()


def main():
    t.tracer(False)   # 关闭笔的轨迹,后面一起刷新出来
    drawClock(160)
    drawPoint()
    realTime()
    t.tracer(True)    # 一次性刷新出来
    t.mainloop()
if __name__ == '__main__':
    main()

来源:https://blog.csdn.net/July__July/article/details/99543992

在这里插入图片描述

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这么神奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值