学会turtle库绘图,玩转整个冬天

4,634 阅读12分钟

Turtle,也叫海龟渲染器,使用Turtle库画图也叫海龟作图。Turtle库是Python语言中一个很流行的绘制图像的函数库。海龟渲染器,和各种三维软件都有着良好的结合。功能强大,使用方便。该渲染器的特色在于其渲染速度可以优海龟渲染器,和各种三维软件都有着良好的结合。使用之前需要导入库:import turtle

绘图命令

操纵海龟绘图有着许多的命令,这些命令可以划分为3种:

一种为运动命令; 一种为画笔控制命令; 还有一种是全局控制命令;

(1) 画笔运动命令:

命令说明
turtle.forward(distance)向当前画笔方向移动distance像素长
turtle.backward(distance)向当前画笔相反方向移动distance像素长度
turtle.right(degree)顺时针移动degree°
turtle.left(degree)逆时针移动degree°
turtle.pendown()移动时绘制图形,缺省时也为绘制
turtle.goto(x,y)将画笔移动到坐标为x,y的位置
turtle.penup()移动时不绘制图形,提起笔,用于另起一个地方绘制时用
turtle.speed(speed)画笔绘制的速度范围[0,10]整数
turtle.circle()画圆,半径为正(负),表示圆心在画笔的左边(右边)画圆

(2) 画笔控制命令:

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

(3) 全局控制命令

命令说明
turtle.clear()清空turtle窗口,但是turtle的位置和状态不会改变
turtle.reset()清空窗口,重置turtle状态为起始状态
turtle.undo()撤销上一个turtle动作
turtle.isvisible()返回当前turtle是否可见
stamp()复制当前图形
turtle.write(s[,font=("font-name",fontsize,"fonttype")])写文本,s为文本内容,font是字体的参数,里面分别为字体名称,大小和类型;font为可选项, font的参数也是可选项

(4)命令详解

  • turtle.colormode(mode)

