Use python to draw a semi-circular spiral line, how to draw an arc in python

Hello everyone, the editor will answer the question of drawing a semicircle in python and filling it with different colors above and below. Many people don't know how to draw a semicircle in python to turn in one direction, let's take a look now!

Article directory


turtle-library

Introduction

The turtle library is a simple graphics drawing module that is very suitable for beginners and even children.
Since the Python2.6 version, the turtle library has become an embedded module of Python, no special installation is required .
The instructions in the turtle library are visual and simple, and the coordinate axes it draws take the center of the canvas as the origin. In the standard mode, the initial direction of the turtle is horizontal to the right (east), which is generally the standard mode, and can be modified by referring to the function mode().
insert image description here

help

  1. Python's built-in function help([object])
    function help() searches in the help documentation by calling the built-in interactive help system. If no arguments are given, the help system will be started at the interpreter console. If the argument is a string, the string is looked up as the name of a module, function, class, method, keyword, or help documentation topic, and the help page is printed to the console. If the argument is any other type of object, generate a help page for that object.
    insert image description here
  2. The help document that comes with Python You can find the pythonXXX.chm help document in the Doc
    under the Python installation path .
    insert image description here
  3. Help documentation on Python official website
    https://docs.python.org/zh-cn/3.8/index.html

object-oriented and procedural-oriented

The turtle library provides basic methods in an object-oriented and procedural-oriented manner. Because it uses the tkinter interface as a base, it requires a version of Python with Tk support installed.
Note : If you want to use multiple turtle objects on the canvas, you must use the object-oriented interface.
In the parameter lists of all functions given below, the function's first additional parameter self is omitted in this text.

  • The object-oriented interface described below contains the public classes.
    The following is an object-oriented way of writing:
# 第一种写法
import turtle
turtle01 = turtle.Turtle()  #创建一个名为turtle01的海龟对象
turtle01.fd(100)  #调用方法让turtle01这个海龟对象前进

# 第二种写法
from turtle import Turtle
turtle01 = Turtle()  #创建一个名为turtle01的海龟对象
turtle01.fd(100)  #调用方法让turtle01这个海龟对象前进
  • The procedure-oriented interface provides functions derived from methods of classes Screen and Turtle. They have the same names as the corresponding methods. When a function derived from the Screen method is called, a canvas object is automatically created. When calling a function derived from the Turtle method, an unnamed turtle object is automatically created.
    The following is a process-oriented way of writing:
# 第一种写法
import turtle
turtle.fd(100)  #调用方法让海龟前进

# 第二种写法
from turtle import *
fd(100)  #调用方法让海龟前进

public class

  • class turtle.RawTurtle(canvas) or class turtle.RawPen(canvas)
    Function: create a turtle object. It can call all methods of the class RawTurtle/Turtle below.
    Parameters canvas: an object created by tkinter.Canvas or ScrolledCanvas or TurtleScreen.
  • class turtle.Turtle()
    function: a subclass of class RawTurtle, inheriting all the methods of class RawTurtle, the difference is that a default Screen object will be created automatically when called for the first time.
  • class turtle.TurtleScreen(cv)
    Function: create a canvas object. It can call all methods of the class TurtleScreen/Screen below.
    Parameter cv: an object created by tkinter.Canvas.
  • class turtle.Screen()
    function: a subclass of class TurtleScreen, inheriting all the methods of class TurtleScreen, the difference is that there are four additional methods.
  • class turtle.ScrolledCanvas(master)
    function: use the class Screen, which automatically provides a scrolling canvas.
    Parameter master: Some Tkinter widgets contained in the scrolling canvas, that is, objects of tkinter.Canvas with scroll bars added.
  • class turtle.Shape(type_, data)
    function: data structure modeling of turtle shape.
    Parameter type_: one of the strings "polygon", "image" and "compound".
    For (type_, data) must follow the following specifications:
type_ data
“polygon” a tuple of polygons, i.e. a tuple of a pair of coordinates
“image” An image (this form is for internal use only)
“compound” None (composite shapes must be constructed using the function addcomponent())
  • class turtle.Vec2D(x, y)
    Function: a two-dimensional vector class, used as an auxiliary class for realizing turtle graphics. Might also be useful for a turtle shape program. It is derived from tuple, so a vector is a tuple.
    Provides the following operations:
statement meaning
a + b vector addition
a - b vector subtraction
a * b quantity product
k*a or a*k multiplication
abs(a) the modulus of the vector a
a.rotate(angle) to rotate

1. The method of class RawTurtle/Turtle

movement of turtles

Move and draw

1. forward(distance)或fd(distance)
  • Function
    Move the turtle forward by the specified distance in the direction the turtle is moving forward.
    The unit of distance is pixel, and the unit of length mentioned below is generally pixel.
  • Parameter
    distance (integer or float): The distance the turtle moves.
2. back(distance)或bk(distance)或backward(distance)
  • Function
    Move the turtle backward by a certain distance, opposite to the direction the turtle is moving forward. But it doesn't change the direction of the turtle.
  • Parameter
    distance (integer or float): The distance the turtle moves.
3. right(angle) or rt(angle)
  • Function
    Turn the turtle right in degrees.
    The default units are degrees, but can be set with the functions degrees() and redians().
    The angle direction depends on the turtle mode, please refer to the function mode().
  • Parameter
    angle (integer or float): The angle at which the turtle turns right.
4. left(angle)或lt(angle)
  • Function
    Turn the turtle to the left in degrees.
    The default units are degrees, but can be set with the functions degrees() and redians().
    The angle direction depends on the turtle mode, please refer to the function mode().
  • Parameter
    angle (integer or floating point): The angle at which the turtle turns left.
