BOBOBK

Drawing a Circle with Squares Using Turtle

TECHNOLOGY

I recently discovered a very interesting Python drawing library called Turtle. Here, I’ll briefly explain the idea behind using the Turtle library to draw a circle with squares.

Each time, the turtle draws a square:

Then, after rotating 3 degrees, it continues to draw the same square. After 120 repetitions, a complete circle is formed. Of course, you can use other angles and repetitions as long as they sum up to 360 degrees.


See the Completed Graphic and Code Below.

Here’s the code:

import turtle
window = turtle.Screen() # Set up basic drawing parameters
window.bgcolor("blue")
wugui = turtle.Turtle()
wugui.shape("turtle")
wugui.color("red")
wugui.speed(5)
for i in range(120): # Set the number of squares
    wugui.forward(100)
    wugui.right(90)
    wugui.forward(100)
    wugui.right(90)
    wugui.forward(100)
    wugui.right(90)
    wugui.forward(100)
    wugui.right(93) # This determines the rotation angle each time, and thus the number of squares to draw.
window.exitonclick()

The code should be self-explanatory, so I won’t go into further detail. Turtle is truly a powerful drawing tool that can create a variety of interesting graphics. For more information, please refer to the official Turtle documentation. Here are some basic parameters, divided into two parts: the Turtle and the Screen.


Turtle Methods

Turtle Motion

Turtle Movement and Drawing

forward() | fd(): Moves the turtle forward by the specified distance. Parameter: (integer or float) a number.

backward() | bk() | back(): Moves the turtle backward by the specified distance. Parameter: (integer or float) a number.

right() | rt(): Rotates the turtle right by the specified angle. Parameter: (integer or float) a number. left() | lt(): Rotates the turtle left by the specified angle. Parameter: (integer or float) a number.

goto() | setpos() | setposition(): Moves the turtle to position (x, y). Parameters: (_x_, _y=None_) numbers.

setx(): Sets the X position. Parameter: (integer or float) a number.

sety(): Sets the Y position. Parameter: (integer or float) a number.

setheading() | seth(): Sets the turtle’s orientation to to_angle. This refers to cardinal directions: North is up, South is down, West is left, East is right.

home(): Moves the turtle to the origin - coordinates (0, 0) - and sets its heading to its starting direction.

circle(): Draws a circle with a given radius. Parameters: (radius, extent, steps) (a number __radius, if positive, counter-clockwise; if negative, clockwise__, a number, number of steps to perform).

dot(): Draws a circular dot with a given diameter and color. Parameters: (size, color) (an integer greater than 1, or None; a color value).

stamp(): Copies the turtle’s current shape to the canvas and returns a stamp_id. This can be cleared later using clearstamp().

clearstamp(): Deletes the stamp returned by stamp(). Parameter: (stamp_id) the return value of the stamp function.

clearstamps(): Deletes all stamps. Defaults to no parameters, deletes all.

undo(): Undoes the last action.

speed(): Turtle’s drawing speed. We set it to 5 here; setting it to the fastest would generate the drawing immediately.

Turtle’s Current State

position() | pos(): Current position.

towards(): Returns the angle between the turtle and the specified point. Parameter: (X, Y) a position.

xcor(): Returns the turtle’s X-coordinate.

ycor(): Returns the turtle’s Y-coordinate.

heading(): Returns the turtle’s current heading value.

distance(): Returns the distance between the turtle and a coordinate point. Parameter: (X, Y) a position.

Settings and Measurement

degrees(): Sets the angle for the entire circle. It’s best not to change this. Parameter: (integer or float) an integer.

radians(): Sets the angle measurement unit to radians. 360 degrees is $2pi$.

Pen Control

Drawing State

pendown() | pd() | down(): Puts the pen down on the drawing surface. Moving the turtle will draw.

penup() | pu() | up(): Lifts the pen up. Moving the turtle will not draw.

pensize() | width(): Sets the thickness of the line. Parameter: (width) a positive number.

pen(): Sets the pen’s attributes using key-value pairs.

  • shown”: True/False - Display.
  • pendown”: True/False - Pen down.
  • pencolor”: color-string or color-tuple - Pen color.
  • fillcolor”: color-string or color-tuple - Fill color.
  • pensize”: positive number - Pen size (positive integer).
  • speed”: number in range 0..10 - Drawing speed (range 0-10).
  • resizemode”: “auto” or “user” or “noresize” - Resize mode.
  • stretchfactor”: (positive number, positive number) - Stretch parameters.
  • outline”: positive number - Outline.
  • tilt”: number - Tilt.

isdown(): Returns True if the pen is down, False otherwise.

Color Control

color(): Returns the current pen color and fill color.

pencolor(): Sets the pen’s color.

fillcolor(): Sets the pen’s fill color.

Filling

filling(): Returns the filling status.

begin_fill(): Use before filling.

end_fill(): Ends the fill operation.

More Drawing Control

reset(): Resets all parameters.

clear(): Deletes the drawing. Unlike reset(), it only deletes the graphic and keeps the parameters.

write(): Writes text.

  • arg: object to be written to the TurtleScreen.
  • move: True/False - Move.
  • align: one of the strings “left”, “center”, or “right” - Alignment parameter, choose one of three.
  • font: a triple (fontname, fontsize, fonttype) - Font.

Turtle State

Visibility

showturtle() | st(): Displays the turtle’s shape.

hideturtle() | ht(): Hides the turtle’s shape.

isvisible(): Returns True or False depending on visibility.

Appearance

shape(): Sets the turtle’s graphical shape. Options: ("arrow", "turtle", "circle", "square", "triangle", "classic").

