[module usage] use of turtle library and example demonstration

1. turtle Library - concept

1.1 turtle Library - definition of turtle Library

1.1.1 turtle Library - what is a turtle library?

Professional Edition: the turtle library is a third-party module of Python language. It is a simple and easy-to-use programming language developed by Wally Feurzig and Seymour Papert in 1966. Now it has become a very popular function library for drawing images in Python language.

Popular version: the turtle library is a library used by Python to draw pictures. There are many drawing commands (tools) in this library. Drawing with the turtle library is to control the movement of the brush, and the trajectory of the brush movement is the drawing.

1.2 Tuttle Library - Tuttle library coordinate system

1.2.1 turtle library standard coordinate angle system

1.2.2 turtle library logo coordinate angle system

# Switch coordinate and angle systems
# mode('standard')
mode('logo')

2. turtle Library - use

2.1 turtle Library - three ways to import turtle Library

2.1.1 mode ①: import turtle

import turtle

turtle.forward(100) # The brush advances 100 PX in the specified direction (right by default) (PX is pixel, resolution unit, representing pixel)

2.1.2 mode ②: import turtle as t

import turtle as t

t.forward(100)

2.1.3 mode ③: from turbine import * (omitted quotation)

from turtle import *

forward(100)

2.2 turtle Library - canvas and window

   in short, the screensize() function is used to set the size of the canvas and the setup() function is used to set the size of the window. The relationship between canvas and window is that window contains canvas.
  when the window is larger than the canvas, the canvas will fill the window.
  when the window is smaller than the canvas, a scroll bar appears.

2.2.1 canvas - the screensize() function sets the canvas size and background color

   at first, the size of the window is only 400px long and 300px wide, and the default background color is white. Therefore, when we set the canvas to a green canvas of 800px long and 400px wide, we can only see the green canvas of (400px, 300px). At this time, a scroll bar will appear, that is, if the window is smaller than the canvas, a scroll bar will appear.

import turtle


# turtle.screensize() is the default value of canvas = length: 400, width: 300, background color: white
turtle.screensize()
turtle.done()  			# Stops drawing with the brush, but the drawing window does not close

# Write out parameter name
turtle.screensize(canvwidth=800, canvheight=400, bg="green")
turtle.done()               # Stops drawing with the brush, but the drawing window does not close

# Omit parameter name
turtle.screensize(800, 400, "red")
turtle.done()               # Stops drawing with the brush, but the drawing window does not close

2.2.2 window (form) - turtle The setup() function sets the window size and position

Because after setting the canvas, the window size will not change. If you want to change it, you can only set it through the setuo() function

import turtle

turtle.screensize(800,400,"blue") # At this time, the window size remains (400300), and the canvas size changes to (800400)
turtle.setup(800,400)		      # At this time, the window size becomes (800300) and is located in the center of the screen
turtle.done()                     # Stops drawing with the brush, but the drawing window does not close

When the canvas parameter is not set, the default canvas is considered to be used. When the window is larger than the canvas, the canvas will fill the window.

import turtle


# When width and height are integers
turtle.setup(800,400)       # At this time, the window size becomes (800400) and is located in the center of the screen
turtle.done()               # Stops drawing with the brush, but the drawing window does not close

turtle.setup(800,400,0,0)   # At this time, the window size changes to (800400), which is located in the upper left corner of the screen
turtle.done()               # Draw window, but do not close the brush

import turtle


# When decimal is used for width and height
turtle.setup(1.0,1.0)       # Using the default canvas settings, the window occupies the entire screen
turtle.done()               # Stops drawing with the brush, but the drawing window does not close
turtle.setup(1.0,0.5)       # Using the default canvas settings, the window occupies half the screen horizontally
turtle.done()               # Stops drawing with the brush, but the drawing window does not close

2.3 turtle Library - brush parameters

   on the canvas, there is a coordinate axis whose coordinate origin is the center of the canvas by default, and there is a small turtle facing the positive direction of the X axis on the coordinate origin. Here we use two words to describe the little turtle: the coordinate origin (position), facing the positive direction of the x-axis (direction). In turtle drawing, we use the position direction to describe the state of the little turtle (brush).

2.3.1 the width - pensize() function sets the thickness of the brush

import turtle           # Import tuetle Library


# Set the brush thickness (if the fan direction is not specified, the brush defaults to the right)
turtle.pensize(10)       # The size of the brush is 10
turtle.pensize(50)		      
turtle.pensize(100)		

2.3.2 color - the pencolor() function sets the color of the brush