5. goto(x, y=None)或setpos(x, y=None)或setposition(x, y=None)
  • Function
    Move the turtle to the specified coordinate point (x, y). But it doesn't change the direction of the turtle.
    If y is None, x must be a pair of coordinates or a Vec2D. (For example, x can be returned by the function position())
    If the state of the brush is put down, the movement track will be drawn.
  • Parameter
    x (a number, or a pair of coordinates, or a vector): the specified x-axis coordinates.
    y (a number, or None): The specified y-axis coordinate.
6. setx(x)
  • Function
    Set the x-axis coordinate of the turtle to x, and the y-axis coordinate remains unchanged.
  • Parameter
    x (integer or float): Set the new x-axis coordinates.
7. sets(s)
  • Function
    Set the y-axis coordinate of the turtle to y, and keep the x-axis coordinate unchanged.
  • Parameter
    y (integer or float): Set the new y-axis coordinate.
8. setheading(to_angle)或seth(to_angle)
  • Function
    Sets the current orientation of the turtle according to the value of to_angle. The angle direction depends on the turtle mode, please refer to the function mode().
  • Parameters
    to_angle (integer or float): The angle to set. Here are some commonly used degrees:
    insert image description here
9. home()
  • Function
    Move the turtle to the origin coordinates (0, 0), and set its direction to its initial direction (the direction depends on the mode, please refer to the function mode()).
10. circle(radius, extent=None, steps=None)
  • Function
    Draws a circle or arc with a given radius. The center of the circle is on the left side of the turtle, the length of radius away.
  • Parameter
    radius (integer or floating point): determines the radius of the circle. It can take positive and negative values. If the radius is positive, the arc will be drawn counterclockwise, otherwise, the arc will be drawn clockwise.
    extent (integer or floating point number or None): determines the range of the arc drawn (example extent=180 means semicircle). One endpoint of the arc is the current nib. If no arguments are given, the entire circle is drawn. Finally, the orientation of the turtle changes with the size of the extent.
    steps (integer or None): When the circle is approximated by the regular polygon it inscribes, steps determines the number of sides of the regular polygon. If not given, it will be calculated automatically. Can be used to draw regular polygons.
    insert image description here
11. dot(size=None, *color)
  • Function
    Use the specified color to draw a dot with a diameter of size.
  • Parameter
    size (an integer greater than or equal to 1, or None): determines the diameter of the dot. If no arguments are given, the largest size between brush size + 4 and brush size * 2 is used.
    color (color specification string, or hexadecimal color code): Determines the color of the dot.
12. stamp()
  • Function
    Duplicate the shape of a turtle at the current turtle position on the canvas, and then leave a mark.
    This function will return a value stampid, which is used to identify the imprint left, which can be deleted by calling the function clearstamp(stampid).
    insert image description here
13. clearstamp(stampid)
  • Function
    Delete the turtle stamp of the specified stampid.
  • Parameter
    stampid (integer): must be the return value of the previous == function stamp() == call.
14. clearstamps(n=None)
  • Function
    Delete all or the first n/last n turtle imprints.
  • Parameter
    n (integer or None): If n is None, delete all imprints; if n>0, delete the first n imprints; otherwise, if n<0, delete the last n imprints.
15. undo()
  • Function
    Undoes the last turtle action. Undo can be repeated, and the number of undo operations is determined by the size of the undo buffer. (Please refer to the function setundobuffer())
16. speed(speed=None)
  • Function
    Set the speed of the turtle, the speed from 1 to 10 makes the animation of drawing lines and turning the turtle faster and faster.
  • Parameter
    speed (an integer in the range 0 to 10, or a speed specification string): If no parameter, returns the current speed. If the number entered is greater than 10 or less than 0.5, speed becomes 0. Note: speed=0 means no animation happens.
    The speed values ​​corresponding to the relevant speed specification strings are as follows:
    • "fastest": 0
    • "fast": 10
    • "normal": 6
    • "slow": 3
    • "slowest": 1

Set the turtle state

1. position() or pos()
  • Function
    Returns the current position (x, y) of the turtle (available as a Vec2D vector).
2. towards(x, y=None)
  • Function
    Returns the angle between the direction of the line from the current position of the turtle to the specified position (x, y) or vector or another turtle and the initial direction (the included angle of the vector).
    Note : It is only related to the initial direction of the turtle, not the current direction of the turtle. The initial orientation of the turtle depends on the turtle mode. (Please refer to the function mode())
  • Parameter
    x (a number, or a pair of coordinates, or a vector, or another turtle object): the specified x-axis coordinates.
    y (a number, or None): The specified y-axis coordinate.
    insert image description here
3. xcor()
  • Function
    Returns the x-coordinate of the turtle.
4. ycor()
  • Function
    Returns the y-coordinate of the turtle.
5. heading()
  • Function
    Returns the current direction of the turtle, which is a floating point number (the value depends on the turtle mode).
    The angle direction depends on the turtle mode, please refer to the function mode().
6. distance(x, y=None)
  • Function
    Returns the distance in pixels from the turtle's current position to the specified position (x, y) or vector or another turtle.
  • Parameter
    x (a number, or a pair of coordinates, or a vector, or another turtle object): the specified x-axis coordinates.
    y (a number, or None): The specified y-axis coordinate.

Setup and Measurement

1. degrees(fullcircle=360.0)
  • Function
    Set the angle measurement unit, that is, set the relative degree of a complete circle. The default is 360 degrees.
  • Parameters
    fullcircle (integer or float): The relative degree of a full circle.
    insert image description here
