preface

This example is excerpted from the official Python library documentation. For convenience, I have modified it personally, and the related function description is not completely referring to the documentation. The execution result is posted in the result.

Please point out any errors and there will be a blog post on turtle’s implementation. Stay tuned!

Because the form of other documents on the Internet does not accord with my personal habits, I always feel not very accustomed to looking up information, so I thought to write a blog as a reference example.

When I learned about Turtle, I found that some teaching products used in youth education at home and abroad are similar to Turtle. Turtle is very good as a teaching product for teenagers in Korea.

Introduction to the

Turtle Graphics is a popular way for introducing programming to kids. Turtle Graphics is a good way to introduce introductory programming to teenagers. For me personally, English is not our first language, and some students’ English level is not too good, which will cause some difficulties in learning programming. Although these difficulties are not the main reason for deciding whether to learn or not, they also play a certain role in hindering the learning. If turtle is taught in Korea, it can be used as a turtle for students in grade 5 and above in elementary school, using students in Shenzhen as an example. For them, Turtle brings a hands-on experience of “professional programming” that no other educational product can provide; That’s probably the difference between a simulated environment and a real one. (Of course, professional programmers will have no problem using Turtle, which is why I said earlier that the Python library experience is close to “professional.”)

Turble was developed by Wally Feurzig and Seymour Papert in 1966.

Turtle’s basic development revolves around a 2D plane in which the main character is a small arrow; The arrow looks like a baby turtle and is programmed to draw line segments by moving them around the screen. A variety of patterns can be formed from these lines, and if your drawing skills are not so good, you may be surprised to learn how to draw in Turtle!

In the official documentation, this is done in an interactive manner. In this article, it is not done in an interactive manner. Considering the popularity of programming in recent years, this paper will try to explain in detail, but some in-depth knowledge will not explain (write an implementation analysis later), generally speaking, simple and practical only need to understand how to use; Please understand. If you are an experienced developer and want to learn about the implementation process, stay tuned for my next article.

Note that python using Turtle is a version that requires Tk support. Tkinter is a GUI toolkit for the standard Python interface Tk. You can check whether it is installed by using the command Python -m Tkinter. It is installed if a simple window appears. Tk and Tkinter are available on most Unix platforms as well as Windows systems. Click on the official documentation for details on Tk.

Basic programming instructions

The following programming instructions are excerpted from the official documentation (no need for beginners in this document).

In programming, there are basically two + two classes used:

  1. The TurtleScreen class will draw a 2D plane, turtle is the drawing pen. Its constructor takes either a tkinter. Canvas or a ScrolledCanvas as an argument. Turtle should be used when the application uses it. The Screen() function returns a singleton of TurtleScreen subclasses. This function should be used when Turtle is used as a separate drawing tool.
  2. RawTurtle alias is RawPen, which defines Turtle objects drawn on TurtleScreen. Its constructor requires a Canvas, which can be ScrolledCanvas or TurtleScreen as arguments. As mentioned earlier, TurtleScreen will draw a 2D plane for Turtle to draw, so RawTurtle objects know where to draw. Derived from RawTurtle is the subclass Turtle (alias :), which uses an “instance of Screen” (if it does not already exist) to automatically create a Pen.

All methods of RawTurtle/Turtle also exist as functions, which are part of the process-oriented interface.

The procedure interface provides functions derived from methods of the classes Screen and Turtle. They have the same name as the corresponding method. Screen objects are automatically created every time a function derived from the screen method is called. An (unnamed) Turtle object is automatically created whenever any function derived from turtle methods is called.

Function list

In Turtle, the Turtle methods are Turtle movement, pen control, and Turtle state. TurtleScreen methods are divided into window control, animation control, screen events, special methods, input methods, screen facing special methods.

The Turtle movement has the following functions: draw and move:

  • forward() | fd()
  • backward() | bk() | back()
  • right() | rt()
  • left() | lt()
  • goto() | setpos() | setposition()
  • setx()
  • sety()
  • setheading() | seth()
  • home()
  • circle()
  • dot()
  • stamp()
  • clearstamp()
  • clearstamps()
  • undo()
  • speed()

