Introduction of Turtle

Turtle is a built-in drawing module in Python that requires no additional installation and is easy to use.
Turtle originally came from the Logo programming language created by Wally Feurzeig, Seymour Papert, and Cynthia Solomon in 1967.
There are many methods in Turtle, and we will only cover a few of them. For more information, please visit the official documentation, which is listed below:Turtle Official documentation

Turtle’s palette and brushes

Turtle operates in an environment that can be viewed as a blank artboard. By default, the starting position of the brush is in the middle of the artboard (0,0), forming an invisible coordinate system with pixels as the origin. We’re actually using Turtle to control the brush and draw on the palette.
The shape of the brush can be set, default is a little arrow, we can useturtle.shape('turtle')Set the brush to a turtle. The turtle’s head faces east by default. Brush shapes and colors can be set to a variety of other options, which we won’t go into here.

Draw with the Turtle

A straight line

The easiest way to draw a line is with Turtle. For example, we want to draw a 50-pixel red line:

import turtle

turtle.shape('turtle') 
turtle.color('red')
turtle.forward(50)

Copy the code

A square

import turtle

turtle.shape('turtle')
turtle.color('yellow')
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
Copy the code

Red pentacle

import turtle

turtle.color('red')
turtle.hideturtle()

turtle.begin_fill()  # start filling
for i in range(5):
  turtle.forward(50)
  turtle.right(144)
turtle.end_fill()  # End fill
Copy the code

White Baby star

import turtle
from random import randint

def draw_star():
  turtle.color('white')
  turtle.hideturtle()
  turtle.begin_fill()
  for i in range(5):
    turtle.forward(10)
    turtle.right(144)
  turtle.end_fill()

for i in range(50):
  turtle.speed(0)
  turtle.penup()
  x = randint(-150, 150)
  y = randint(-100, 100)
  turtle.goto(x, y)
  turtle.pendown()
  draw_star()

turtle.penup()
turtle.goto(0, -130)
turtle.pendown()
Copy the code