Detailed introduction to the use of Python's turtle library (draw arbitrary polygons, the most detailed on the entire network)

Learning the Turtle library is actually learning mathematics, and it can also increase your interest in mathematics and learning. The Turtle library can also help children better understand geometry and mathematical concepts, such as angles, proportions, properties of geometric figures, etc. It is a very interesting library in Python.

Preface

The Turtle library is a very interesting library in Python that can be used to draw various graphics, such as straight lines, circles, squares, etc. The significance of mastering the Turtle library is that it can cultivate children's creativity and imagination, allowing them to realize their own ideas by writing code, and at the same time improve their programming ability and logical thinking ability. In addition, the Turtle library can also help children better understand geometry and mathematical concepts, such as angles, proportions, properties of geometric figures, etc. Learning the Turtle library is actually learning mathematics, but it is more interesting.

Introduction to turtle library

The Turtle library is a standard library of Python that provides a drawing turtle robot. You can use Python code to control the movement and actions of the turtle robot to realize the function of drawing graphics. The Turtle library supports drawing straight lines, circles, ellipses, curves, fill colors and other functions, and can be used to draw a variety of graphics and patterns. Using the Turtle library can deepen your understanding and mastery of the Python language, and you can also perform artistic creation and educational activities.

Python has a built-in turtle library. In 1966, Seymour Papert and Wally Feurzig invented a language specifically for children to learn programming-LOGO language. Its characteristic is to command through programming. A small turtle draws on the screen. Turtle Graphics was later ported to various high-level languages. Python has built-in turtle, which basically replicates 100% of all the functions of the original Turtle Graphics.

Use of turtle library

The library needs to be imported before use. You can use from turtle import * or import turtle. The former does not require the addition of turtle, while the latter requires the addition of turtle.   

Simple example:

import turtle

# 创建一个Turtle对象
t = turtle.Turtle()

#turtle.setup(width,height,startx,starty)
# 移动Turtle对象前进100步
t.forward(100)

# 向左旋转Turtle对象90度
t.left(90)

# 移动Turtle对象前进50步
t.forward(50)

# 创建另一个Turtle对象
t2 = turtle.Turtle()

# 移动Turtle对象t2前进80步
t2.forward(80)

# 绘制线段连接两个Turtle对象的位置
t2.goto(t.xcor(), t.ycor())

# 调用done()使得窗口等待被关闭,否则将立刻关闭窗口:
turtle.done()

Draw a rectangle

Start simple and draw a rectangle.

# 导入turtle包的所有内容:
from turtle import *

# 设置笔刷宽度:
width(4)

# 前进:
forward(200)
# 右转90度:
right(90)

# 笔刷颜色:
pencolor('red')
forward(100)
right(90)

pencolor('green')
forward(200)
right(90)

pencolor('blue')
forward(100)
right(90)

# 调用done()使得窗口等待被关闭,否则将立刻关闭窗口:
done()

It can be seen from the program code that turtle drawing is to direct the turtle to move forward and turn, and the trajectory of the turtle's movement is the drawn line. To draw a rectangle, simply move the turtle forward, turn right 90 degrees, and repeat 4 times.

Call the width() function to set the brush width, and call the pencolor() function to set the color. For more operations, please refer to the instructions of the turtle library. After drawing is completed, remember to call the done() function to let the window enter the message loop and wait to be closed. Otherwise, since the Python process will end immediately, the window will be closed immediately.

Draw any polygon

Increase the difficulty and learn some mathematical geometry knowledge.

Interior angle formula of polygon: Interior angle= (n-2) * 180 / n, where n is the number of sides of the polygon.

The sum of all interior angles of a polygon is equal to 180*(n - 2), where n is the number of sides of the polygon.

Taking the regular pentagon as an example, set n to 5 and substitute it into the formula to get (5-2) * 180 / 5 = 3 * 180 / 5 = 108 degrees. Therefore, each interior angle of the regular pentagon is 108 degrees.

In fact, drawing problems like this are all mathematical problems. If you calculate the angle correctly, it will be easy to draw.

Derivation of the formula for interior angles of polygons to learn mathematical knowledge.

The interior angle of a polygon refers to the angle between any two adjacent vertices inside the polygon.

Proof 1:

Because the sum of the interior angles of each triangle is 180°, an n-sided row can be divided into n-2 triangles. Therefore, the sum of the interior angles of a polygon is equal to 180*(n - 2). Then each interior angle = (n-2) * 180 / n.

Proof method two:

The sum of the exterior angles of any convex polygon is 360°. In an n-sided polygon, the number of exterior angles at each vertex is 360°/n. Since the polygon has n vertices, the sum of the exterior angles is 360 degrees. Therefore, the formula can be obtained: n * number of external angles = 360 degrees, that is, number of external angles = 360 degrees / n. Interior angle + exterior angle = 180 degrees, you can get the interior angle formula of a polygon: interior angle = 180 degrees - (360 degrees / n) = (n - 2) * 180 degrees / n.

For example, in a triangle, the number of exterior angles at each vertex is 360° / 3 = 120°. In a quadrilateral, the number of exterior angles at each vertex is 360° / 4 = 90°. In a pentagon, the number of exterior angles at each vertex is 360° / 5 = 72°.

For example, draw several regular pentagons:

from turtle import *
import time

def draw5(x, y):
    pu()
    goto(x, y)
    pd()
    # set heading: 0
    seth(0)
    for i in range(5):
        fd(40)
        rt(72)
        time.sleep(1)

for x in range(0, 250, 50):
    draw5(x, 0)

done()

Question, how to draw a five-pointed star?

According to the above formula, if you want to draw a five-pointed star, the key is to know how much angle it turns each time?

The pentagram is 144 degrees. Why is it 144 degrees, do you know? Because the interior angle of the regular pentagon is 108 degrees, its supplementary angle is 72 degrees. Each angle of the pentagon is 180-72-72=36 degrees, so each rotation is 180-36 = 144 degrees.

#绘制一个五角星
from turtle import *
import time

def drawStar(x, y):
    pu()
    goto(x, y)
    pd()
    # set heading: 0
    seth(0)
    for i in range(5):
        fd(110)
        rt(144)
        time.sleep(1)

drawStar(0,0)

done()

By analogy, can you draw a six-pointed star?

It's also very simple. The key is to know the angle of each corner of the six-pointed star and find the steering angle. According to the formula of the interior angle of a polygon, the interior angle of a polygon = (n-2) * 180 / n, where n is the number of sides of the polygon.

First draw each small triangle, turning it 60 degrees each time, and then draw the remaining 5 small triangles. A total of 6 small triangles form a hexagon.

from turtle import *

def triangle():
    pensize(2)
    pencolor('black')
    for i in range(3):
        fd(60)
        right(120)
 
        
def test():
    colors=['green','red','yellow','pink','purple','orange']
    
    speed(1)
    
    for i in range(6):
        begin_fill()
        fillcolor(colors[i])
        triangle()
        fd(60) 
        left(60) #以坐标系为基准,左转60°
        end_fill()
    
    #填充中心颜色
    fillcolor("blue")
    begin_fill()
    for i in range(6):
        fd(60)
        left(60)
    end_fill()
    ht()#隐藏画笔
    done()
    
test()
from turtle import *
def triangle(x):
    pensize(2)
    pencolor('black')
    for i in range(3):
        fd(x)
        right(120)

def main():
    speed(8)
    colors=['green','red','yellow','blue']
    for j in range(1,7):
        for i in range(4):
            if j >= 2:
                triangle(160 + j * 10)
                left(90)
            else:
                fillcolor(colors[i])
                begin_fill()
                triangle(160)
                left(90)
                end_fill()
    ht()
main()
done()

 Guess what shape the following code will draw?

from turtle import *
def triangle():
    pensize(2)
    pencolor('black')
    for i in range(3):
        fd(160)
        right(120)

def test():
    penup()
    setpos(-100,140)#画笔移动到一个绝对坐标。(开始默认画笔居中)
    pendown()
    speed(5)
    colors=['green','red','pink','purple','blue','yellow','orange']
    for i in range(6):
        fillcolor(colors[i])
        begin_fill()
        triangle()
        fd(160)
        right(60)
        end_fill()
    ht()

#执行
test()

done()

Question, can you draw the following windmill?

draw a tornado

from turtle import *
# 龙卷风
setup(800,600)

pensize(1)

speed(6)

colors=['green','red','yellow','grey','orange','blue','pink','purple']

bgcolor('black')

for i in range(1,10):
    pencolor(colors[i%8])
    penup()
    goto(5*i,0)
    pendown()
    circle(10*i)
    
done()

 

Concentric circles (archery targets)

# 同心圆
from turtle import *
setup(800, 600, 450, 50)
pensize(5)
bgcolor('white')
speed('fastest')
colors = ['blue', 'yellow', 'red', 'green', 'white', 'black', 'orange', 'grey']
for i in range(10, 1, -1):
    penup()
    goto(0, -20 * i)
    pendown()
    begin_fill()
    fillcolor(colors[i % 4])
    circle(20 * i)
    end_fill()
hideturtle()
done()

Introduction to the main functions of turtle

absolute coordinates

The initial position of the turtle is (0, 0), located in the center of the canvas.