Get turtle status:

  • position() | pos()
  • towards()
  • xcor()
  • ycor()
  • heading()
  • distance()

Setting and measurement:

  • degrees()
  • radians()

Pen Control -> Draw State:

  • pendown() | pd() | down()
  • penup() | pu() | up()
  • pensize() | width()
  • pen()
  • isdown()

Color control:

  • color()
  • pencolor()
  • fillcolor()

Fill:

  • filling()
  • begin_fill()
  • end_fill()

More drawing controls:

  • reset()
  • clear()
  • write()

Pen Status -> Visibility:

  • showturtle() | st()
  • hideturtle() | ht()
  • isvisible()

Appearance:

  • shape()
  • resizemode()
  • shapesize() | turtlesize()
  • shearfactor()
  • settiltangle()
  • tiltangle()
  • tilt()
  • shapetransform()
  • get_shapepoly()No completion

Events:

  • onclick()
  • onrelease()
  • ondrag()

Some special methods of Turtle:

  • begin_poly()
  • end_poly()
  • get_poly()
  • clone()
  • getturtle() |
  • getpen()
  • getscreen()
  • setundobuffer()
  • undobufferentries()

Screen methods are as follows: window control:

  • bgcolor()
  • bgpic()
  • clear() | clearscreen()
  • reset() | resetscreen()
  • screensize()
  • setworldcoordinates()

Animation control:

  • delay()
  • tracer()
  • update()

Screen events:

  • listen()
  • onkey() | onkeyrelease()
  • onkeypress()No completion
  • onclick() | onscreenclick()
  • ontimer()
  • mainloop() | done()No completion

Settings and special methods:

  • mode()No completion
  • colormode()No completion
  • getcanvas()
  • getshapes()
  • register_shape() | addshape()No completion
  • turtles()
  • window_height()
  • window_width()

Input method:

  • textinput()
  • numinput()

Special way to face the screen:

  • bye()
  • exitonclick()No completion
  • setup()
  • title()

Function usage and examples

Turtle Movement

forward() | fd()

The command syntax is turtle.forward(distance) turtle.fd(distance) Parameter description: Distance to a number (integer or floating point) (note: The distance is in pixels) Example code:

from turtle import *
forward(25)
input(a)Copy the code

Code Meaning:

from turtle import *After turtle was installed, I used from to introduce Turtle and import all of its modules, so I used import *;

forward(25)Since I introduced Turtle, INSTEAD of using turtle for calls, I use methods directly; Use forward to draw a line in one direction. The line goes to the right by default, in the direction indicated by the arrow, and is drawn in action. This method takes the length of the line segment you want to draw, or the distance you want the Turtle to trace.

input()If input is not applied, the window will flash by. Using input allows you to see how it works. Of course, some ides or editors have this feature by default.

The running results are as follows:



If the above examples do not highlight the distance of the line segment well, you can increase the distance length; Now I have changed the length to 300 and changed the code to:

from turtle import *
forward(300)
input(a)Copy the code

The running effect is as follows:

backward()

Use the syntax: turtle.back(distance) turtle.bk(distance) turtle.Backward (distance) Passing in parameters: Distance number moves the turtle backward a distance opposite to the direction the turtle is going. You can’t change the turtle’s direction. Example:

from turtle import *
forward(300)
backward(400)
input(a)Copy the code

Backward (400) : Use backward to return turtle’s action, using a distance parameter larger than the forward length in order to highlight contrast. The bk and back methods can also be used, and the effect is the same:

from turtle import *
forward(300)
bk(400)
input(a)Copy the code

Running results:

right()/left()

Use the syntax: turtle.right(Angle) turtle.rt(Angle) Argument: Angle number (integer or floating point number) Use the right method to make Turtle rotate the Angle to the right, but note that only the Angle direction is rotated, not forward. The rotation of the Angle is clockwise. You can use a plus or minus sign to indicate the direction of turning. If no sign is added, the rotation is clockwise by default. If a – sign is added, the rotation is counterclockwise. Use examples (for better comparison, I added the right turn before forward) :