1.0:RGB小数模式 255:RGB整数模式

  • turtle.penup() 别名 turtle.pu() 画笔抬起,不留下痕迹

  • turtle.pendown() 别名turtle.pd()`画笔落下,留下痕迹

  • turtle.pensize(width) 别名 turtle.width(width)画笔宽度

  • turtle.pencolor(color)

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

  • turtle.forword(d) 别名 turtle.fd(d)向前行进 d:行进距离,可以为负数

  • turtle.circle(r,extent=None)根据半径r,绘制一个extent角度的弧度 r:默认圆心在海龟左侧r距离的位置

  • turtle.setheading(angle) 别名 turtle.seth(angle)改变行进方向

  • angle:改变方向的角度(绝对坐标下,绝对角度)

  • turtle.left(angle) turtle.right(angle) angle:当前方向上转过得角度

让我们用 “社会人” 的方式来练习一下


from turtle import *def nose(x,y):    

"""画鼻子"""    
pensize(5)    
pencolor((255, 155, 192))    
penup()    
# 将海龟移动到指定的坐标    
goto(x,y)    
pendown()    
# 设置海龟的方向(0-东、90-北、180-西、270-南)    
setheading(-30)    
begin_fill()    
fillcolor(255, 192, 203)    
a = 0.4    
for i in range(120):        
if 0 <= i < 30 or 60 <= i <90:            
a = a + 0.08            
# 向左转3度            
left(3)            
# 向前走            
forward(a)        
else:            
a = a - 0.08            
left(3)            
forward(a)    
end_fill()    
penup()    
setheading(90)    
forward(25)    
setheading(0)    
forward(10)   
pendown()    
# 设置画笔的颜色(红, 绿, 蓝)    
pencolor(255, 155, 192)    
setheading(10)    
begin_fill()    
circle(5)    
color(160, 82, 45)    
end_fill()    
penup()    
setheading(0)    
forward(20)    
pendown()    
pencolor(255, 155, 192)    
setheading(10)    
begin_fill()    
circle(5)    
color(160, 82, 45)    
end_fill()def head(x, y):    
"""画头"""    
color((255, 155, 192), "pink")    
penup()    goto(x,y)    setheading(0)    pendown()    begin_fill()    
setheading(180)    circle(300, -30)    circle(100, -60)    
circle(80, -100)    circle(150, -20)    circle(60, -95)    
setheading(161)    circle(-300, 15)    penup()    
goto(-100, 100)    pendown()    setheading(-30)    
a = 0.4    for i in range(60):        
if 0<= i < 30 or 60 <= i < 90:            
a = a + 0.08            
lt(3) #向左转3度            
fd(a) #向前走a的步长        
else:            
a = a - 0.08            
lt(3)            
fd(a)    
end_fill()
def ears(x,y):    
"""画耳朵"""    
color((255, 155, 192), "pink")   
penup()    
goto(x, y)    
pendown()    
begin_fill()    
setheading(100)    
circle(-50, 50)    
circle(-10, 120)    
circle(-50, 54)    
end_fill()    
penup()    
setheading(90)    
forward(-12)    
setheading(0)    
forward(30)    
pendown()    
begin_fill()   
setheading(90)    
circle(-50, 50)    circle(-10, 120)    circle(-50, 56)    end_fill()def eyes(x,y):  
  """画眼睛"""    color((255, 155, 192), "white")    penup()    setheading(90)   
 forward(-20)    setheading(0)    forward(-95)    pendown()    begin_fill()    
circle(15)    end_fill()    color("black")    penup()    setheading(90)   
 forward(12)    setheading(0)    forward(-3)    pendown()   
 begin_fill()    circle(3)    end_fill()    color((255, 155, 192), "white")    
penup()    seth(90)    forward(-25)    seth(0)    forward(40)    pendown()    
begin_fill()    circle(15)    end_fill()    color("black")    penup()    setheading(90)    forward(12)    setheading(0)    forward(-3)    pendown()    begin_fill()    circle(3)    end_fill()def cheek(x,y):    """画脸颊"""    color((255, 155, 192))    penup()    goto(x,y)    pendown()    setheading(0)    begin_fill()    circle(30)    end_fill()def mouth(x,y):    """画嘴巴"""    color(239, 69, 19)    penup()    goto(x, y)    pendown()    setheading(-80)    circle(30, 40)    circle(40, 80)def body(x,y):    '''画身体'''    penup()    goto(x,y)    pencolor('red')    fillcolor(250,106,106)    pendown()    begin_fill()    setheading(-66)    circle(-450,17)    setheading(180)    forward(185)    setheading(85)    circle(-450,17)    end_fill()    '''右手'''    penup()    goto(110,-45)    pendown()    pensize(8)    pencolor(255, 192, 203)    setheading(30)    circle(-400,10)    penup()    goto(167,-5)    pendown()    setheading(-120)    forward(20)    left(100)    forward(20)    '''左手'''    penup()    goto(-25,-45)    pendown()    pencolor(255, 192, 203)    setheading(150)    circle(400,10)    penup()    goto(-78,-6)    pendown()    setheading(-60)    forward(20)    right(100)    forward(20)def feet1(x,y):    pensize(7)    pencolor(255, 192, 203)    penup()    goto(x,y)    setheading(-90)    pendown()    forward(10)    penup()    goto(x-12,y-10)    pendown()    pencolor(238,201,0)    fillcolor(238,230,132)    begin_fill()    setheading(0)    forward(24)    right(90)    forward(36)    right(90)    forward(40)    circle(-10,180)    forward(16)    left(90)    forward(12)    end_fill()def feet2(x,y):    pensize(7)    pencolor(255, 192, 203)    penup()    goto(x,y)    setheading(-90)    pendown()    forward(10)    penup()    goto(x-12,y-10)    pendown()    pencolor(238,201,0)    fillcolor(238,230,132)    begin_fill()    setheading(0)    forward(24)    right(90)    forward(36)    right(90)    forward(40)    circle(-10,180)    forward(16)    left(90)    forward(12)    end_fill()def tail(x,y):    pensize(8)    penup()    goto(x,y)    pendown()    pencolor(255, 192, 203)    setheading(-5)    circle(30,100)    circle(10,180)    circle(20,150)def backg(x):    penup()    goto(-420,x)    setheading(0)    fillcolor(50,205,50)    begin_fill()    forward(840)    right(90)    forward(300)    right(90)    forward(840)    right(90)    forward(300)    end_fill()    setheading(0)    fillcolor(0,191,255)    begin_fill()    forward(840)    left(90)    forward(600)    left(90)    forward(840)    left(90)    forward(600)    end_fill()def cloude1(x, y):    """画云"""    penup()    goto(x,y)    setheading(90)    fillcolor(255,255,255)    begin_fill()    a = 0.4    for i in range(120):        if 0 <= i < 30 or 60 <= i <90:            a = a + 0.14            # 向左转3度            left(3)            # 向前走            forward(a)        else:            a = a - 0.15            left(3)            forward(a)    end_fill()def cloude2(x, y):    """画云"""    penup()    goto(x,y)    setheading(90)    fillcolor(255,255,255)    begin_fill()    a = 0.4    for i in range(120):        if 0 <= i < 30 or 60 <= i <90:            a = a + 0.15            # 向左转3度            left(3)            # 向前走            forward(a)        else:            a = a - 0.13            left(3)            forward(a)    end_fill()def setting():    """设置参数"""    pensize(5)    # 隐藏海龟    hideturtle()    colormode(255)    color((255, 155, 192), "pink")    setup(840, 700)    speed(10)def main():    """主函数"""        setting()     backg(0)    body(105,-20)    nose(-100, 100)    head(-69, 167)    ears(0, 160)    eyes(0, 140)    cheek(80, 10)    mouth(-20, 30)    feet1(10,-150)    feet2(90,-150)    tail(130,-110)    cloude1(-200,200)    cloude2(300,300)    done()if __name__ == '__main__':    main()


turtle作品

1、五角星


import turtle

turtle.color('red','red')
turtle.begin_fill()
for i in range(5):    
    turtle.forward(100)                                   
    turtle.right(144)
turtle.end_fill()
turtle.hideturtle()
turtle.done()

2、粉色心


import turtle
t = turtle.Turtle()
t.speed(0)
def curvemove():    
    for i in range(200):        
        t.right(1)        
        t.forward(1)
t.color('red','pink')
t.begin_fill()
t.left(140)
t.forward(111.65)
curvemove()
t.left(120)
curvemove()
t.forward(111.65)
t.end_fill()
t.hideturtle()
turtle.done()

3、奥运五环


import turtle  # 导入turtle模块

turtle.width(5)  # 确定圆圈的宽度
turtle.circle(60)  # 确定圆的半径

turtle.penup()
turtle.forward(140)
turtle.pendown()
turtle.color("red")  # 确定圆圈的颜色
turtle.circle(60)

turtle.penup()
turtle.forward(140)
turtle.pendown()
turtle.color("yellow")
turtle.circle(60)

turtle.penup()           
turtle.goto(210, -50)        
turtle.pendown()              
turtle.color("blue")   
turtle.circle(60)      
           
turtle.penup()
turtle.goto(60, -50)
turtle.pendown()
turtle.color("green")
turtle.circle(60)

turtle.done()

4、时钟1

# coding=utf-8
 
import turtle
from datetime import *
 
 
# 抬起画笔,向前运动一段距离放下
def Skip(step):
    turtle.penup()
    turtle.forward(step)
    turtle.pendown()
 
 
def mkHand(name, length):
    # 注册Turtle形状,建立表针Turtle
    turtle.reset()
    Skip(-length * 0.1)
    # 开始记录多边形的顶点。当前的乌龟位置是多边形的第一个顶点。
    turtle.begin_poly()
    turtle.forward(length * 1.1)
    # 停止记录多边形的顶点。当前的乌龟位置是多边形的最后一个顶点。将与第一个顶点相连。
    turtle.end_poly()
    # 返回最后记录的多边形。
    handForm = turtle.get_poly()
    turtle.register_shape(name, handForm)
 
 
def Init():
    global secHand, minHand, hurHand, printer
    # 重置Turtle指向北
    turtle.mode("logo")
    # 建立三个表针Turtle并初始化
    mkHand("secHand", 135)
    mkHand("minHand", 125)
    mkHand("hurHand", 90)
    secHand = turtle.Turtle()
    secHand.shape("secHand")
    minHand = turtle.Turtle()
    minHand.shape("minHand")
    hurHand = turtle.Turtle()
    hurHand.shape("hurHand")
 
    for hand in secHand, minHand, hurHand:
        hand.shapesize(1, 1, 3)
        hand.speed(0)
 
        # 建立输出文字Turtle
    printer = turtle.Turtle()
 
    # 隐藏画笔的turtle形状
    printer.hideturtle()
    printer.penup()
 
 
def SetupClock(radius):
    # 建立表的外框
    turtle.reset()
    turtle.pensize(7)
    turtle.pencolor("#ff5500")
    turtle.fillcolor("green")
 
    for i in range(60):
        Skip(radius)
        if i % 5 == 0:
            turtle.forward(20)
            Skip(-radius - 20)
 
            Skip(radius + 20)
            if i == 0:
                turtle.write(int(12), align="center", font=("Courier", 14, "bold"))
            elif i == 30:
                Skip(25)
                turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))
                Skip(-25)
            elif (i == 25 or i == 35):
                Skip(20)
                turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))
                Skip(-20)
            else:
                turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))
            Skip(-radius - 20)
        else:
            turtle.dot(5)
            Skip(-radius)
        turtle.right(6)
 
 
def Week(t):
    week = ["星期一", "星期二", "星期三",
            "星期四", "星期五", "星期六", "星期日"]
    return week[t.weekday()]
 
 
def Date(t):
    y = t.year
    m = t.month
    d = t.day
    return "%s-%d-%d" % (y, m, d)
 
 
def Tick():
    # 绘制表针的动态显示
    t = datetime.today()
    second = t.second + t.microsecond * 0.000001
    minute = t.minute + second / 60.0
    hour = t.hour + minute / 60.0
    secHand.setheading(6 * second)
    minHand.setheading(6 * minute)
    hurHand.setheading(30 * hour)
 
    turtle.tracer(False)
 
    printer.forward(65)
    printer.write(Week(t), align="center",
                  font=("Courier", 14, "bold"))
    printer.back(130)
    printer.write(Date(t), align="center",
                  font=("Courier", 14, "bold"))
    printer.home()
    turtle.tracer(True)
 
    # 100ms后继续调用tick
    turtle.ontimer(Tick, 100)
 
 
def main():
    # 打开/关闭龟动画,并为更新图纸设置延迟。
    turtle.tracer(False)
    Init()
    SetupClock(160)
    turtle.tracer(True)
    Tick()
    turtle.mainloop()
 
 
if __name__ == "__main__":
    main()

时钟2


# coding=utf-8

import turtle
from datetime import * 

# 抬起画笔,向前运动一段距离放下
def Skip(step):    
    turtle.penup()    
    turtle.forward(step)    
    turtle.pendown()  

def mkHand(name, length):    
    # 注册Turtle形状,建立表针Turtle    
    turtle.reset()    
    Skip(-length * 0.1)    
    # 开始记录多边形的顶点。当前的乌龟位置是多边形的第一个顶点。    
    turtle.begin_poly()    
    turtle.forward(length * 1.1)    
    # 停止记录多边形的顶点。当前的乌龟位置是多边形的最后一个顶点。将与第一个顶点相连。    
    turtle.end_poly()    
    # 返回最后记录的多边形。    
    handForm = turtle.get_poly()    
    turtle.register_shape(name, handForm) 
 
def Init():    
    global secHand, minHand, hurHand, printer    
    # 重置Turtle指向北    
    turtle.mode("logo")    
    # 建立三个表针Turtle并初始化    
    mkHand("secHand", 135)    
    mkHand("minHand", 125)    
    mkHand("hurHand", 90)    
    secHand = turtle.Turtle()    
    secHand.shape("secHand")    
    minHand = turtle.Turtle()    
    minHand.shape("minHand")    
    hurHand = turtle.Turtle()    
    hurHand.shape("hurHand")    
 
    for hand in secHand, minHand, hurHand:        
        hand.shapesize(1, 1, 3)        
        hand.speed(0)   
      
    # 建立输出文字Turtle    
    printer = turtle.Turtle()  
   
    # 隐藏画笔的turtle形状    
    printer.hideturtle()    
    printer.penup()  


def SetupClock(radius):    
    # 建立表的外框    
    turtle.reset()    
    turtle.pensize(7)    
    turtle.pencolor("#ff5500")    
    turtle.fillcolor("green") 
    
    for i in range(60):        
        Skip(radius)        
        if i % 5 == 0:            
            turtle.forward(20)           
            Skip(-radius - 20)   
          
            Skip(radius + 20)            
            if i == 0:                
                turtle.write(int(12), align="center", font=("Courier", 14, "bold"))            
            elif i == 30:                
                Skip(25)                
                turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))                
                Skip(-25)            
            elif (i == 25 or i == 35):                
                Skip(20)                
                turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))                
                Skip(-20)            
            else:                
                turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))            
            Skip(-radius - 20)        
        else:            
            turtle.dot(5)            
            Skip(-radius)        
        turtle.right(6)  
def Week(t):    
    week = ["星期一", "星期二", "星期三",            
            "星期四", "星期五", "星期六", "星期日"]    
    return week[t.weekday()]  

def Date(t):    
    y = t.year   
    m = t.month    
    d = t.day    
    return "%s-%d-%d" % (y, m, d)  

def Tick():    
    # 绘制表针的动态显示    
    t = datetime.today()    
    second = t.second + t.microsecond * 0.000001    
    minute = t.minute + second / 60.0    
    hour = t.hour + minute / 60.0    
    secHand.setheading(6 * second)    
    minHand.setheading(6 * minute)    
    hurHand.setheading(30 * hour)   
  
    turtle.tracer(False)     

    printer.forward(65)    
    printer.write(Week(t), align="center", font=("Courier", 14, "bold"))    
    printer.back(130)    
    printer.write(Date(t), align="center", font=("Courier", 14, "bold"))    
    printer.home()    
    turtle.tracer(True)     

    # 100ms后继续调用tick    
    turtle.ontimer(Tick, 100)  

def main():    
    # 打开/关闭龟动画,并为更新图纸设置延迟。    
    turtle.tracer(False)    
    Init()    
    SetupClock(160)    
    turtle.tracer(True)    
    Tick()    
    turtle.mainloop()  

if __name__ == "__main__":    
    main()

5、树1


from turtle import *from random import *from math import *def tree(n, l):    pd() # 下笔    # 阴影效果    t = cos(radians(heading() + 45)) / 8 + 0.25    pencolor(t, t, t)    pensize(n / 3)    forward(l) # 画树枝    if n > 0:        b = random() * 15 + 10 # 右分支偏转角度        c = random() * 15 + 10 # 左分支偏转角度        d = l * (random() * 0.25 + 0.7) # 下一个分支的长度        # 右转一定角度,画右分支        right(b)        tree(n - 1, d)        # 左转一定角度,画左分支        left(b + c)        tree(n - 1, d)        # 转回来        right(c)    else:        # 画叶子        right(90)        n = cos(radians(heading() - 45)) / 4 + 0.5        pencolor(n, n*0.8, n*0.8)        circle(3)        left(90)        # 添加0.3倍的飘落叶子        if(random() > 0.7):            pu()            # 飘落            t = heading()            an = -40 + random()*40            setheading(an)            dis = int(800*random()*0.5 + 400*random()*0.3 + 200*random()*0.2)            forward(dis)            setheading(t)            # 画叶子            pd()            right(90)            n = cos(radians(heading() - 45)) / 4 + 0.5            pencolor(n*0.5+0.5, 0.4+n*0.4, 0.4+n*0.4)            circle(2)            left(90)            pu()            #返回            t = heading()            setheading(an)            backward(dis)            setheading(t)    pu()    backward(l)# 退回bgcolor(0.5, 0.5, 0.5) # 背景色ht() # 隐藏turtlespeed(0) # 速度,1-10渐进,0最快tracer(0, 0)pu() # 抬笔backward(100)left(90) # 左转90度pu() # 抬笔backward(300) # 后退300tree(12, 100) # 递归7层done()


6、树



import turtleimport randomfrom turtle import *from time import sleept = turtle.Turtle()w = turtle.Screen()def tree(branchLen, t):    if branchLen > 3:        if 8 <= branchLen <= 12:            if random.randint(0, 2) == 0:                t.color('snow')            else:                t.color('lightcoral')            t.pensize(branchLen / 3)        elif branchLen < 8:            if random.randint(0, 1) == 0:                t.color('snow')            else:                t.color('lightcoral')            t.pensize(branchLen / 2)        else:            t.color('sienna')            t.pensize(branchLen / 10)        t.forward(branchLen)        a = 1.5 * random.random()        t.right(20*a)        b = 1.5 * random.random()        tree(branchLen-10*b, t)        t.left(40*a)        tree(branchLen-10*b, t)        t.right(20*a)        t.up()        t.backward(branchLen)        t.down()def petal(m, t):  # 树下花瓣    for i in range(m):        a = 200 - 400 * random.random()        b = 10 - 20 * random.random()        t.up()        t.forward(b)        t.left(90)        t.forward(a)        t.down()        t.color("lightcoral")        t.circle(1)        t.up()        t.backward(a)        t.right(90)        t.backward(b)def main():    t = turtle.Turtle()    myWin = turtle.Screen()    getscreen().tracer(5, 0)    turtle.screensize(bg='wheat')    t.left(90)    t.up()    t.backward(150)    t.down()    t.color('sienna')    tree(60, t)    petal(100, t)    myWin.exitonclick()main()


7、树


from turtle import *from random import *from math import *def tree(n, l):    pd()    t = cos(radians(heading() + 45)) / 8 + 0.25    pencolor(t, t, t)    pensize(n / 4)    forward(l)    if n > 0:        b = random() * 15 + 10        c = random() * 15 + 10        d = l * (random() * 0.35 + 0.6)        right(b)        tree(n - 1, d)        left(b + c)        tree(n - 1, d)        right(c)    else:        right(90)        n = cos(radians(heading() - 45)) / 4 + 0.5        pencolor(n, n, n)        circle(2)        left(90)    pu()    backward(l)bgcolor(0.5, 0.5, 0.5)ht()speed(0)tracer(0, 0)left(90)pu()backward(300)tree(13, 100)done()