Turtle is an interesting module in Python called Turtle Drawing. It is based on the Tkinter module and provides some simple drawing tools. Turtle drawing originally came from the Logo programming language in the 1960s. Then some cool Python programmers built turtle libraries that let other programmers just import Turtle and use turtles for drawing in Python.

The original link | turtles drawing simple tutorial

1. Basic functions

In turtle graphics, we can write commands to move a virtual (imaginary) turtle back and forth across the screen. This turtle carries a pen, and we can use this pen to draw lines wherever the turtle moves. By writing code to move turtles in all sorts of cool patterns, we can make amazing pictures. With turtle graphics, not only were we able to create impressive visuals with just a few lines of code, but we could also follow the turtle and see how each line of code affected its movement. This helps us understand the logic of the code. So turtle diagrams are often used as a way for beginners to learn Python.

1.1 Turtle Motion

This section contains some functions commonly used in motion control

turtle.goto(x,y)

The brush is positioned at the coordinate (x,y)

Turtle. forward(distance) Moves the length of distance in the forward direction

Turtle. backward(distance) Moves a long distance in a negative direction

Turtle. right(Angle) Indicates the Angle to the right

Turtle. left(Angle) Angle to the left

Turtle.home () returns to the origin

Turtle. circle(radius, extent=None, steps=None) Draw a circle radius and extent is the Angle of the circle

Turtle. speed(speed) Moves at speed

It’s pretty overwhelming to see so many functions, so let’s do an example. First draw a square with sides of 100, and then draw a 3/4 circle with a radius of 50.

# Control the brush speed
turtle.speed(5)
Position the brush at the origin
turtle.goto(0.0)
# Starting at the origin, draw a square with sides of length 100
for i in range(4) :So we're going a distance of 100
    turtle.forward(100)
    # 90 degrees to the right
    turtle.right(90)

Position the brush at the origin
turtle.home()
# Draw a circle with a radius of 100, 3/4 of it
turtle.circle(50.270)
Copy the code

Finally, the following results are obtained:

1.2 Pen Control

This section contains control functions for brushes, commonly used as follows:

Turtle.pendown (), in which case the trajectory of the movement will be drawn Pensize (width=None pen thickness turtle.pencolor(*args) pencolor turtle.fillcolor(*args) fillcolor Turtle.begin_fill () begins to fill turtle.end_fill() ends to fill turtle.write(arg, move=False, align= “left”, font=(” Arial “, 8, “Normal”)) to write words

Again, let’s do an example. Draw a square and fill it in. Finally write some words

# Control the color of the brush
turtle.pencolor('red')
# put pen to paper
turtle.pendown()
# Set the fill color
turtle.fillcolor('blue')
# start filling
turtle.begin_fill()
# Starting at the origin, draw a square with sides of length 100
for i in range(4) :So we're going a distance of 100
    turtle.forward(200)
    # 90 degrees to the right
    turtle.right(90)
# End fill
turtle.end_fill()
turtle.penup()
turtle.goto(100, -100)
turtle.write('Crossin Programming Classroom ')

Copy the code

The result is this

We can also set the brush thickness, brush speed and so on,

1.3 Window Control

There are two commonly used functions

Turtle.bgcolor (*args) Sets the background color turtle.bgpic(picName =None) Sets the background image padding code as follows

turtle.bgcolor('red')
turtle.bgpic(r'yourpic.png')
Copy the code

2. Examples of turtle mapping

We use a few simple examples to illustrate the use of turtle drawing.

2.1 Draw circles with squares

import turtle
for i in range(360):
    turtle.setheading(i)
    for i in range(4):
        turtle.forward(100)
        turtle.left(90)
Copy the code

With 360 squares spaced one degree apart, a few lines of code can produce a beautiful regular pattern.

2.2 Red pentacle

Use the Fill function to draw a big red star

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

Copy the code

The result is shown below:

2.3 exercises

More than you can say, we’ve picked out some interesting pictures from turtle on the web to try them out

eggs

# 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 Turtle
    turtle.reset()
    Skip(-length * 0.1)
    # Start recording the vertices of the polygon. The current turtle position is the first vertex of the polygon.
    turtle.begin_poly()
    turtle.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)
    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 needle
    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)
 
    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