from turtle import *
right(30)
forward(300)
input(a)Copy the code

Right (30) :Turn 30 degrees clockwise

Running results:



Counterclockwise turn:

from turtle import *
right(-30)
forward(300)
input(a)Copy the code

Right (30) :Turn counterclockwise 30°

Running results:



To use “right” is to turn right, and to use “left” is to turn left.

goto()

Turtle.goto (x, y=None) turtle.setpos(x, y=None) Turtle.setPosition (x, y=None) X: a number or a coordinate y: a number or nothing the area drawn in turtle is a 2D plane. The plane is positioned by coordinates. The coordinates are represented by pos in turtle and the initial position is (0,0). Code examples:

from turtle import *

goto(30.30)
input(a)Copy the code

Goto (30, 30): Jump to the coordinate point x is 30, y is 30.

Running results:



Note here that the direction of turtle has not changed.

setx()/sety()

Turtle.setx (x) Arguments: x: a number (integer or floating point) sets the value of the x coordinate with the y coordinate unchanged turtle.sety(y) arguments: y: a number (integer or floating point) sets the value of the y coordinate with the x coordinate unchanged setx examples of code:

from turtle import *

setx(10)
input(a)Copy the code

Setx (10) : Set the x coordinate to position 10

setheading() | seth()

Turtle.setheading (to_angle) Turtle.seth (to_angle) parameter:

  • To_angle: an integer (integer or floating point)

Using Setheading will set turtle’s initial state to 0°, similar to a protractor. Turtle is originally a line perpendicular to a plane and has no Angle, so it is 0. If you pass in 45 with Setheading, it will point to 45° relative to the initial state. Code examples:

from turtle import *

setheading(45)
input(a)Copy the code

Operation effect:



Seth’s method is similar.

home()

Turtle.home () moves turtle to the origin coordinate (0,0)- and sets its course to the starting direction.

from turtle import *

forward(80)
home()
input(a)Copy the code

Home () : Turtle for the initial coordinates. Running results:

circle()

Turtle. circle(radius, extent=None, steps=None) parameter:

  • Radius: indicates the digital radius
  • Extent: The number range can be empty
  • Steps: Integer can be empty

You can draw a circle, or a radian, using circle. The first parameter is the radius, and the second parameter controls how far you draw, so if you say 90, you only draw to 90 degrees. Steps are the steps, and the edges of the circle are actually jagged, equivalent to the feeling of pixels. The code will be compared to facilitate understanding. Draw an example of circular code:

from turtle import *

circle(120)
input(a)Copy the code

Code Meaning:

circle(120): a circle of radius 120

Running results:



Draw with the second parameter extent:

from turtle import *

circle(120.180)
input(a)Copy the code

Code Meaning:

Circle (120180).: a sector 120 in diameter.



Examples of code for adding the third steps parameter:

from turtle import *

circle(120.180.1)
input(a)Copy the code

Circle (120,180,1) : a sector with steps of 1.



It’s a straight line, so we changed the steps to 2,Circle (120180, 2)Running results:



It’s a crease, we changed the steps to 20,Circle (120180)Running results:



Back to normal, these are the steps steps.

dot()

Turtle. dot(size=None, *color) parameter:

  • Size: an integer greater than 0
  • Draws a size origin with a specified color.

Code examples:

from turtle import *

dot(20."blue")
input(a)Copy the code

Running results:

stamp()

Turtle.stamp () copies a turtle.

from turtle import *

stamp()
color("blue")
goto(100.0)
input(a)Copy the code

Code Meaning:

stamp(): a copy of oneself;

color("blue"): Sets the current self to blue;

Goto (100, 0): Move to the left where x is 100 and y is 0.

The results are as follows:



The black one is turtle②, and the blue one is the original color.

clearstamp()

Turtle. Clearstamp (stampid) parameters:

  • Stampid: The id value of stamp will be returned after copying a copy of itself using stamp. The copied object can be deleted by passing in the ID value.