2. radians()
  • Function
    Sets the angular measurement unit to radians. Equivalent to the function degrees(2*math.pi).

brush control

painting state

1. pendown() or pd() or down()
  • Function
    Put down the brush, and it will draw a track when moving.
2. penup() or pu() or up()
  • Function
    Lift the paintbrush, no trace will be drawn when moving.
3. pensize(width=None)或width(width=None)
  • Function
    Sets the width of the line to width.
    If the adjustment mode is set to "auto" and the turtle shape is a polygon, the polygon is drawn with the newly set line of the same width. (Please refer to function resizemode() and function shape())
  • Parameter
    width (positive number or None): the width of the setting. If no arguments are given, returns the current width.
4. pen(pen=None, **pendict)
  • Function
    Use the parameters of the keyword to set the state and properties of the brush.
    This dictionary can be used as an argument in subsequent calls to the function pen() to restore the previous state of the pen. Additionally, one or more of these properties can be provided as key-value pairs. Can be used to set multiple properties in one statement.
    Note : You need to understand the concept of dictionaries
    https://www.runoob.com/python3/python3-dictionary.html
  • Parameter
    pen : a custom dictionary name. Can be None.
    pendict : Contains one or more key-value pairs.
    The keys and corresponding values ​​are listed below:
    • shown: True or False
    • pendown: True or False
    • pencolor: color specification string, or hexadecimal color code
    • fillcolor: color specification string, or hexadecimal System color code
    • pensize: positive number
    • speed: integer or floating point number in the range of 0 to 10
    • resizemode: "auto" or "user" or "noresize"
    • stretchfactor: (positive number, positive number)
    • outline: positive number
    • tilt: integer or float
    insert image description here
5. isdown()
  • Function
    Return True if the pen is down; return False if the pen is up.

color control

1. pencolor(*args)
  • Function
    Returns or sets the brush color. If the turtle shape is a polygon, draw the outline of the polygon with the newly set brush color. (Please refer to the function shape())
  • The parameters
    allow the following four input formats:
    1. pencolor()
    returns the color specification string or tuple of the current pen. Can be used as an input parameter to another color/brush color/fill color call.
    2. pencolor(colorstring)
    sets the pen color to colorstring, which is a Tk color specification string, such as "red", "blue" or "#33cc8c".
    3. pencolor((r, g, b))
    sets the pen color to the RGB color represented by the tuple of r, g and b. Each value of r, g, and b must be in the range 0 to colormode, where colormode is 1.0 or 255 (see function colormode()).
    4. pencolor(r, g, b)
    sets the pen color to the RGB color represented by r, g and b. Each value of r, g, and b must be in the range 0 to colormode, where colormode is 1.0 or 255 (see function colormode()).
2. fillcolor(*args)
  • Function
    Returns or sets the fill color.
  • Parameters
    Allow the following four input formats:
    1. fillcolor()
    2. fillcolor(colorstring)
    3. fillcolor((r, g, b))
    4. fillcolor(r, g, b)
    The above input formats can refer to the function pencolor The input format of (*args) will not be introduced here.
3. color(*args)
  • Function
    Returns or sets the pen color and fill color.
  • The parameters
    allow the following multiple input formats:
    1. color()
    returns the current pen color and the current fill color in the form of a pair of color specification strings or tuples returned by the function pencolor() and the function fillcolor().
    2. color(colorstring), color((r,g,b)), color(r,g,b)
    can refer to the input format of the function pencolor(*args), and set the fill color and brush color to the same color value .
    3. color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2))
    color(colorstring1, colorstring2) is equivalent to the combination of pencolor(colorstring1) and fillcolor(colorstring2).
    Another input format is also similar to the above.

filling

1. filling()
  • Function
    Returns the fill status (True if filled, False otherwise).
2. begin_fill()
  • Function
    to be called before drawing the figure to be filled.
3. end_fill()
  • Function
    Fills the graph drawn after the last call to ==function begin_fill()==.

More painting controls

1. reset()
  • Function
    Removes the drawing of the turtle from the canvas, re-centers the turtle and sets variables to default values.
2. clear()
  • Function
    Removes the turtle's drawing from the canvas, but does not move the turtle, and the state and position of the turtle and other turtle's drawings are not affected.
3. write(arg, move=False, align=“left”, font=(“Arial”, 8, “normal”))
  • Function
    Write the text at the current turtle position according to the set alignment and the given font format.
  • Parameters
    arg (string object): the text to write on the canvas.
    move (True/False): If move is True, move the turtle to the bottom right corner of the text, otherwise don't. By default, move is False.
    align ("left" or "center" or "right"): The alignment.
    font (contains three items (font name, font size, font type)): font attributes.
    insert image description here

properties of turtles

visibility

1. hideturtle() or ht()
  • Function
    Makes the turtle invisible.
    It's a good idea to do this when you're doing some complex drawing, as hiding the turtle can significantly speed up drawing.
2. showturtle() or st()
  • Function
    Makes the turtle visible.
3. isvisible()
  • Function
    Returns True if the turtle is visible; returns False if it is invisible.

Exterior

1. shape(name=None)
  • Function
    Sets the turtle shape to the specified shape, or returns the name of the current turtle shape if no shape is specified.
  • Parameter
    name (string or None): The named turtle shape must exist in the canvas's turtle shape dictionary. Initially there were these turtle shapes: "arrow", "turtle", "circle", "square", "triangle", "classic". To learn how to add a turtle shape, refer to the function register_shape().