Turtles face to the right by default. (In the turtle module, you can use the setheading() function (can be abbreviated as seth) to set the heading of the turtle. Its function is to set the current heading of the turtle. The parameter is an integer between 0-360, which represents the direction of the turtle. Heading angle. For example, setheading(90) will make the turtle face upward, and seth(180) will make the heading point to the left.

marching function

turtle.goto(x,y, go to any position (X, Y) from the current position.

No matter where the turtle is, the direction it faces is the direction it is going.

Forward function: turtle.fd(), moves forward the specified distance.

Back function: turtle.bk(), moves backward by the specified distance.

Arc drawing function: turtle.circle(r, angle) Taking the r pixel on the left as the center of the circle, rotate the angle counterclockwise.

Orientation function: turtle.seth(angle) orients towards the absolute direction angle. (The turtle faces to the right by default. Setting it to 90 will turn it counterclockwise and point directly upward. Setting it to 180 will make it point to the left.)

The right() and left() functions are used to set the turtle's steering angle.

The right(angle) function is used to rotate the turtle to the right by a specified angle. The angle parameter is an integer that represents the angle at which the turtle should rotate. For example, right(90) will rotate the turtle 90 degrees to the right.

The left(angle) function is used to rotate the turtle to the left by a specified angle. The angle parameter is an integer that represents the angle at which the turtle should rotate. For example left(90) will rotate the turtle 90 degrees to the left. These two functions can be used to control the walking direction of the turtle and the direction of drawing graphics. When using these two functions, it is important to note that they set the relative steering angle of the turtle, not the absolute steering angle. In other words, after calling the right() function, the turtle's facing direction will rotate to the right, and after calling the left() function, the turtle's facing direction will rotate to the left.

turtle.penup() Raise the brush

turtle.pendown() pen down

turtle.pensize() Turtle waistline

turtle.pencolor() brush color

turtle.speed() sets the movement speed. The parameter value represents the speed level of the turtle. The value range is [0, 10]. Note that 0 also represents the fastest speed, 1 represents the slowest, and 10 represents the fastest. speed, the default speed should be 5 (normal).

  • If the number entered is greater than 10 or less than 0.5, the speed is set to 0.
  • Speed ​​strings are mapped to speed values ​​in the following way:
    • ‘fastest’:0
    • ‘fast’:10
    • ‘normal’:6
    • ‘slow’:3
    • ‘slowest’:1

turtle.home() returns the origin (0,0) position (center of the screen), facing right.

Draw complex graphics

Note: Some resources are quoted from "100 Examples of Python Creative Programmingturtle". If there is any infringement, please inform us to delete it.

beautiful tree

from turtle import *

# 设置色彩模式是RGB:
colormode(255)

lt(90)

lv = 14
l = 120
s = 45

width(lv)

# 初始化RGB颜色:
r = 0
g = 0
b = 0
pencolor(r, g, b)

penup()
bk(l)
pendown()
fd(l)

def draw_tree(l, level):
    global r, g, b
    # save the current pen width
    w = width()

    # narrow the pen width
    width(w * 3.0 / 4.0)
    # set color:
    r = r + 1
    g = g + 2
    b = b + 3
    pencolor(r % 200, g % 200, b % 200)

    l = 3.0 / 4.0 * l

    lt(s)
    fd(l)

    if level < lv:
        draw_tree(l, level + 1)
    bk(l)
    rt(2 * s)
    fd(l)

    if level < lv:
        draw_tree(l, level + 1)
    bk(l)
    lt(s)

    # restore the previous pen width
    width(w)

speed("fastest")

draw_tree(l, 4)

done()

Colorful boa constrictor

import turtle
turtle.setup(650, 350,200,200)
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.pensize(25)
colors=['green','blue','yellow','orange','pink','purple']
turtle.seth(-40)
for i in range(4):
    turtle.color(colors[i])#选择索引从0~3的颜色
    turtle.circle(40, 80)#上半弧度
    turtle.circle(-40, 80)#下半弧度
turtle.color(colors[5])
turtle.circle(40, 80/2)
turtle.fd(40)
turtle.circle(16, 180)
turtle.fd(40 * 2/3)

turtle.done()

Draw Peppa Pig

# coding=utf-8
 
import turtle as t
 
t.pensize(4)
t.hideturtle()
t.colormode(255)
t.color((255, 155, 192), "pink")
t.setup(840, 500)
t.speed(10)
 
# 鼻子
t.pu()
t.goto(-100, 100)
t.pd()
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.done()

Draw clocks

# -*- coding:utf-8 –*-
# 用turtlr画时钟
# 以自定义shape的方式实现
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()

Draw a lion head 

import turtle as t

def hair():  # 画头发
    t.penup()
    t.goto(-50, 150)
    t.pendown()
    t.fillcolor('#a2774d')
    t.begin_fill()
    for j in range(10):  # 重复执行10次
        t.setheading(60 - (j * 36))  # 每次调整初始角度
        t.circle(-50, 120)  # 画120度的弧
    t.end_fill()
    
def face():  # 画脸
    t.penup()
    t.goto(0, 100)
    t.pendown()
    t.fillcolor('#f2ae20')
    t.begin_fill()
    t.setheading(180)
    t.circle(85)
    t.end_fill()
    # 下巴
    t.circle(85, 120)
    t.fillcolor('white')
    t.begin_fill()
    t.circle(85, 120)
    t.setheading(135)
    t.circle(100, 95)
    t.end_fill()
    
def ears(dir):  # 画眼睛,dir用来设置方向,左右眼对称
    t.penup()
    t.goto((0 - dir) * 30, 90)
    t.setheading(90)
    t.pendown()
    t.fillcolor('#f2ae20')
    t.begin_fill()
    t.circle(dir * 30)
    t.end_fill()
    t.penup()
    t.goto((0 - dir) * 40, 85)
    t.setheading(90)
    t.pendown()
    t.fillcolor('white')
    t.begin_fill()
    t.circle(dir * 17)
    t.end_fill()
    
def nose():  # 画鼻子
    t.penup()
    t.goto(20, 0)
    t.setheading(90)
    t.pendown()
    t.fillcolor('#a2774d')
    t.begin_fill()
    t.circle(20)
    t.end_fill()
    
def eye(dir):  # 画耳朵,dir用来设置方向,左右耳对称
    t.penup()
    t.goto((0 - dir) * 30, 20)
    t.setheading(0)
    t.pendown()
    t.fillcolor('black')
    t.begin_fill()
    t.circle(10)
    t.end_fill()
    
def mouth():  # 画嘴巴
    t.penup()
    t.goto(0, 0)
    t.setheading(-90)
    t.pendown()
    t.forward(50)
    t.setheading(0)
    t.circle(80, 30)
    t.penup()
    t.goto(0, -50)
    t.setheading(180)
    t.pendown()
    t.circle(-80, 30)
    
hair()
ears(1)
ears(-1)
face()
eye(1)
eye(-1)
mouth()
nose()

t.done()

Draw a little red flower

import turtle as t

t.speed(0)
 
#花柄
t.penup()
t.goto(0,-150)
t.pendown()
t.pensize(2)
t.setheading(90)
t.color('brown')
t.fd(300)
 
#花瓣
t.pensize(1)
t.color('black','red')
t.begin_fill()
for i in range(10):
    t.left(45)
    t.circle(80,60)
    t.left(120)
    t.circle(80,60)
t.end_fill()
 
#叶子
for i in range(2):
    t.penup()
    t.goto(0,10-50*i)
    x=20+80*i
    t.setheading(x)
    t.pendown()
    t.color('brown','green')
    t.begin_fill()
    t.circle(60,60)
    t.left(120)
    t.circle(60,60)
    t.end_fill()

t.hideturtle()

Romantic Sakura

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
        ran = random ()
        # 这里相比于原来随机添加了填充的圆圈,让樱花叶子看起来更多一点
        if (ran > 0.7):
            begin_fill ()
            circle ( 3 )
            fillcolor ( 'pink' )
        # 把原来随机生成的叶子换成了统一的粉色
        pencolor ( "pink" )
        circle ( 3 )
        if (ran > 0.7):
            end_fill ()
        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.956, 0.9255, 0.9882 )  # 设置背景色(把灰色换成淡紫色)
ht ()  # 隐藏turtle
speed ( 0 )  # 速度 1-10渐进,0 最快
tracer ( 0, 0 )
pu ()  # 抬笔
backward ( 50 )
left ( 90 )  # 左转90度
pu ()  # 抬笔
backward ( 300 )  # 后退300
tree ( 12, 100 )  # 递归7层

done ()

Quote source 

Turtle Drawing - Liao Xuefeng's official website

python---turtle library (detailed explanation)_python turtle_beyond ct's blog-CSDN blog

python: turtle draws interesting small image collection_turtle drawing works-CSDN blog

Python Turtle drawing: stars in a black hole (with source code)_turtle drawing code-CSDN blog

Python turtle basic knowledge collection and drawing collection_python turtle programming code collection-CSDN blog

Python — turtle commonly used codes_python turtle programming code collection-CSDN blog

Python turtle drawing collection_Xiang Zihanlai-Huawei Cloud Developer Alliance

Guess you like

Origin blog.csdn.net/qq8864/article/details/134811126