Code examples:

from turtle import *

turtle2=stamp()
color("blue")
goto(100.0)
clearstamp(turtle2)
input(a)Copy the code

Code Meaning:

turtle2=stamp(): Receives the returned stampid

clearstamp(turtle2): Delete the copied turtle

Running results:

clearstamps()

Turtle. clearstamps(n=None) argument: an integer or empty delete all or the first/last n copies of Turtle. If n is empty, delete all turtle; If n>0, delete the first n entries. If n<0, delete the last n. Code examples:

from turtle import *
import time

for i in range(8):
    stamp(); 
    fd(10)
    
time.sleep(1)
clearstamps(2)
time.sleep(1)
clearstamps(-2)
time.sleep(1)
clearstamps()
input(a)Copy the code

For I in range(8): Loop to create 8 Turtles, each taking 10 steps; Note that when you copy it, you will have turtle as the main name, and when you copy it you will get the current location, which is turtle as the main name. Time.sleep (1) : Pause code added for better viewing. Clearstamps (2) : delete the first two turtle clearstamps(-2) : delete the second two turtle clearstamps() : delete all turtle copies

Running results:

undo()

Turtle.undo () undoes the previous turble operation. Code examples:

from turtle import *
import time

fd(100)
left(160)
fd(100)
time.sleep(1)
undo()
input(a)Copy the code

Code Meaning:

undo(): Retract the previous step

Running results:

speed()

Turtle. Speed (speed = None) parameters:

  • Speed: an integer ranging from 0 to 10.

Set the speed of turtle. Out of range is 0. The official documentation gives a reference to the speed value, and can be passed in with an identifier as a parameter, as follows:

  • “Fastest” : 0
  • “Fast” : 10
  • “Normal” : 6
  • “Missile” : 3
  • “The slowest” : 1

Code examples:

from turtle import *
import time

speed('fastest')# or use 0
circle(100)
input(a)Copy the code

Code Meaning:

speed('fastest'): To use the fastest speed, you can use 0 instead

Run result (here are two examples of results with different values) :



Pen control

Render state

penup() | pu() | up()

Turtle.penup () turtle.pu() Turtle.up () is not drawn when moving. Code examples:

from turtle import *
import time

penup()
speed('normal')# can also be replaced by 0
circle(100)
input(a)Copy the code

Code Meaning:

penup(): After using the following movement will not be drawn.

Running results:

pendown() | pd() | down()

Turtle.pendown () turtle.pd() Turtle.down () is drawn when moving. Code examples:

from turtle import *
import time

penup()
circle(100)
pendown()
circle(100)
input(a)Copy the code

Code Meaning:

pendown(): Then add a little bit of code, walk around without drawing, and finally draw again.

Running results:

pensize() | width()

Turtle. pensize(width=None) Turtle. width(width=None)

  • Width: indicates the line width, which can be empty

Sets the line width, or returns it. Code examples:

from turtle import *
import time

pensize(10)  
circle(100)
input(a)Copy the code

Code Meaning:

pensize(10): Sets the width of the code. Using the width method gives the same result

Running results:

pen()

Turtle. pen(pen=None, **pendict) parameter:

  • Pen – Has a specific identifier value
  • Pendict: Has multiple keyword arguments

Set the methods associated with pen. The following are the official Settings:

  • “To” : True/False
  • “Pendown” : True/False
  • “Pencolor” : color – string or color – a tuple
  • Fillcolor: color – string or color – a tuple
  • “Pensize” : positive number
  • Speed: number in range 0… 10
  • Resizemode: “Auto” or “user” or “noresize”
  • “Stretchfactor” : (positive number, positive number)
  • “The outline” : positive number
  • “Tilt” : the number

Multiple properties can be set in a single statement. Code examples:

from turtle import *
import time

pen(speed=10, pencolor="red", pensize=10)
circle(100)
input(a)Copy the code

Code Meaning:

pen(speed=10, pencolor="red", pensize=10): Set pen drawing speed to 10, color to red, and line size to 10.

Running results:

isdown()

Turtle.isdown () draws when it is lifted or lowered, in other words, draws when it is moved, and returns True if drawn and False otherwise. Code examples:

from turtle import *
import time

pen(speed=10, pencolor="red", pensize=10)
circle(100)
print(isdown())
penup()
pen(speed=10, pencolor="red", pensize=10)
circle(100)
print(isdown())
input(a)Copy the code

Code Meaning:

print(isdown()): is drawn by default, output pen down, output true

penup(): Use penup() to lift the pen, not only when moving, print False

Running results:

Color control

pencolor()

Turtle.pencolor (*args) Returns the color of the current line setting or the color of the set line. Pencolor passable participation without passable parameters:

  • Pencolor (): returns the current color setting without taking an argument
  • Pencolor (colorString) : You can pass in a string to set the color value
  • Pencolor ((r, g, b)) : Pass in a tuple value for setting
  • Pencolor (r, g, b) : directly assign r, g, b values

Code examples:

from turtle import *
import time

pencolor("brown")
circle(100)
input(a)Copy the code

Pencolor (“brown”) : Set the color and draw a circle. You can also use RGB to pass in the color:

from turtle import *
import time

tup = (0.2.0.8.0.55)
pencolor(tup)
circle(100)
input(a)Copy the code

Running results:

fillcolor()

Turtle.fillcolor (*args) returns the set color or sets the color of Turtle. Fillcolor passable participation without passable parameters:

  • Fillcolor (): returns the current color setting with no parameter
  • Fillcolor (colorString) : You can pass in a string to set the color value
  • Fillcolor ((r, g, b)) : Pass in a tuple value for setting
  • Fillcolor (r, g, b) : specifies the values of r, g, and b

color()

Turtle.color (*args) returns the color of the set pen or the set fill color. Color can be transferred to participate in no transfer:

  • Color (): returns the current color setting without taking an argument
  • Color (colorString) : You can pass in a string to set the color value
  • Color (colorString), color((r,g,b)) : Pass in 2 RGB values, one set to Turtle color and one set to draw line color
  • Color (colorString1, colorstring2) : Pass in two string values, one set to turtle color and one set to draw line color

Code examples:

from turtle import *
import time

color("red"."blue")
circle(100)
input(a)Copy the code

Code Meaning:

color("red", "blue"): Set the line to red and turtle to blue

Running results:

begin_fill()/end_fill()

Turtle.begin_fill () starts filling the color. Turtle.end_fill () ends the fill color. Code examples:

from turtle import *
import time

color("black"."red")
begin_fill()
circle(100)
end_fill()
input(a)Copy the code

Code Meaning:

begin_fill(): Start filling. This should be done before drawing the graph.

end_fill(): Finish drawing, must add otherwise will not be filled.

Running results:

More drawing control

reset()

Turtle.reset () removes turtle from the screen and recenters the turtle, recharging all values. Code examples:

from turtle import *
import time

fd(100)
left(30)
fd(100)
time.sleep(1)
reset()
input(a)Copy the code

Code Meaning:

time.sleep(1): Stops the comparison effect for one second

reset()Reset:

Running results:

clear()

Turtle.clear () clears the screen drawing lines. Does not affect turtle position. Code examples:

from turtle import *
import time

fd(100)
left(30)
fd(100)
time.sleep(1)
clear()
input(a)Copy the code

Code Meaning:

clear(): Clears the above drawing effects

Running results:

write()

Turtle. write(arg, move=False, align=”left”, font=(“Arial”, 8, “normal”)) parameter:

  • Arg – the value you want to output to the screen
  • Move — True/False Whether to move the output value align — align font — type of font

Output values to the screen, font and alignment can be set. Code examples:

from turtle import *
import time

fd(100)
left(30)
fd(100)
time.sleep(1)
write("Hello?".False, align="center")
input(a)Copy the code

Code Meaning:

Write (" hello ", False, align="center"): displays hello, but does not move when displaying values, and aligns them with center.

Running results:



Write (" hello ", False, align="center")Instead ofWrite (" hello ", True, align="center")To make the output value move when turtle.