2. resizemode(rmode=None)
  • Function
    Sets the resizing mode to one of the following values: 'auto', 'user', 'noresize'. If no arguments are given, returns the current tuning mode.
  • Parameter
    rmode ("auto" or "user" or "noresize" or None): different adjustment modes have the following effects:
    "auto": adjust the shape of the turtle according to the size of the brush. (Please refer to the function pensize())
    "user": Adjust the shape of the turtle according to the stretch factor and outline width set by the function shapesize(). resizemode("user") and the function shapesize() are often used together. (Please refer to the function shapesize())
    "noresize": The shape of the turtle will not change.
3. shapesize(stretch_wid=None, stretch_len=None, outline=None)或turtlesize(stretch_wid=None, stretch_len=None, outline=None)
  • Function
    Set the size of the turtle shape. If no arguments are given, returns the dimensions of the current turtle shape. The turtle shape will change according to its stretch factor and outline width if and only if the adjustment mode is set to user.
  • Parameter
    stretch_wid (positive number or None): The stretch factor perpendicular to the direction of the turtle, that is, the width of the stretched turtle. When None, it is the current value. The default initial value is 1.
    stretch_len (positive number or None): The stretch factor parallel to the direction of the turtle, that is, the length of the stretched turtle. When None, it is the current value. The default initial value is 1.
    outline (positive or None): The outline width of the turtle shape. When None, it is the current value. The default initial value is 1.
4. shearfactor(shear=None)
  • Function
    Set or return the current clip factor. Cut out the turtle shape according to the given clipping factor (i.e., the tangent of the clipping angle). The shear angle refers to the angle (acute angle) between the direction of the turtle's advance and the shear line. But it will not change the direction and area of ​​the turtle.
  • Parameters
    shear (integer or float or None): take the tangent of the shear angle. When it is 0, it means no cutting. If no argument is given, returns the current clip factor.
5. tilt(angle)
  • Function
    Rotates the shape of the turtle according to angle based on the current rotation angle, but does not change the direction of the turtle.
    The angle direction depends on the turtle mode, please refer to the function mode().
  • Parameter
    angle (integer or floating point): rotation angle. Rotate clockwise when taking a negative value, and rotate counterclockwise when taking a positive value.
6. settiltangle(angle)
  • Function
    Rotate the turtle shape to the specified angle orientation regardless of the current rotation angle. But it won't change the direction the turtle is going.
    The angle direction depends on the turtle mode, please refer to the function mode().
  • Parameter
    angle (integer or floating point): rotation angle. Rotate clockwise when taking a negative value, and rotate counterclockwise when taking a positive value.
7. tiltangle(angle=None)
  • Function
    Set or return the current rotation angle. But it won't change the direction the turtle is going.
    Rotates the turtle shape to the specified angular orientation, regardless of the current rotation angle.
    The angle direction depends on the turtle mode, please refer to the function mode().
  • Parameter
    angle (integer or float or None): rotation angle. Rotate clockwise when taking a negative value, and rotate counterclockwise when taking a positive value. If no arguments are given, returns the current rotation angle.
8. shapetransform(t11=None, t12=None, t21=None, t22=None)
  • Function
    Set or return the transformation matrix of the current turtle shape.
    If no arguments are given, returns a transformation matrix as a tuple of 4 elements. In addition, according to the matrix composed of the first row t11, t12 and the second row t21, t22, set the given element and transform the shape of the turtle. The determinant t11 ​​* t22 - t12 * t21 must be non-zero, otherwise an error will be generated. Modify the stretch factor, shear factor and rotation angle according to the given matrix.
  • Parameters
    t11, t12, t21, t22 (integer or floating-point number or None): The specific meaning is not clear at present, and needs to be researched by yourself.
    insert image description here
9. get_shapepoly()
  • Function
    Returns the current turtle shape as a tuple of coordinate pairs. This can be used to define a new shape or a component of a compound shape.
    insert image description here

use of events

1. onclick(fun, btn=1, add=None)
  • Function
    Binds the function fun to mouse click events on this turtle.
  • Parameters
    fun (function or None): A function with two parameters that will be called with the coordinates (x,y) of the clicked point on the canvas. If function fun is None, existing bindings are removed.
    btn (integer): indicates the number of the button on the mouse, the default is 1. 1 indicates the left mouse button, 2 indicates the middle mouse button, and 3 indicates the right mouse button.
    add (True or False or None): If True, a new binding will be added, otherwise the previous binding will be replaced.
    insert image description here
2. onrelease(fun, btn=1, add=None)
  • Function
    Binds the function fun to mouse button release events on this turtle.
  • Parameters
    fun (function or None): A function with two parameters that will be called with the coordinates (x,y) of the clicked point on the canvas. If function fun is None, existing bindings are removed.
    btn (integer): indicates the number of the button on the mouse, the default is 1. 1 indicates the left mouse button, 2 indicates the middle mouse button, and 3 indicates the right mouse button.
    add (True or False or None): If True, a new binding will be added, otherwise the previous binding will be replaced.
    insert image description here
3. ondrag(fun, btn=1, add=None)
  • Function
    Binds the function fun to mousemove events on this turtle.
    Note : Every mouse move event on the turtle is preceded by a mouse click event.
  • Parameters
    fun (function or None): A function with two parameters that will be called with the coordinates (x,y) of the clicked point on the canvas. If function fun is None, existing bindings are removed.
    btn (integer): indicates the number of the button on the mouse, the default is 1. 1 indicates the left mouse button, 2 indicates the middle mouse button, and 3 indicates the right mouse button.
    add (True or False or None): If True, a new binding will be added, otherwise the previous binding will be replaced.
    insert image description here

special method

1. begin_poly()
  • Function
    Start recording the vertices of a polygon. Make the current turtle's position the first vertex of the polygon.