About brush colors and fill colorsThree primary color values (Red, Green, Blue)
White: white(255,255,255)
balck: Black(0,0,0)
red: red(255,0,0)
green: green(0,255,0)
Bull: Blue(0,0,255)
Grey: grey(128,128,128)
purple: purple(255,0,255)
Yellow: yellow(255,255,0)
import turtle           # Import tuetle Library


turtle.pencolor()  		# The default color of the brush is black
turtle.pencolor("red")  
turtle.pencolor("blue")  

2.3.3 moving speed - turbine The speed() function sets the speed at which the brush moves

turtle.speed(speed): set the moving speed of the brush (the speed range of brush drawing is an integer [0,10], and the larger the number, the faster)

import turtle           # Import tuetle Library


turtle.speed(1)			 # Brush movement speed is 1
turtle.speed(speed=5)
turtle.speed(speed=10)

2.4 turtle Library - common drawing functions

2.4.1 done() function - stops the brush drawing, but the drawing window does not close

In the turtle library, the done() function stops the brush and prevents the painting window from closing. If the next code needs a brush, the brush will not start again.

import turtle

turtle.forward(100)
turtle.done()
turtle.left(60)
turtle.forward(100)

2.4.2 forward() function - moves distance pixels in the direction of the current brush

import turtle           # Import tuetle Library

turtle.forward(distance=100)     # The brush draws in the right direction by default, with a length of 100px
turtle.forward(100)     		 # Omit parameter name
turtle.done()                    # Stops drawing with the brush, but the drawing window does not close

2.4.3 backward() function - moves a distance pixel length in the opposite direction of the current brush

import turtle
turtle.backward(distance=100)
turtle.backward(100)			# Omit parameter name
turtle.done()                   # Stops drawing with the brush, but the drawing window does not close

2.4.4 right() function - move degree clockwise

import turtle

turtle.right(60)			# With reference to the standard coordinate system, the arrow rotates clockwise by 60 °
turtle.forward(100)			# Then move the length of 100px
turtle.done()               # Stops drawing with the brush, but the drawing window does not close

2.4.5 left() function - move degree counterclockwise

import turtle

turtle.left(60)			    # With reference to the standard coordinate system, the arrow rotates 60 ° counterclockwise first
turtle.forward(100)			# Then move the length of 100px
turtle.done()               # Stops drawing with the brush, but the drawing window does not close

2.4.6 penup() function - lift the brush and do not display the moving track

When the brush is raised, no lines will be drawn when moving.

import turtle

turtle.penup()  # Lift the brush
turtle.forward(100)
turtle.done()

2.4.7 pendown() function - drop the brush to display the moving track

   it is often used in pairs with the penup() function. After the brush falls, the moving track will be displayed again when moving.
   simply put, first use the pendown() function to write, and then use the penup() function to lift the pen after drawing a figure. Now that we have finished drawing a figure, we use the pendown() function to write and start drawing the second figure, and then penuo() function to lift the pen after drawing the second figure, and so on.

import turtle


turtle.forward(50)


turtle.penup()          # Lift the brush
turtle.forward(50)


turtle.pendown()        # Drop the brush
turtle.forward(50)


turtle.done()

2.4.8 goto() function - move the track from the origin to the specified coordinates

import turtle


turtle.goto(100,200)
turtle.done()

2.4.9 circle() function - draw a circle with radius r

If the radius of the circle is positive, the center of the circle will draw a circle on the left side of the brush (y positive half axis)
If the radius of the circle is negative, the center of the circle will draw a circle on the right side of the brush (y negative half axis)

import turtle

turtle.pendown()
turtle.circle(r=100)	# If you omit the name, you can directly write turtle circle(100)
turtle.penup()

turtle.pendown()
turtle.circle(r=-100)
turtle.penup()
turtle.done()