Turtle state

hideturtle()|showturtle()|isvisible()

Turtle.hideturtle () turtle.ht() sets whether turtle is visible. Code examples:

from turtle import *
import time

hideturtle()
input(a)Copy the code

Code Meaning:

hideturtle(): Makes turtle invisible

Running results:

showturtle()

Turtle.showturtle () turtle.st() makes turtle visible. Code examples:

from turtle import *
import time

hideturtle()
time.sleep(1)
showturtle()
input(a)Copy the code

Code Meaning:

showturtle(): Set turtle visible.

Running results:

turtle.isvisible()

Check whether turtle is displayed. Code examples:

from turtle import *
import time

hideturtle()
print(isvisible())
time.sleep(1)
showturtle()
print(isvisible())
input(a)Copy the code

Code Meaning:

print(isvisible()): Read status, displayed as True otherwise False

Running results:

appearance

shape()

Turtle. Shape (name = None) parameters:

  • Name: Valid shape name Sets Turtle Shape to a shape with the given name, or returns the name of the current shape if no name is specified. Shapes named as must exist in TurtleScreen’s shape dictionary. By default, the following polygon shapes are available: Arrow, Tortoise, Circle, Square, Triangle, classic. If you set it to turtle, it will become turtle.

Code examples:

from turtle import *
import time

shape("turtle")
input(a)Copy the code

Code Meaning:

shape("turtle"): Set turtle to turtle shape

Running results:

shapesize()

Turtlesize (stretch_wid=None, stretch_len=None, outline=None)

  • Stretch_wid: y axis tensile
  • Stretch_len: x axis tensile
  • Outline: Edge stretching

Turtle can be set to pull up. Code examples:

from turtle import *
import time

shapesize(15.15.112)
fd(100)
input(a)Copy the code

Code Meaning:

shapesize(15, 15, 112): X-axis stretch 15, Y-axis stretch 15, edge stretch 112

Running results:

tilt()

Turtle. Tilt (Angle) parameters:

  • Angle: the Angle

Change the arrow direction, but do not change the turtle direction. Code examples:

from turtle import *
import time

tilt(30)
fd(111)
input(a)Copy the code

Code Meaning:

tilt(30)Turtle Turns the Angle but does not change direction of action.

Running results:

The event

onclick()

Turtle. onclick(fun, BTN =1, add=None) :

  • Fun: Function in response
  • BTN: The number of clicks can be empty
  • Add: True or False Adds a new binding, otherwise a click event will be bound to Turtle instead of the previous binding.

Code examples:

from turtle import *
import time

def turn(x, y) :
    left(180)

onclick(turn)
input(a)Copy the code

Code Meaning:

onclick(turn): Call the turn function with each click, rotate 180°.

Running results:

onrelease()

Turtle. onRelease (fun, BTN =1, add=None) argument:

  • Fun: Function in response
  • BTN: The number of clicks can be empty
  • Add: True or False Adds a new binding, otherwise it replaces the previous binding in response to a function on mouse click release.

Code examples:

from turtle import *
import time

def turn(x, y) :
    left(180)
def turn_(x, y) :
    left(-180)
    
onclick(turn)
onrelease(turn_)
input(a)Copy the code

Code Meaning:

onrelease(turn_): Executes the turn_ function after mouse release

Running results:

ondrag()

Turtle. ondrag(fun, BTN =1, add=None)

  • Fun: Function in response
  • BTN: The number of clicks can be empty
  • Add: True or False Adds a new binding, otherwise the previous binding will be replaced

Drag-and-drop response. Code examples:

from turtle import *
import time

ondrag(goto)
input(a)Copy the code

Code Meaning:

ondrag(goto): Goto is executed when dragging

Running results:

Some special Turtle methods

clone()

Turtle.clone () clones and returns turtle with the same properties. Code examples:

from turtle import *
import time

mick = Turtle()
joe = mick.clone()
mick.goto(111.0)
joe.goto(0.111)
input(a)Copy the code

Code Meaning:

mick = Turtle(): Create a Turtle instance

joe = mick.clone(): Clone this Mick instance

Mick. Goto (111, 0)Mick the Turtle is moving to the coordinates of x = 111y = 0

Joe. Goto (0111).: Joe this turtle is moving to the coordinate y is 111x is 0

Running results:

getturtle()|getpen()

Turtle.getturtle () Turtle.getPen () Returns an example of code for the current Turtle:

from turtle import *
import time

pet = getturtle()
pet.fd(50)
input(a)Copy the code

Code Meaning:

pet = getturtle(): gets the object currently turtle

Running results:

setundobuffer()

Turtle. Setundobuffer (size) parameters:

  • Size: size Sets the buffer size. The number of actions turtle uses undo to undo the buffer. If size is None, undo is disabled.

Code examples:

from turtle import *
import time

setundobuffer(42)
input(a)Copy the code

undobufferentries()

Returns the number of actions stored in the buffer. Code examples:

from turtle import *
import time

fd(111)
left(10)
fd(11)
print(undobufferentries())
input(a)Copy the code

Code Meaning:

print(undobufferentries()): Outputs the number of actions in the buffer

Running results:

Window control

bgcolor()

turtle.bgcolor(*args)
Copy the code

Parameters:

  • Args: Pass in the color code or logo, if not, set the color or get the current color for the background color.

Code examples:

from turtle import *

bgcolor("orange")
goto(10.0)
input(a)Copy the code

Code Meaning:

bgcolor("orange"): Set the background color to orange

Running results:

bgpic()

Turtle. Bgpic (picname = None) parameters:

  • Picname: returns the name of the background picture if it is not passed, and sets the background picture if it is passed with the parameter. The file name or path can be passed

Code examples:

from turtle import *

bgpic(r"C:\Users\Administrator\Desktop\timg1.jpg")
goto(10.0)
input(a)Copy the code

Code Meaning:

bgpic(r"C:\Users\Administrator\Desktop\timg1.jpg"): Sets the background image

Running results:

clear()|clearscreen()

Turtle.clear () Turtle.clearScreen () Clear the screen without moving turtle position. Code examples:

from turtle import *

goto(100.0)
clear()
input(a)Copy the code

Code Meaning:

clear(): Clears the drawn content

Operation effect:

clearscreen()

Understand everything including Turtle.

Running results:

reset()|resetscreen()

Turtle.reset () turtle.resetScreen () resets turtle to its initial state on the screen. Code examples:

from turtle import *
import time

goto(100.0)
time.sleep(2)
resetscreen()
input(a)Copy the code

Code Meaning:

resetscreen(): reset the turtle

Running results:

screensize()

turtle.screensize(canvwidth=None, canvheight=None, bg=None)

Canvwidth: The width of the canvas

Canvheight: The length of the canvas

Resize the canvas and use the scroll bar to view the content beyond the visual form.



Code examples:

from turtle import *
import time

screensize(2000.1500)
goto(1000.0)
Copy the code

Code Meaning:

Screensize (2000150): Adjust the canvas width to 2000 and length to 1500

Running results:



setworlcoordinates()

turtle.setworldcoordinates(llx, lly, urx, ury)

Parameters:

  • LLX: x in the lower left corner
  • Lly: y in the lower left corner
  • Urx: x in the upper right corner
  • Ury: Y in the lower right corner

Customize the coordinate system with xy in the lower left and right corners. Code examples:

from turtle import *

setworldcoordinates(-10, -7.5.10.7.5)
for _ in range(72):
    left(10)
for _ in range(4):
    left(90); fd(5)
input(a)Copy the code

Code Meaning:

Setworldcoordinates (-, 10-7.5, 10,7.5): Customize a small coordinate system

fd(5): The distance of 5 pixels drawn in the normal coordinate system is too small. After the customization of the coordinate system, 5 units is enough to compare the whole coordinate system.

Running results:

The animation control

delay()

Turtle. Delay (delay = None) parameters:

  • Delay: positive integer