resizemode(): Resize mode.

  • auto”: adapts the appearance of the turtle corresponding to the value of pensize (automatic).
  • user”: adapts the appearance of the turtle according to the values of stretchfactor and outlinewidth (outline) (determined by stretch parameters).
  • noresize”: no adaptation of the turtle’s appearance takes place (no adjustment).

shapesize() | turtlesize(): Returns the pen’s attributes.

shearfactor(): Sets or returns the current shear factor.

settiltangle(): Same as tilt(), but can be empty, then returns the current rotation angle.

tiltangle(): Deprecated.

tilt(): Sets the current turtle angle without affecting the turtle’s direction of movement (only changes the turtle’s appearance).

shapetransform(): Sets or returns the turtle’s shape’s current transformation matrix.

get_shapepoly(): Returns the coordinates of the current shape.

Event Listeners

onclick(): Mouse click event.

  • fun: a function with two arguments which will be called with the coordinates of the clicked point on the canvas (function needs two arguments).
  • num: number of the mouse-button, defaults to 1 (left mouse button) (click count, default 1).
  • add: True or False - if True, a new binding will be added, otherwise it will replace a former binding (add new binding function, otherwise replace previous function).
    • Example:
      def turn(x, y):
          # ...
          left(180)
      onclick(turn)
      

onrelease(): Mouse release event, same as above.

ondrag(): Mouse drag event, same as above.

Special Turtle Methods

begin_poly(): Starts recording the vertices of a polygon; the current point is the starting point.

end_poly(): Ends recording the vertices of a polygon; the current point is the starting point.

get_poly(): Returns the last recorded polygon.

clone(): Creates an exact copy of the turtle.

getturtle() | getpen(): Gets the turtle object itself.

getscreen(): Gets the screen object.

setundobuffer(): Sets or disables the undo buffer.

undobufferentries(): Returns the number of entries in the undo buffer.


Screen Methods

Window Control

bgcolor(): Sets or returns the current screen’s background color.

bgpic(): Sets or returns the current screen’s background image name.

clear() | clearscreen(): Clears the drawing.

reset() | resetscreen(): Resets the screen.

screensize(): Screen size.

  • canvwidth: positive integer, new width of canvas in pixels (width).
  • canvheight: positive integer, new height of canvas in pixels (height).
  • bg: colorstring or color-tuple, new background color (color).

setworldcoordinates(): Global coordinates.

  • llx: a number, x-coordinate of lower left corner of canvas (lower left X-coordinate).
  • lly: a number, y-coordinate of lower left corner of canvas (lower left Y-coordinate).
  • urx: a number, x-coordinate of upper right corner of canvas (upper right X-coordinate).
  • ury: a number, y-coordinate of upper right corner of canvas (upper right Y-coordinate).

Animation Control

delay(): Animation delay (milliseconds). Parameter: (integer) a number.

tracer(): Enables animation, sets delay.

  • n: nonnegative integer (n actions performed once).
  • delay: nonnegative integer (delay in milliseconds).

update(): Updates the canvas, used when tracer is off.

Screen Event Listeners

listen(): Starts listening, positions the mouse on the canvas.

onkey() | onkeyrelease(): Keyboard key up (requires focus, after using listen() above).

  • fun: a function with no arguments or None (action function).
  • key: a string: key (e.g., “a”) or key-symbol (e.g., “space”) (key pressed).

onkeypress(): Keyboard key down event, same as above.

onclick() | onscreenclick(): Mouse click event.

  • fun: a function with two arguments which will be called with the coordinates of the clicked point on the canvas (function needs two arguments).
  • num: number of the mouse-button, defaults to 1 (left mouse button) (click count).
  • add: True or False - if True, a new binding will be added, otherwise it will replace a former binding (whether to add or replace).

ontimer(): Timer.

  • fun: a function with no arguments (no function needed).
  • t: a number $>= 0$ (event interval).

mainloop() | done(): Starts the event loop; must be the last function in Turtle drawing.

Settings and Special Methods

mode(): Drawing mode, one of three: “standard”, “logo”, or “world”.

colormode(): Color mode, 1.0 or 255.

getcanvas(): Returns the TurtleScreen’s current Canvas.

getshapes(): Returns currently available shapes.

register_shape() | addshape(): Three ways to call:

  1. Directly call an image: screen.register_shape("turtle.gif")
  2. Call a shape, specify points:
    screen.register_shape("triangle", ((5,-3), (,5), (-5,-3)))
    
  3. Call a shape, name it anything.

turtles(): Returns a list of turtle objects.

window_height(): Returns the window height.

window_width(): Returns the window width.

Input Methods

textinput(): Text input.

  • title: string (input name).
  • prompt: string (input text).

numinput(): Numeric input.

  • title: string (input name).
  • prompt: string (input text).
  • default: number (optional) (default value).
  • minval: number (optional) (minimum value).
  • maxval: number (optional) (maximum value).

Screen-Specific Methods

bye(): Closes the Turtle window.

exitonclick(): Closes the window on mouse click.

setup(): Sets up the main window parameters.

  • width: if an integer, a size in pixels; if a float, a fraction of the screen; default is 50% of screen (width).
  • height: if an integer, the height in pixels; if a float, a fraction of the screen; default is 75% of screen (height).
  • startx: if positive, starting position in pixels from the left edge of the screen; if negative from the right edge; if None, center window horizontally (left starting position).
  • startx: if positive, starting position in pixels from the top edge of the screen; if negative from the bottom edge; if None, center window vertically (right starting position).

title(): Sets the drawing window title.

Related