2. end_poly()
  • Function
    Stop recording polygon vertices. Make the current turtle's position the last vertex of the polygon. The last vertex will be connected to the first vertex.
3. get_poly()
  • Function
    Returns the last recorded polygon. This polygon is used to set the shape of the turtle, please refer to the function register_shape().
    insert image description here
4. clone()
  • Function
    Create and return a turtle clone with the same position, turtle orientation, and turtle properties.
5. getturtle() or getpen()
  • Function
    Returns the Turtle object itself. The only reasonable use is as a function returning an unnamed turtle.
6. getscreen()
  • Function
    Returns the TurtleScreen object when the turtle is drawing. Methods of class TurtleScreen can then be called for this object.
7. setundobuffer(size)
  • Function
    Set or disable the undo buffer.
  • Parameter
    size (integer or None): size gives the maximum number of turtle actions that can be undone by the function undo(). If size is an integer, install an empty undo buffer of the given size. If the argument is empty, the undo buffer is disabled.
8. undobufferentries()
  • Function
    Returns the maximum undoable number in the undo buffer.
    Note : size in function setundobuffer() <= maximum undoable number

Two, the method of class TurtleScreen/Screen

window control

1. bgcolor(*args)
  • Function
    Sets or returns the background color of the canvas.
  • The parameters
    allow the following four input formats:
    1. bgcolor()
    returns the background color specification string or tuple of the current canvas. Can be used as an input argument to another color/background-color call.
    2. bgcolor(colorstring)
    sets the background color of the canvas to colorstring, which is a Tk color specification string, such as "red", "blue" or "#33cc8c".
    3. bgcolor ((r, g, b))
    sets the background color of the canvas to the RGB color represented by the tuple of r, g, and b. Each value of r, g, and b must be in the range 0 to colormode, where colormode is 1.0 or 255 (see function colormode()).
    4. bgcolor(r, g, b)
    sets the background color of the canvas to the RGB colors represented by r, g, and b. Each value of r, g, and b must be in the range 0 to colormode, where colormode is 1.0 or 255 (see function colormode()).
2. bgpic(picname=None)
  • Function
    Sets the background image or returns the name of the current background image.
  • Parameter
    picname (gif filename as a string, or "nopic", or None): If picname is a filename, set the corresponding image as the background image. If picname is "nopic", delete the existing background image. If picname is None, returns the filename of the current background image.
3. clear()或clearscreen()
  • Function
    Deletes all drawings and all turtles from the canvas. Resets the currently empty canvas to its initial state: white background, no background image, no event binding and no tracking.
    Note : This function can only be used as a global function if it is named clearscreen. The function clear() is another global function derived from the function clear() of the class Turtle.
4. reset()或resetscreen()
  • Function
    Resets the initial state of all turtles on the canvas.
    Note : This function is only available as a global function if it is named resetscreen. The function reset() is another global function derived from the function reset() of the class Turtle.
5. screensize(canvwidth=None, canvheight=None, bg=None)
  • Function
    If no arguments are given, returns the current values ​​(canvas width, canvas height). Or resize the canvas the turtles are drawing on. But it doesn't change the drawing window. To observe hidden parts of the canvas, scroll bars can be used.
  • Parameters
    canvwidth (positive integer or None): The new width of the canvas in pixels.
    cnvheight (positive integer or None): The new height of the canvas in pixels.
    bg (color specification string or color tuple or None): The new background color.
6. setworldcoordinates(llx, lly, urx, ury)
  • Function
    Create a user-defined coordinate system. When this function is called, it will automatically switch to the mode "world". If necessary, the function mode() can be called to switch. Before this, execute a function reset(). If the mode "world" is active, all drawings will be redrawn according to the new coordinates. (Please refer to the function mode())
  • Parameter
    llx (integer or float): the x-coordinate of the bottom left of the canvas.
    lly (integer or float): The y-coordinate of the bottom left of the canvas.
    urx (integer or float): The x-coordinate of the upper right of the canvas.
    ury (integer or float): The y-coordinate of the upper right of the canvas.
    The positive and negative values ​​of these four parameters determine the direction of the coordinate axis, and four situations are given below.
    The values ​​of these four parameters should be proportions. Divide the current width of the turtle drawing window into x parts, divide the current height of the window into y parts, and use one equal part as a unit to move the turtle.
    insert image description here
    insert image description here

animation control

1. delay(delay=None)
  • Function
    Set or return the drawing delay. This is approximately the time interval between two consecutive canvas updates. The longer the drawing delay, the slower the animation. (Comparable with the function speed())
  • Parameter
    delay (positive integer or None): The drawing delay value in milliseconds. If the parameter is empty, returns the current drawing delay value.
2. tracer(n=None, delay=None)
  • Function
    Turns turtle animation on or off, sets a delay for updated drawing. Can be used to speed up the drawing of complex graphics. When the argument is null, returns the currently stored value n.
  • Parameter
    n (non-negative integer or None): actually perform n regular canvas updates.
    delay (non-negative integer or None): set the delay value (please refer to the function delay()).
    insert image description here
3. update()
  • Function
    Performs an update of the canvas. Used when tracer is off.

Canvas events

1. listen(xdummy=None, ydummy=None)
  • Function
    Set focus on the canvas (so that keyboard events can be collected).
  • Parameters
    Two dummy parameters are provided to be able to pass the function listen() to the function onclick().
2. onkey(fun, key)或onkeyrelease(fun, key)
  • Function
    Binds the function fun to a key release event on the keyboard.
    Note : In order to be able to register keyboard events, the canvas must have focus. (Please refer to the function listen())
  • Parameters
    fun (function or None): a function with no parameters. If function fun is None, the event binding is removed.
    key (string): A key (such as "a") or a key symbol (such as "space").
    insert image description here