2.4.10 turtle.shape(') function - the brush arrow turns into a little turtle

import turtle

turtle.shape("turtle")
turtle.forward(100)
turtle.done()

2.4.11 hideturttle() function - Hide brush arrow

import turtle

turtle.hideturtle()
turtle.forward(100)
turtle.done()

2.4.12 showturtle() function - display brush arrow

import turtle

# Hide arrows, show tracks
turtle.pendown() 
turtle.hideturtle()
turtle.forward(100)

# Hide arrows, hide tracks
turtle.penup()
turtle.forward(100)

# Show arrows, show tracks
turtle.pendown()
turtle.showturtle()
turtle.forward(100)

turtle.done()

2.4.13 fillcolor() function, begin_fill() function, end_fill() function - fills the drawing with color

import turtle 


turtle.fillcolor('green')  # Sets the color of the fill

turtle.begin_fill()        # Start fill color
for j in range(4):
    turtle.forward(100)
    turtle.left(90)
turtle.end_fill()          # End fill color
turtle.done()

2.4.14 turtle.color(color1, color2) function - sets the brush color and fill color at the same time

import turtle 


turtle.color("red","blue")  # The brush color is set to red and the fill color is set to blue

turtle.begin_fill()  # Start fill color
for j in range(4):
    turtle.forward(100)
    turtle.left(90)
turtle.end_fill()  # End fill color
turtle.done()

2.4.15turtle.write() function - write text

import turtle

import turtle

turtle.write(arg="If he is snowed at the same time, he will be white headed all his life", move=False, align='left', font=('Arial', 16, 'normal'))
turtle.hideturtle()
turtle.done()

2.5 turtle Library - example demonstration

2.5.1 example demonstration - five color filled square combination pattern

import turtle 


def drawRect():
    turtle.hideturtle()
    turtle.pendown()
    for i in range(4):
        turtle.forward(100)
        turtle.left(90)
        turtle.speed(10)
    turtle.penup()


def main():
    clrs = ['red', 'green', 'blue', 'gray', 'brown']  # Color list
    for i in range(10):
        turtle.fillcolor(clrs[i % 5])                      # Select a color from the list
        turtle.begin_fill()                                # Start filling
        drawRect()
        turtle.end_fill()                                  # End filling
        turtle.right(36)

    turtle.done()


if __name__ == '__main__':
    main()

2.5.2 example demonstration - five pointed star

# coding=utf-8
import turtle
import time

turtle.pensize(5)
turtle.pencolor("yellow")
turtle.fillcolor("red")

turtle.begin_fill()
for _ in range(5):
  turtle.forward(200)
  turtle.right(144)
turtle.end_fill()
time.sleep(2)

turtle.penup()
turtle.goto(-150, -120)
turtle.color("violet")
turtle.write("Done", font=('Arial', 40, 'normal'))

turtle.done()

2.5.3 example demonstration - display text as a circle

#Displays the text as a circle
import turtle
text = "When drunk, I don't know the sky is in the water. The boat is full of clear dreams and the Star River is pressed"
turtle.penup()          # It can be abbreviated as pu
x = len(text)
for i in text:
    turtle.write(i, font='consolas')
    turtle.right(360/x)  # It can be abbreviated as rt
    turtle.penup()
    turtle.forward(30)   # It can be abbreviated as fd
turtle.hideturtle()
turtle.done()

2.5.4 example demonstration - clock

# coding=utf-8

import turtle
from datetime import *

# Lift the brush, move it forward a 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 watch needle Turtle
    turtle.reset()
    Skip(-length * 0.1)
    # Start recording the vertices of the polygon. The current tortoise position is the first vertex of the polygon.
    turtle.begin_poly()
    turtle.forward(length * 1.1)
    # Stops recording the vertices of the polygon. The current tortoise position is the last vertex of the polygon. Connect to the first vertex.
    turtle.end_poly()
    # Returns the last recorded polygon.
    handForm = turtle.get_poly()
    turtle.register_shape(name, handForm)


def Init():
    global secHand, minHand, hurHand, printer
    # Reset Turtle pointing North
    turtle.mode("logo")
    # Create and initialize the three watch pins Tuttle
    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 output text Tuttle
    printer = turtle.Turtle()
    # Hide the turtle shape of the brush
    printer.hideturtle()
    printer.penup()


def SetupClock(radius):
    # Create table outline
    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 watch 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 calling tick after 100ms
    turtle.ontimer(Tick, 100)


def main():
    # Turn turtle animation on / off and set a delay for updating drawings.
    turtle.tracer(False)
    Init()
    SetupClock(160)
    turtle.tracer(True)
    Tick()
    turtle.mainloop()


if __name__ == "__main__":
    main()

3. References

Detailed explanation of Python drawing Turtle Library: https://blog.csdn.net/zengxiantao1994/article/details/76588580
Python easy to learn (III) turtle drawing: https://blog.csdn.net/weixin_34050427/article/details/88677104
python - basic introduction to turtle Library: https://zhuanlan.zhihu.com/p/64594462
Detailed explanation of functions of Tuttle code I: https://blog.csdn.net/weixin_44527588/article/details/98302740
setup and screen: https://blog.csdn.net/piglite/article/details/105332460
Python turtle.write() usage and code example: https://vimsky.com/examples/usage/turtle-write-function-in-python.html
Instructions for use of turtle.write method: https://blog.csdn.net/cnds123/article/details/113915180

Keywords: Python

Added by champbronc2 on Sun, 20 Feb 2022 00:11:36 +0200