Sets or returns the drawing delay in milliseconds. The longer the drawing delay, the slower the animation. Code examples:

from turtle import *

delay(100)
fd(200)
input(a)Copy the code

Code Meaning:

delay(100): Define delay

Running results:



tracer()

turtle.tracer(n=None, delay=None)

parameter

  • N: Updates the screen every n times
  • Delay, delay

Turn turtle animation on/off and set a delay for updating graphics. Given n, only the NTH periodic screen update is actually performed, which can be used to speed up the drawing of complex graphics. Code examples:

from turtle import *

tracer(100.1)
dist = 2
for i in range(200):
     fd(dist)
     rt(90)
     dist += 2
input(a)Copy the code

Code Meaning:

tracer(100, 1): Refreshes the screen 100 times

Running results:

In a flash.



Change to refresh the screen every time:tracer(100, 1)

Screen event

listen()|onkey()|onkeyrelease()

Turtle.listen () turtle.onkey(fun, key) arguments:

  • Fun: Function executed
  • Key: indicates a response event

Listen Enables listening, and onKey responds to events. Code examples:

from turtle import *

def f() :
     fd(50)
     lt(60)
listen()
onkey(f, "Up")

input(a)Copy the code

Code Meaning:

listen(): Enables listening events

Onkey (f, "Up") :Listen to the keyboard ↑ press down, execute f function

Running results:

ontimer()

Turtle. ontimer(fun, t=0) parameter:

  • Fun: function
  • T: Fun is called after time t.

Code examples:

from turtle import *
def f() :
    fd(200)
    left(110)

ontimer(f,1000)
input(a)Copy the code

Code Meaning:

ontimer(f,1000): Call f after 1 second

Running results:

The input method

textinput()

turtle.textinput(title, prompt). Parameters:

  • Title: dialog box title
  • Prompt: Describes the input text

A dialog window for entering strings pops up. The title argument is the title of the dialog window, and the propmt is a text that mainly describes what information to enter. Returns string input. If the dialog box is cancelled, empty is returned. Code examples:

from turtle import *
textinput("turtle"."Hello!)
input(a)Copy the code

Code Meaning:

Textinput (" Turtle ", "Hello!" ): Text input

Running results:

numinput()

Turtle. numinput(title, prompt, default=None, minval=None, maxval=None)

  • Title: the title
  • Prompt: describe
  • Minval: minimum value
  • Maxval: indicates the maximum value
  • Default: indicates the default value

A dialog box for entering a number appears. Title is the title of the dialog window, and Prompt is a text that mainly describes what numeric information to enter. Default: default value, minimum value: minimum value, maximum value: maximum value The entered number must be within the range of the minimum value. If these are given, maxval. Otherwise, a prompt will be issued and the dialog will remain open for corrections. Returns numeric input. If the dialog box is cancelled, “None” is returned. Code examples:

from turtle import *

numinput("Poker"."Your stakes:".1000, minval=10, maxval=10000)
input(a)Copy the code

Code Meaning:

numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000): Accepts a number with a minimum value of 10 and a maximum value of 10000, with a title of Poker and a prompt for Your stakes, and a default value of 1000.

Running results:

Settings and special methods

Window_height () | window_width () to obtain wide screen high code sample:

from turtle import *

print(window_height(),window_width())
input(a)Copy the code

Running results:

bye()|title()

Turtle.bye () window closes.

from turtle import *

print(window_height(),window_width())
input()
bye()
input(a)Copy the code

Title (context) Context is the text to be displayed. Use title to set the title.

setup ()

Turtle. setup(width=_CFG[“width”], height=_CFG[“height”], startx=_CFG[“leftright”], starty=_CFG[“topbottom”])

  • Width: indicates the window width
  • Height: window height
  • Startx: The X coordinate of the occurrence position
  • Starty: indicates the y coordinate of the occurrence position

Code examples:

from turtle import *

setup (width=200, height=200, startx=600, starty=400)
input(a)Copy the code

Running results:

Welcome to like, collect, pay attention to;

If there are any mistakes can be pointed out in the comment section, thank you!