3. onkeypress(fun, key=None)
  • Function
    Binds the function fun to keypress events on the keyboard.
    Note : In order to be able to register keyboard events, the canvas must have focus. (Please refer to the function listen())
  • Parameters
    fun (function or None): a function with no parameters. If function fun is None, the event binding is removed.
    key (string or None): key (eg "a") or key symbol (eg "space"). Binds the function fun to the key's keypress event if key is given, or to any key's keypress event if key is not given.
4. onclick(fun, btn=1, add=None)或onscreenclick(fun, btn=1, add=None)
  • Function
    Binds the function fun to mouse click events on this canvas.
    Note : This function is only available as a global function if it is named onscreenclick. The function onclick() is another global function derived from the function onclick() of the class Turtle.
  • Parameters
    fun (function or None): A function with two parameters that will be called with the coordinates (x,y) of the clicked point on the canvas. If function fun is None, existing bindings are removed.
    btn (integer): indicates the number of the button on the mouse, the default is 1. 1 indicates the left mouse button, 2 indicates the middle mouse button, and 3 indicates the right mouse button.
    add (True or False or None): If True, a new binding will be added, otherwise the previous binding will be replaced.
    insert image description here
5. ontimer(fun, t=0)
  • Function
    Installs a timer that calls the function fun after t milliseconds.
  • Parameter
    fun (function): a function without parameters, which can be customized.
    t (integer or floating point): a number greater than or equal to zero, used for timing.
6. mainloop() or done()
  • Function
    Start the event loop - call the function mainloop() of the Tkinter interface. and must be the last statement of the turtle drawing program. This function must not be used if running the script in -n mode (no subprocesses) in IDLE (for interactive use of turtle plots).

input method

1. textinput(title, prompt)
  • Function
    Pop up a dialog window for inputting character strings. If the dialog is confirmed, returns the string entered by the user. Returns None if the dialog was canceled.
  • Parameter
    title (string): The title of the dialog window.
    prompt (string): The text used to prompt the user for information.
2. numinput(title, prompt, default=None, minval=None, maxval=None)
  • Function
    Pop up a dialog window for inputting numbers. If the dialog is confirmed, returns the number entered by the user. Returns None if the dialog was canceled.
  • Parameter
    title (string): The title of the dialog window.
    prompt (string): The text used to prompt the user for numeric information.
    default (integer or float or None): The default value.
    minval (integer or float or None): The minimum value of the user-entered number.
    maxval (integer or float or None): The maximum value of the user-entered number.

Settings and special methods

1. mode(mode=None)
  • Function
    Set the mode of the turtle, and perform a reset. If no arguments, returns the current mode.
  • Parameter
    mode ("standard" or "logo" or "world"): The mode "standard" is compatible with the turtle library. Mode "logo" is compatible with most logo turtle shapes. The mode "world" uses user-defined world coordinates (please refer to the function setworldcoordinates()), in this mode, if the x/y unit ratio t=1, the angle will be distorted.
model initial turtle orientation positive angle
“standard” horizontal right (east) counterclockwise
“logo” horizontally up (north) clockwise
2. colormode(cmode=None)
  • Function
    Return the color mode, or set it to 1.0 or 255. Subsequently, the r, g, b values ​​of the color triplet must be in the range 0 to cmode.
  • Parameter
    cmode (one of 1.0 or 255): when cmode=1.0, the color mode is RGB decimal value; when cmode=255, the color mode is RGB integer value. When the parameter is empty, returns the current color mode.
color English string RGB decimal value RGB integer value hex string
pure black “black” (0, 0, 0) (0, 0, 0) “#000000”
pure red “red” (1, 0, 0) (255, 0, 0) “#FF0000”
lime orange “lime” (0, 1, 0) (0, 255, 0) “#00FF00”
pure blue “blue” (0, 0, 1) (0, 0, 255) “#0000FF”
pure white “white” (1, 1, 1) (255, 255, 255) “#FFFFFF”
blue “cyan” (0, 1, 1) (0, 255, 255) “#00FFFF”
magenta “magenta” (1, 0, 1) (255, 0, 255) “#FF00FF”
pure yellow “yellow” (1, 1, 0) (255, 255, 0) “#FFFF00”
grey “gray” (0.50, 0.50, 0.50) (128,128,128) “#808080”
maroon “maroon” (0.50, 0, 0) (128, 0, 0) “#800000”
pure green “green” (0, 0.50, 0) (0, 128, 0) “#008000”
navy blue “navy” (0, 0, 0.50) (0, 0,128) “#000080”
teal color “teal” (0, 0.50, 0.50) (0, 128, 128) “#008080”
Purple “purple” (0.50, 0, 0.50) (128, 0, 128) “#800080”
olive “olive” (0.50, 0.50, 0) (128, 128, 0) “#808000”
gold “gold” (1, 0.84, 0) (255, 215, 0) “#FFD700”
Pink “pink” (1, 0.75, 0.80) (255, 192, 203) “#FFC0CB”

RGB color value and hexadecimal color code conversion tool: https://www.sioe.cn/yingyong/yanse-rgb-16/

3. getcanvas()
  • Function
    Returns the current canvas. Very useful for people who know how to use the Tkinter canvas.
4. getshapes()
  • Function
    Returns a list of the names of all currently available turtle shapes.
