Turtle, also known as Turtle renderer, uses the Turtle library for drawing, also known as Turtle drawing. The Turtle library is a popular Python library for drawing images. Turtle renderer, with all kinds of 3D software. Powerful and easy to use. The rendering speed of the renderer is better than that of the renderer, and a variety of 3D software has a good combination. You need to import the library before using it: Import Turtle
The drawing commands
There are many commands for manipulating turtle drawings, which can be divided into three categories:
One is movement command; One is the paintbrush control command; There are also global control commands;
(1) Brush movement command:
The command | instructions |
---|---|
turtle.forward(distance) | Moves the distance pixel length to the current brush direction |
turtle.backward(distance) | Moves the distance pixel length in the opposite direction of the current brush |
turtle.right(degree) | Move clockwise by degree degree |
turtle.left(degree) | Move counterclockwise by degree degrees |
turtle.pendown() | Draws while moving, also draws by default |
turtle.goto(x,y) | Move the brush to x,y |
turtle.penup() | When moving without drawing, lift the pen for drawing in another place |
turtle.speed(speed) | Brush drawing speed range [0,10] integer |
turtle.circle() | Draw a circle with a radius of positive (negative), meaning the center of the circle is drawn to the left (right) of the brush |
(2) Brush control command:
The command | instructions |
---|---|
turtle.pensize(width) | The width when drawing the graph |
turtle.pencolor() | The brush color |
turtle.fillcolor(colorstring) | Draw the fill color of the graph |
turtle.color(color1, color2) | Set pencolor=color1 and fillcolor=color2 |
turtle.filling() | Returns whether the current state is filled |
turtle.begin_fill() | Ready to fill the graph |
turtle.end_fill() | Fill completed; |
turtle.hideturtle() | Hide arrow display; |
turtle.showturtle() | Corresponds to the hideturtle() function |
(3) Global control command
The command | instructions |
---|---|
turtle.clear() | Clear the Turtle window, but the position and status of Turtle will not change |
turtle.reset() | Clear the window and reset turtle to the start state |
turtle.undo() | Undo the previous turtle action |
turtle.isvisible() | Returns whether the current Turtle is visible |
stamp() | Copy current graph |
turtle.write(s[,font=(“font-name”,fontsize,”fonttype”)]) | Write text, s is the text content, font is the font parameter, inside the font name, size and type respectively; Font is optional, and the parameter of font is optional |
(4) Detailed command explanation
-
turtle.colormode(mode)
1.0:RGB decimal mode 255:RGB integer mode
-
Turtle.penup () alias turtle.pu() the brush is lifted without leaving a trace
-
Turtle.pendown () alias turtle.pd() ‘the brush falls, leaving a trace
-
Turtle.pensize (width) Alias turtle.width(width) Brush width
-
turtle.pencolor(color)
Pencolor ((0.63,0.13,0.94))RGB tuple value turtle.pencolor((0.63,0.13,0.94))RGB tuple value
-
Turtle.forword (d) alias turtle.fd(d) Forward travel d: distance traveled, which can be a negative number
-
Turtle.circle (r,extent=None) Draws an extent Angle radian r based on radius r: the default center is r distance to the left of the turtle
-
Turtle.setheading (Angle) alias turtle.seth(Angle) changes direction
-
Angle: the Angle at which the direction is changed (absolute coordinates, absolute Angle)
-
Turtle. left(Angle) turtle.right(Angle) Angle: Angle turned in the current direction
Let’s practice this in a “social person” way
from turtle import *def nose(x,y):
"""Draw the nose"""
pensize(5)
pencolor((255, 155, 192))
penup()
# Move the turtle to the specified coordinates
goto(x,y)
pendown()
# Set the direction of the turtle (0-east, 90-north, 180-west, 270-south)Setheading (-30) begin_fill() fillcolor(255, 192, 203) a = 0.4for i in range(120):
if 0 <= i < 30 or 60 <= i <90:
a = a + 0.08
Turn left 3 degrees
left(3)
# forward
forward(a)
else: a = a-0.08 left(3) forward(a) end_fill() penup() setheading(90) forward(25) setheading(0) forward(10) pendown()# Set the brush color (red, green, blue)
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):
"""Painting head"""
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) Turn left 3 degrees
fd(a) # Take a step forward
else: a = a -0.08lt (3) fd(a) end_fill() def ears(x,y):"""Draw ears."""
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):
"""Draw the eyes.""" 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): """Painting cheeks.""" color((255, 155, 192)) penup() goto(x,y) pendown() setheading(0) begin_fill() circle(30) end_fill()def mouth(x,y): """Draw the mouth.""" color(239, 69, 19) penup() goto(x, y) pendown() setheading(-80) circle(30, 40) circle(40, 80)def body(x,y): ' ''Draw the body'' ' penup() goto(x,y) pencolor('red'Fillcolor (250,106,106) begin_fill() setheading(-66) circle(-450,17) setheading(180) forward(185) Circle setheading (85) (450) end_fill ()' ''right'' 'penup() goto(110,-45) pendown() pensize(8) pencolor(255, 192, Goto (167,-5) Pendown () setheading(-120) forward(20) left(100) forward(20)' ''the left'' 'penup() goto(-25,-45) pendown() pencolor(255, 192, Goto (-78,-6) Pendown () setheading(-60) forward(20) right(100) forward(20)def feet1(x,y): pensize(7) pencolor(255, 192, Goto (x-12,y-10) pendown() 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, Goto (x-12,y-10) pendown() 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, Circle (10, 100) circle(10,180) def backg(x): Penup () goto(-420,x) setheading(0) fillcolor(50,205,50) begin_fill() right(90) right(90) Fill (840) right(90) forward(300) end_fill() setheading(0) fillcolor(0,191,255) begin_fill() left(90) forward(600) left(90) forward(840) left(90) forward(600) end_fill()def cloude1(x, y):"""Painting"""Penup () goto(x,y) setheading(90) fillcolor(255,255,255) fill() a = 0.4for i in range(120): if 0 <= i < 30 or 60 <= i <90: a = a + 0.14 Cloude2 (x, y) def cloude2(x, y): def cloude2(x, y): Fill () a = 0.4 for I in range(120): begin_fill() a = 0.4 for I in range(120): If 0 <= I < 30 or 60 <= I <90: a = a + 0.15 # left(3) # forward(a) else: A = a-0.13 left(3) forward(a) def setting(): Pensize (5) # hideturtle() colormode(255) color(255, 155, 192), "pink") setup(840, 700) speed(10)def main(): """ main function """ setting() backg(0) body(105,-20) nose(-100, 100) head(-69, 167) ears(0, 160) eyes(0, 140) cheek(80, 50) 10) mouth(-20, 30) feet1 feet2 (10-150) (90-150) tail (130-110) cloude1 cloude2 (200200) (300300) done () if __name__ = = "__main__ ': main()Copy the code
Turtle works
1. Pentagram
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()Copy the code
2. Pink Heart
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'Curvemove () t.curve (120) t.curve () t.curve (111.65) t.end_fill() t.hideturtle() turtle.done()Copy the code
The Olympic Rings
import turtle Import the Turtle module
turtle.width(5) # Determine the width of the circle
turtle.circle(60) # Determine the radius of the circle
turtle.penup()
turtle.forward(140)
turtle.pendown()
turtle.color("red") # Determine the color of the circle
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()Copy the code
4. Clock 1
# coding=utf-8
import turtle
from datetime import *
# Lift the brush, move it forward for some distance and put it down
def Skip(step):
turtle.penup()
turtle.forward(step)
turtle.pendown()
def mkHand(name, length):
# Register the Turtle shape and create the watchpin TurtleTurtle. Reset () Skip (- length * 0.1)# Start recording the vertices of the polygon. The current turtle position is the first vertex of the polygon.Turtle turtle. Begin_poly (). The forward (length * 1.1)# Stop recording vertices of polygons. The current turtle position is the last vertex of the polygon. It's going to be connected to the first vertex.
turtle.end_poly()
# return the last recorded polygon.
handForm = turtle.get_poly()
turtle.register_shape(name, handForm)
def Init():
global secHand, minHand, hurHand, printer
# reset Turtle to point north
turtle.mode("logo")
Create three pins Turtle and initialize
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)
# create the output text Turtle
printer = turtle.Turtle()
# Hide the turtle shape of the brush
printer.hideturtle()
printer.penup()
def SetupClock(radius):
Create table outer box
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 = ["Monday"."Tuesday"."Wednesday"."Thursday"."Friday"."Saturday"."Sunday"]
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():
Draw the dynamic display of the needleT = datetime.today() second = t.second + t. icrosecond * 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)
Continue to call tick after # 100ms
turtle.ontimer(Tick, 100)
def main():
# Turn turtle animation on/off and set delay for updating drawings.
turtle.tracer(False)
Init()
SetupClock(160)
turtle.tracer(True)
Tick()
turtle.mainloop()
if __name__ == "__main__":
main()Copy the code
The clock 2
# coding=utf-8
import turtle
from datetime import *
# Lift the brush, move it forward for some distance and put it down
def Skip(step):
turtle.penup()
turtle.forward(step)
turtle.pendown()
def mkHand(name, length):
# Register the Turtle shape and create the watchpin TurtleTurtle. Reset () Skip (- length * 0.1)# Start recording the vertices of the polygon. The current turtle position is the first vertex of the polygon.Turtle turtle. Begin_poly (). The forward (length * 1.1)# Stop recording vertices of polygons. The current turtle position is the last vertex of the polygon. It's going to be connected to the first vertex.
turtle.end_poly()
# return the last recorded polygon.
handForm = turtle.get_poly()
turtle.register_shape(name, handForm)
def Init():
global secHand, minHand, hurHand, printer
# reset Turtle to point north
turtle.mode("logo")
Create three pins Turtle and initialize
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)
# create the output text Turtle
printer = turtle.Turtle()
# Hide the turtle shape of the brush
printer.hideturtle()
printer.penup()
def SetupClock(radius):
Create table outer box
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 = ["Monday"."Tuesday"."Wednesday"."Thursday"."Friday"."Saturday"."Sunday"]
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():
Draw the dynamic display of the needleT = datetime.today() second = t.second + t. icrosecond * 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)
Continue to call tick after # 100ms
turtle.ontimer(Tick, 100)
def main():
# Turn turtle animation on/off and set delay for updating drawings.
turtle.tracer(False)
Init()
SetupClock(160)
turtle.tracer(True)
Tick()
turtle.mainloop()
if __name__ == "__main__":
main()Copy the code
5, 1 tree
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) # draw tree if n > 0: D = l * (random() * 0.25 + 0.7) # the length of the next branch # Right (b) tree(n-1, D) # left(b + c) tree(n-1, D) # right(c) else: N = cos(radians(heading() -45)) / 4 + 0.5 pencolor(n, n*0.8, N *0.8) circle(3) left(90) # if(random() > 0.7: Pu () # falling 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) # draw leaf pd() right(90) n = cos(radians(heading() -45)) / 4 + 0.5 Pencolor (+ n * n * 0.5 + 0.5, 0.4, 0.4 0.4+n*0.4) circle(2) left(90) pu() # return t = heading() setheading(an) backward(dis) setheading(t) pu() backward(l)# Return bgColor (0.5, 0.5, 0.5) # Background color HT () # Hide Turtlespeed (0) # Speed, 1-10 progression, 0 fastest tracer(0, 0)pu() # Backward (100)left(90) # Left (90) # Backward (300) # back 300tree(12, 100) # Recursion 7 layer done()Copy the code
6, trees,
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()Copy the code
7, trees,
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)ifn > 0: B = random() * 15 + 10 C = random() * 15 + 10 D = l * (random() * 0.35 + 0.6) 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) tree (13, 100) (300).done(a)Copy the code