5. register_shape(name, shape=None)或addshape(name, shape=None)
  • Function
    Adds a turtle shape to the turtle shape list in the canvas. Therefore, the added turtle shape can only be called through the function shape(shapename).
  • 参数
    有三种不同的方法来调用这个函数:
    1)添加相应的图像形状:name是gif文件的名称,而shape是None。
    :图像形状在旋转海龟时不旋转,所以它们不显示海龟的方向。
    2)添加相应的多边形形状:name是一个任意字符串,shape是几对坐标的元组。
    3)安装相应的复合形状:name是一个任意字符串,shape是一个(复合)形状对象。
6. turtles()
  • 功能
    返回画布上所有海龟组成的列表。
7. window_height()
  • 功能
    返回海龟绘图窗口的高度。
8. window_width()
  • 功能
    返回海龟绘图窗口的宽度。

不是从类TurtleScreen继承的特定于类Screen的方法

1. bye()
  • 功能
    关闭海龟绘图窗口。
2. exitonclick()
  • 功能
    将函数bye()绑定到画布上的鼠标点击事件上。如果turtle.cfg文件中using_IDLE的值为False(默认值),函数exitonclick()也会进入主事件循环。可参考函数mainloop()。
    :如果你经常使用集成开发环境IDLE并启用-n开关(没有子进程),则将turtle.cfg文件中的using_IDLE设置为True。在这种情况下,IDLE自身的主事件循环对于客户端脚本也是活动的。其中turtle.cfg文件的配置将在下文中详细介绍。
3. setup(width=_CFG[“width”], height=_CFG[“height”], startx=_CFG[“leftright”], starty=_CFG[“topbottom”])
  • 功能
    设置海龟绘图窗口的大小和位置。参数的默认值存储在配置文件中,可以通过turtle.cfg文件进行更改。
  • 参数
    width(整数或浮点数):如果是整数,则以像素为单位设置窗口宽度。如果是浮点数,则是画布的百分比值(默认是0.5=50%的画布宽度)。
    height(整数或浮点数):如果是整数,则以像素为单位设置窗口高度。如果是浮点数,则是画布的百分比值(默认是0.75=75%的画布高度)。
    startx(整数或None):如果为正,则startx为窗口左侧距离电脑屏幕左侧边缘的像素距离,如果为负,则startx为窗口右侧距离电脑屏幕右侧边缘的像素距离,如果为None,则窗口是水平居中的。
    starty(整数或None):如果为正,则starty为窗口顶部距离电脑屏幕顶部边缘的像素距离,如果为负,则starty为窗口底部距离电脑屏幕底部边缘的像素距离,如果为None,则窗口是垂直居中的。
4. title(titlestring)
  • 功能
    设置海龟绘图窗口的标题为给定的titlestring。
  • 参数
    titlestring(字符串):显示在海龟绘图窗口的标题栏中。

turtle.cfg文件配置画布和海龟

  • turtle.cfg文件是一个turtle库内置的默认配置文件。
    如果你想使用一个不同的配置,更好地反映turtle库的特点,或更适合你的需要,那么你可以更改turtle.cfg文件的配置内容。
  • 在turtle.cfg文件里会有以下内容:
    insert image description here
  • 简要说明上图中的内容:
    1)前四行对应 函数setup() 的参数。
    2)第五行和第六行对应于 函数screensize() 的参数。
    3)shape可以是任何内置的海龟形状,如arrow、turtle等。可参考函数shape()。
    4)如果你不想使用fillcolor(比如让海龟透明),则必须写成fillcolor = “”。
    :所有非空字符串在turtle.cfg文件中不能有引号。
    5)如果你想要反映海龟的状态,则必须写成resizemode =auto。
    6)如果你设置的是language = italian,那么文档字符串字典文件turtle_docstringdict_italian.py将在导入时加载(在同一个目录中加载)。
    7)exampleturtle和examplescreen定义了相应对象在文档字符串中显示的名称。
    8)如果你经常使用集成开发环境IDLE并启用-n开关(没有子进程),则将using_IDLE设置为True。这将阻止函数exitonclick() 进入主事件循环。
  • The turtle.cfg file is stored in Lib\turtledemo under the Python installation path .
    Of course, the turtle.cfg file can also be saved in the directory where the turtle is located, and the current working directory can also have a file with the same name. The latter overrides the configuration of the former.
    insert image description here

demo script

Intricate Traditional Turtle Drawing

  • source code
from turtle import Turtle, mainloop
from time import perf_counter as clock

# wrapper for any additional drawing routines
# that need to know about each other
class Designer(Turtle):

    def design(self, homePos, scale):
        self.up()
        for i in range(5):
            self.forward(64.65 * scale)
            self.down()
            self.wheel(self.position(), scale)
            self.up()
            self.backward(64.65 * scale)
            self.right(72)
        self.up()
        self.goto(homePos)
        self.right(36)
        self.forward(24.5 * scale)
        self.right(198)
        self.down()
        self.centerpiece(46 * scale, 143.4, scale)
        self.getscreen().tracer(True)

    def wheel(self, initpos, scale):
        self.right(54)
        for i in range(4):
            self.pentpiece(initpos, scale)
        self.down()
        self.left(36)
        for i in range(5):
            self.tripiece(initpos, scale)
        self.left(36)
        for i in range(5):
            self.down()
            self.right(72)
            self.forward(28 * scale)
            self.up()
            self.backward(28 * scale)
        self.left(54)
        self.getscreen().update()

    def tripiece(self, initpos, scale):
        oldh = self.heading()
        self.down()
        self.backward(2.5 * scale)
        self.tripolyr(31.5 * scale, scale)
        self.up()
        self.goto(initpos)
        self.setheading(oldh)
        self.down()
        self.backward(2.5 * scale)
        self.tripolyl(31.5 * scale, scale)
        self.up()
        self.goto(initpos)
        self.setheading(oldh)
        self.left(72)
        self.getscreen().update()

    def pentpiece(self, initpos, scale):
        oldh = self.heading()
        self.up()
        self.forward(29 * scale)
        self.down()
        for i in range(5):
            self.forward(18 * scale)
            self.right(72)
        self.pentr(18 * scale, 75, scale)
        self.up()
        self.goto(initpos)
        self.setheading(oldh)
        self.forward(29 * scale)
        self.down()
        for i in range(5):
            self.forward(18 * scale)
            self.right(72)
        self.pentl(18 * scale, 75, scale)
        self.up()
        self.goto(initpos)
        self.setheading(oldh)
        self.left(72)
        self.getscreen().update()

    def pentl(self, side, ang, scale):
        if side < (2 * scale): return
        self.forward(side)
        self.left(ang)
        self.pentl(side - (.38 * scale), ang, scale)

    def pentr(self, side, ang, scale):
        if side < (2 * scale): return
        self.forward(side)
        self.right(ang)
        self.pentr(side - (.38 * scale), ang, scale)

    def tripolyr(self, side, scale):
        if side < (4 * scale): return
        self.forward(side)
        self.right(111)
        self.forward(side / 1.78)
        self.right(111)
        self.forward(side / 1.3)
        self.right(146)
        self.tripolyr(side * .75, scale)

    def tripolyl(self, side, scale):
        if side < (4 * scale): return
        self.forward(side)
        self.left(111)
        self.forward(side / 1.78)
        self.left(111)
        self.forward(side / 1.3)
        self.left(146)
        self.tripolyl(side * .75, scale)

    def centerpiece(self, s, a, scale):
        self.forward(s); self.left(a)
        if s < (7.5 * scale):
            return
        self.centerpiece(s - (1.2 * scale), a, scale)

def main():
    t = Designer()
    t.speed(0)
    t.hideturtle()
    t.getscreen().delay(0)
    t.getscreen().tracer(0)
    at = clock()
    t.design(t.position(), 2)
    et = clock()
    return "runtime: %.2f sec." % (et-at)

if __name__ == '__main__':
    msg = main()
    print(msg)
    mainloop()

  • operation result
    insert image description here

Draws an analog clock showing the current time on this machine

  • source code
from turtle import *
from datetime import datetime

def jump(distanz, winkel=0):
    penup()
    right(winkel)
    forward(distanz)
    left(winkel)
    pendown()

def hand(laenge, spitze):
    fd(laenge*1.15)
    rt(90)
    fd(spitze/2.0)
    lt(120)
    fd(spitze)
    lt(120)
    fd(spitze)
    lt(120)
    fd(spitze/2.0)

def make_hand_shape(name, laenge, spitze):
    reset()
    jump(-laenge*0.15)
    begin_poly()
    hand(laenge, spitze)
    end_poly()
    hand_form = get_poly()
    register_shape(name, hand_form)

def clockface(radius):
    reset()
    pensize(7)
    for i in range(60):
        jump(radius)
        if i % 5 == 0:
            fd(25)
            jump(-radius-25)
        else:
            dot(3)
            jump(-radius)
        rt(6)

def setup():
    global second_hand, minute_hand, hour_hand, writer
    mode("logo")
    make_hand_shape("second_hand", 125, 25)
    make_hand_shape("minute_hand",  130, 25)
    make_hand_shape("hour_hand", 90, 25)
    clockface(160)
    second_hand = Turtle()
    second_hand.shape("second_hand")
    second_hand.color("gray20", "gray80")
    minute_hand = Turtle()
    minute_hand.shape("minute_hand")
    minute_hand.color("blue1", "red1")
    hour_hand = Turtle()
    hour_hand.shape("hour_hand")
    hour_hand.color("blue3", "red3")
    for hand in second_hand, minute_hand, hour_hand:
        hand.resizemode("user")
        hand.shapesize(1, 1, 3)
        hand.speed(0)
    ht()
    writer = Turtle()
    #writer.mode("logo")
    writer.ht()
    writer.pu()
    writer.bk(85)

def wochentag(t):
    wochentag = ["Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday", "Sunday"]
    return wochentag[t.weekday()]

def datum(z):
    monat = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "June",
             "July", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."]
    j = z.year
    m = monat[z.month - 1]
    t = z.day
    return "%s %d %d" % (m, t, j)

def tick():
    t = datetime.today()
    sekunde = t.second + t.microsecond*0.000001
    minute = t.minute + sekunde/60.0
    stunde = t.hour + minute/60.0
    try:
        tracer(False)  # Terminator can occur here
        writer.clear()
        writer.home()
        writer.forward(65)
        writer.write(wochentag(t),
                     align="center", font=("Courier", 14, "bold"))
        writer.back(150)
        writer.write(datum(t),
                     align="center", font=("Courier", 14, "bold"))
        writer.forward(85)
        tracer(True)
        second_hand.setheading(6*sekunde)  # or here
        minute_hand.setheading(6*minute)
        hour_hand.setheading(30*stunde)
        tracer(True)
        ontimer(tick, 100)
    except Terminator:
        pass  # turtledemo user pressed STOP

def main():
    tracer(False)
    setup()
    tracer(True)
    tick()
    return "EVENTLOOP"

if __name__ == "__main__":
    mode("logo")
    msg = main()
    print(msg)
    mainloop()
  • operation result
    insert image description here

more demo scripts

Various demo scripts are stored in Lib\turtledemo under the Python installation path . Among them, __main__.py is a demo viewer, which can be used to view the source code of the script and run it immediately.
insert image description here

Guess you like

Origin blog.csdn.net/mynote/article/details/132448074