Python

Constant dripping wears away a stone

Turtle Graphics


Turtleis a Python module that provides turtle graphics primitives.
  • Tkinter: Tkinter is one of Python's interfaces for developing GUIs(graphical user interfaces). It is a standard GUI library for Python. It provides a object-oriented interface to the Tk GUI toolkit.
  • Public Classes:
    • turtle.RawTurtle(canvas)|turtle.Rawpen(canvas): Create a turtle.canvasis a tkinter.Canvas, a ScrolledCanvas or a TurtleScreen.
    • turtle.Turtle: It is a subclass of RawTurtle. It draws on a default Screen object created automatically.
    • turtle.TurtleScreen(canvas): It provides screen oriented methods.canvasis a tkinter.Canvas.
    • turtle.Screen: It is a subclass of TurtleScreen.
    • turtle.ScrolledCanvas(master):masteris a tkinter.Canvas with scrollbars added.
    • turtle.Shape(type_, data):type_is string "polygon", "image", or "compound".
        When type is
      • "polygon":datais a polygon tuple, which is a tuple of pairs of coordinates.
      • "image":datais an image.
      • "polygon":datais not needed.
    • turtle.Vec2D(x, y): It is a 2D vector class. A vector is a tuple.
  • Turtle Methods:
    • Turtle Motion:
      • position() | pos(): Return the turtle's current location (x, y).
      • goto(x[, y]) | setpos(x[, y]) | setposition(x[, y]): Ifyis not given,xmust be a pair of numbers representing x and y coordinates. Move the turtle to an absolute position in the same orientation as the turtle's current orientation. If the pen is down, draw line while moving.
      • home(): Move turtle to the origin (coordinates(0, 0)), and set its heading to its start orientation.
      • speed([an_integer | a_speedstring]): Set the tutle's moving speed. The parameter is optional. If no parameter, the turtle uses the current speed and the function returns the current speed. Turtle's speed is an integer in the range of 0 to 10; If the parameter given is a number that is greater than 10 or less than 0.5, it is set to 0. If it is a decimal number between 0 and 10, it will be rounded to its nearest integer. Zero speed means that no animation takes place and the turtle moves instantly. Speedstrings are mapped speedvalues. "fastest" is 0, "fast" is 10, "normal" is 6, "slow" is 3, and "slowest" is 1.
      • forward(distance) | fd(distance): The parameterdistanceis a number which specifies the number of pixels the turtle moves. Move the turtle forward by the specifieddistancein the same direction as the turtle's current heading direction. Ifdistanceis negative, move the turtle backward by the specified distance in the opposite direction to the turtle's current heading direction.
      • backward(distance) | bk(distance) | back(distance): The parameterdistanceis a number which specifies the number of pixels the turtle moves. Move the turtle backward by the specifieddistancein the opposite direction to the current heading direction of the turtle. Ifdistanceis negative, move the turtle forward by the specified distance in the same direction as the turtle's current heading direction.
      • right(angle) | rt(angle): The parameterangleis a number which specifies angle units that the turtle turns. Turn the turtle right by the specifiedangleunits (by default, units are degrees).
      • left(angle) | lt(angle): The parameterangleis a number which specifies angle units that the turtle turns. Turn the turtle left by the specifiedangleunits (by default, units are degrees).
      • setx(x_coordinate): Set the turtle's first coordinate tox_coordinator. The second coordinate is unchanged.
      • sety(y_coordinate): Set the turtle's second coordinate toy_coordinator. The first coordinate is unchanged.
      • setheading(to_angle) | seth(to_angle): Set the heading direction of the turtle toto_anglein degrees. Forto_angle, in standard mode, 0 means east, 90 means north, 180 means west, and 270 means south.
      • circle(radius[, extent, steps]): Draw a circle with the givenradius. The center of the circle isradiusunits from the turtle and the segment between the circle and the turtle is perpendicular to the turtle's heading direction. Ifradiusis positive, draw the circle in counterclockwise direction; otherwise draw the circle in clockwise direction. Ifextentis not given, draw an entire circle; othwerwise, draw an arc ofententdegrees. A circle is approximated by an inscribed regular polygon.stepsspecifies the number of steps to be used to draw a circle. Ifstepsis not given, it will be calculated automatically.
      • dot([diameter_size, color]): Draw a dot using colorcolorand diameterdiameter_sizeif they are given. Ifcoloris not given, use black color. Ifdiameter_sizeis not given, use the maximum of turtle.pensize()+4 and 2*turtle.pensize().
      • stamp(): Stamp the turtle's shape onto the canvas at the current turtle position and return a stamp_id for that stamp.
      • clearstamp(stamp_id): Delete stamp withstamp_idwhich is returned from stamp() call.
      • clearstamps(number):numberis an integer which indicates the number of stamps to be deleted. Ifnumberis not given, delete all stamps. Ifnumberis a positive integer, delete firstnumberstamps. Ifnumberis a negative integer, delete lastnumberstamps.
      • undo(): Undo the last turtle action(s). The number of undo actions is determined by the size of the undobuffer.
      • towards(x[, y]): Ifyis not given,xmust be a pair of numbers representing x and y coordinates. Return the angle between the line from turtle position to position specified by (x, y) or x (if y is not given).
      • xcor(): Return the turtle’s x coordinate.
      • ycor(): Return the turtle’s y coordinate.
      • heading(): Return the turtle’s current heading.
      • distance(x[, y]): Ifyis not given,xmust be a pair of numbers representing x and y coordinates. Return the distance between between the turtle position to the position specified by (x, y) or x (if y is not given).
      • degrees(fullcircle=360): Set angle measurement units to degrees, i.e., set the number of “degrees” for a full circle. Default value for a full circle is 360 degrees. If it is set to be 400 degrees, a quater circle would be 400/4=100 degrees.
      • radians(): Set angle measurement units to radians. i.e., 360 degrees is equivalent to radians 2*math.pi, and 90 degrees is equivalent to half of math.pi.
    • Pen Control:
      • pendown() | pd() | down(): Put the pen down, which means that the turtle draws while moving.
      • penup() | pu() | up(): Pull the pen up, which means the turtle does not draw when moving.
      • pensize([width]) | width([width]):widthis optional, which indicates pen thickness. If it is not given, the function return the current pensize.
      • pen([pendict | keyword_parameters]): Turtle's pen attributes are a pen-dictionary: {'shown': True/False, 'pendown': True/False, 'pencolor': color-string/color-tuple, 'fillcolor': color-string/color-tuple, 'pensize': a-positive-number, 'speed': 0..10, 'resizemode': 'auto'/'user'/'noresize', 'stretchfactor': (a-positive-number, a-positive-number), 'shearfactor': number, 'outline': a-positive-number, 'tilt': number}. If no argments, this method returns a pen dictionary. If has parameters, the parameters can be a dictionary with some or all of the above listed key-value pairs or one or more keyword-parameters with the above listed keys as keywords. The parameters can also be a mix of a dictionary and keyword-parameters.
      • isdown(): Return True if pen is down; otherwise return False.
      • pencolor([color]):coloris either a colorstring or a RGB color represented by a tuple of (r, g, b) or r, g, b. Each of r, g, and b must be in the range 0..colormode, where colormode is either 1 or 255. If no parameter, the method returns the current pencolor.
      • fillcolor([color]):coloris either a colorstring or a RGB color represented by a tuple of (r, g, b) or r, g, b. Each of r, g, and b must be in the range 0..colormode, where colormode is either 1 or 255. If no parameter, the method returns the current fillcolor.
      • color([color1, color2]): If no argements, the method returns a tuple of the turtle's pencolor and fillcolor. If bothcolor1 andcolor2are given, they can a colorstring, or a RGB color represented by a tuple of (r, g, b), withcolor1as pencolor andcolor2as fillcolor. If onlycolor1is given, it can be a colorstring, or a RGB color represented by a tuple of (r, g, b) or r, g, b, withcolor1for both pencolor and fillcolor.
      • begin_fill(): This method should be called just before drawing a shape to be filled.
      • end_fill(): This method should be called after finish drawing and filling a shape after the last call to begin_fill().
      • filling(): Return fillstate, which is True if filling and False otherwise.
      • reset(): Delete the turtle’s drawings from the screen, re-center the turtle and set variables to default values.
      • clear(): Delete the turtle’s drawings from the screen, but the turtle's state and position remain unchanged.
      • write(info[, move=False, align="left", font]): This function writes text specified byinfoat the current turtle position with the given font according toalign.
        • infois the information that you want to write at the position such as a string, a tuple, a list, a dictionary, etc.
        • moveis False or True. By default it is false. If it is True, the pen is moved to the bottom-right corner of the written text.
        • alignis "left", "center", or "right". Its default is "left".
        • fontis a triple of fontname (i.e, "Arial", etc.), fontsize, fonttype (i.e., 'normal', 'bold', etc.). If this parameter is not given, default font will be used. If only one of the triple is given, it can be a string for fontname, an integer for fontsize, or a string for fonttype. If two or three of the triple are given, they need to be enclosed in a pair of brackets.
    • Turtle State:
      • showturtle() | st(): Make the turtle visible.
      • hideturtle() | ht(): Make the turtle invisible.
      • isvisible(): Return True if the turtle is shown; otherwise return False.
      • shape([shapename]): Set the turtle shape to shapeshapename. Ifshapenameis not given, return the name of the current turtle shape.shapenamemust be in the TurtleScreen's shape dictionary. The initial shape dictionary has the polygon shapes "arrow", "turtle", "circle", "square", "triangle", and "classic".
      • resizemode([rmode]): Set resizemode to one of the values: “auto”, “user”, “noresize”. Ifrmodeis not given, return the current resizemode.
        • "auto": adapts the appearance of the turtle according to the turtle's pensize.
        • "user": adapts the appearance of the turtle according to the turtle's stretchfactor and outline set by shapesize().
        • "noresize": no adaption of the turtle’s appearance.
      • shapesize([stretch_wid=None, stretch_len=None, outline=None]) | turtlesize(stretch_wid=None, stretch_len=None, outline=None): Return or set the pen’s attributes stretchfactors and/or outline. If and only if resizemode is set to “user”, the turtle will be displayed stretched according to its stretchfactorsstretch_widandstretch_len.
        • stretch_widis stretchfactor perpendicular to its orientation. It is a positive number.
        • stretch_lenis stretchfactor in direction of its orientation. It is a positive number.
        • outlinedetermines the width of the shapes’s outline. It is a positive number.
      • shearfactor([shear]): Shear the turtleshape according to the given shearfactor. Return the current shearfactor ifshearis not given. Otherwise, set the shearfactor to beshear(a number), which is the tangent of the shear angle. The turtle’s heading ((moving direction) remains unchanged.
      • tilt(angle): Rotate the turtleshape byangle(a number) from its current tilt-angle, which is the angle between the orientation of the turtleshape and the heading of the turtle. The turtle's heading remains unchanged.
      • settiltangle(angle): Rotate the turtleshape to point in the direction which isangleaway from the turtle's heading direction, regardless of its current tilt-angle. The turtle’s heading remains unchanged.
      • tiltangle([angle]): Return the current title-angle ifangleis not given. Otherwise rotate the turtleshape to point in the direction which isangleaway from the turtle's heading direction, regardless the current tilt-angle. The turtle's heading remains unchanged.
      • shapetransform(t11=None, t12=None, t21=None, t22=None): If parameters are given, they are numbers used to set the turtleshape's transformation matrix with t11 and t12 in the first row and t21 and t22 in the second row. The matrix must not be singular. In other words, the determinant t11 * t22 - t12 * t21 must not be zero, otherwise an error will be raised. If no parameters, return the current turtle shape's transformation matrix as a tuple of four elements.
      • get_shapepoly(): Return the current turtleshape polygon as a tuple of coordinate pairs. This can be used to define a new shape or components of a compound shape.
    • Using Events for Turtle:
      • onclick(function[, mouse_button=1, add_binding=False]): Bindfunctionto the mouse-click event on this turtle. Iffunction is None, existing bindings are removed.
        • function:Required. It is a function with two parameters. The function will be called with the x and y coordinates of the clicked point on the canvas.
        • mouse_button:Optional. It is a mouse-button number. Its default value is 1 (left mouse button). Number 2 represents middle mouse button and 3 represents right mouse button.
        • add_binding:Optional. It is a boolean type. If it is True, a new binding will be added to the mouse-click event on this screen; otherwise the new function will replace a former binding.
      • onrelease([function, mouse_button=1, add_binding=False]): Bindfunctionto mouse-button-release events on this turtle. If nofunction is given, existing bindings are removed.
      • ondrag([function, mouse_button=1, add_binding=False]): Bind fun to mouse-drag events on this turtle. If fun is None, existing bindings are removed.
    • Special Turtle Methods:
      • begin_poly(): Start recording the vertices of a polygon. The current turtle position is the first vertex of the polygon.
      • end_poly(): Stop recording the vertices of a polygon. The current turtle position is the last vertex of the polygon.
      • get_poly(): Return the last recorded polygon.
      • clone(): Create and return a clone of the turtle with same position, heading and properties.
      • getturtle() | getpen(): Return the Turtle object.
      • getscreen(): Return the TurtleScreen object the turtle is drawing on.
      • setundobuffer([size]): Set or disable undobuffer. Ifsizeis an integer, an empty undobuffer of given size is installed.sizespecifies the maximum number of turtle actions that can be undone by the undo() method. Ifsizeis None, undobuffer is disabled.
      • undobufferentries(): Return the number of entries in the undobuffer. If setundobuffer(None),undobufferentrieswill be 0. Otherwise,undobufferentriesis minimum of the size passed to thesetundobuffer()method and the number of last turtle actions.
  • TurtleScreen/Screen Methods:
  • Window Control:
    • bgcolor([color]): Set or return the background color of the TurtleScreen.coloris either a colorstring, or a RGB color represented by a tuple of (r, g, b), or three numbers r, g, b. Each of r, g, and b must be in the range 0..colormode, where colormode is either 1 or 255. If no parameter, the method returns the current background color.
    • bgpic(picture_name): Set background image ifpicture_nameis given or return the name of the current background image if no parameter or it is None.picture_nameis a string which is the name of an image, or 'nopic', or None. Ifpicture_nameis 'nopic', delete the background image if there is one.
    • clearscreen(): Delete all drawings and all turtles from the TurtleScreen and then reset the empty TurtleScreen to its initial state with white background with no background image, no event bindings and tracing on.
    • resetscreen(): Reset all turtles on the TurtleScreen to their initial state.
    • screensize([canvasWidth=None, canvasHeight=None, backgroundColor=None]): Resize the canvas size to(canvasWidth, canvasHeight)if the first two parameters are given. Set the new background color of canvas tobackgroundColorifbackgroundColoris given. If no parameters, return the current canvas size.
      • canvasWidth:A positive integer which is the new width of canvas in pixels.
      • canvasHeight:A positive integer which is the new height of canvas in pixels.
      • backgroundColor:A colorstring or a color tuple which is the new background color of canvas.
    • setworldcoordinates(llx, lly, urx, ury): Set up a user-defined coordinate system; switch to mode 'world' if necessary. If mode 'world' is already active, all drawings are redrawn according to the new coordinates. All four parameters are required.
      • llx:a number, which is the x-coordinate of the lower left corner of the canvas.
      • llya number, which is the y-coordinate of the lower left corner of the canvas.
      • urx:a number, which is the x-coordinate of the upper right corner of the canvas.
      • ury:a number, which is the y-coordinate of the upper right corner of the canvas.
  • Animation Control:
    • delay([delay=None]):delayis a positive integer in milliseconds. If it is given, set the drawing delay in milliseconds. The longer the drawing delay, the slower the animation. If it is None or not given, return the drawingdelayin milliseconds.
    • tracer([n=1, delay]): Turn turtle animation on(n>=1) or off (n=0)and set delay for drawing updates. Bothnanddelayare nonnegative integers. If both are positive numbers, slowed down drawing updates on the screen will be displayed, which is like tracing in turtle graphics. If no parameters, return the current stored value of n. Ifnis greater than 0, each n-th regular screen update will be really performed. For example, ifn=1, the default, every screen update will occur. Ifn=2, only every other screen update will occur. Ifdelayis also given, set the delay value for screen updates.
    • update(): Perform a TurtleScreen update, which will be used when tracer is turned off.
  • Using Screen Events: The actions that an user performs, such as moving the mouse, clicking the mouse buttons, or hitting certain keys on the keyboard, are called events. The turtle module is able to detect such events. If necessary, we can make the turtle listen for events and run certain functions when hear the events.
    • listen(): To listen for events (set focus on TurtleScreen). If certain events after this function have occurred, act correspondingly.
    • onkey(my_function, key) | onkeyrelease(my_function, key): Bindmy_functionto key-release event of keykey. Ifmy_functionis None, event bindings are removed. TurtleScreen must have the focus when call this method.
      • my_functionrequired. It is a function with no parameters or None.
      • keyrequired. It is a string representing a key such as "a", "@", etc, or a key-symbol such as "space".
    • onkeypress(my_function[, key]): Bindmy_functionto key-press event of keykeyifkey is given, or to any key-press event ifkeyis not given. TurtleScreen must have the focus when call this method.
    • onclick(function[, mouse_button=1, add_binding=False]) | onscreenclick(function[, mouse_button=1, add_binding=False]): Bindfunctionto the mouse-click event on this screen. Iffunctionis None, existing bindings are removed.
      • function:Required. It is a function with two parameters. The function will be called with the x and y coordinates of the clicked point on the canvas.
      • mouse_button:Optional. It is a mouse-button number. Its default value is 1 (left mouse button). Number 2 represents middle mouse button and 3 represents right mouse button.
      • add_binding:Optional. It is True/False. If it is True, a new binding will be added to the mouse-click event on this screen; otherwise the new function will replace a former binding.
    • ontimer(my_function[, time=0]): Install a timer that callsmy_functionaftertimemilliseconds.
      • my_function:Required. It is a function with no parameters.
      • time:Optional. It is a nonnegative number in milliseconds. By default, it is 0.
    • mainloop() | done(): It is a Screen method that calls Tkinter.mainloop() to start event loop. It must be the last statement for an interactive use of turtle graphics in a turtle graphics program.
  • Settings and Special Methods:
    • mode([mode=None]): Set turtle mode and perform reset.modeis one of the strings "standard", "logo", or "world". ifmodeis not given, return the current mode.
      • "standard":This mode is compatible with old turtle. The initial turtle heading in this mode is to the right.
      • "logo":This mode is compatible with most Logo turtle graphics.
      • "world":This mode uses user-defined world coordinates. In this mode, angles appear distorted if x/y unit ratio is not 1.
    • colormode([color_mode=None]):color_modeis either 1.0 or 255. Set the colormode ifcolor_modeis given or return the current colormode if it is not given or is None. If it is 1.0, the r, g, b values of a color triple have to be in the range of (0, 1); if it is 255, the r, g, b values of a color triple have to be in the range of (0, 255).
    • getcanvas(): Return the Canvas of this TurtleScreen.
    • getshapes(): Return a list of names of all currently available turtle shapes.
    • register_shape(name[, shape=None]) | addshape(name[, shape=None]): Add a shape to the shapelist of TurtleScreen. There are three ways to call this function:
      • nameis the name of a gif file and noshape.Install the image shape. Image shapes do not rotate when turning the turtle.
      • nameis an arbitrary string andshapeis a tuple of pairs of coordinates. Install the corresponding polygon shape.
      • nameis an arbitrary string andshapeis a compound shape object. Install the corresponding compound shape.
    • turtles(): Return the list of turtles on the screen.
    • window_height(): Return the height of the turtle window.
    • window_width(): Return the width of the turtle window.
  • Input Methods:
    • textinput(title, prompt): Pop up a dialog window on the screen for a text input.titleis the title of the dialog window,promptis a string that describes what information to input. Return the text input (a string). If the dialog is cancelled before submitting (clicking 'ok'), return None.
    • numinput(title, prompt[, default=None, minval=None, maxval=None]): Pop up a dialog window for input of a number.titleis the title of the dialog window,promptis a string that describes what numerical information to input.defaultis default value,minvalis minimum value for input,maxvalis maximum value for input. Ifminvalandmaxvalare given, the number input must be in the range [minval, maxval]. Return the number input. If the dialog is cancelled before submitting (clicking 'ok'), return None.
  • Methods Specific to Screen:
    • bye(): Close the turtle graphics window.
    • exitonclick(): Bind functionbye()to mouse clicks on the turtle graphics windows. The turtle graphics window will be closed when click on the turtle graphics window.
    • setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom'): Set the size and position of the main window. Default values of the parameters are stored in the configuration dictionary and can be changed viaturtle.cfgfile.
      • width:A positive number. If it is an integer, set the width of the windowwidthin pixels. If it is a float, set the width of the turtle graphics window to a fraction of the computer screen. The default is 50% of the computer screen.
      • height:A positive number. If it is an integer, set the height of the windowheightin pixels. If it is a float, set the height of the turtle graphics window to a fraction of the computer screen. The default is 75% of the computer screen.
      • startx:If it is positive, set the left edge of the turtle graphics windowstartxin pixels away from the left edge of the computer screen. If it is negative, set the right edge of the turtle graphics window-startxin pixels away from the right edge of the screen. If it is 0 or None, center the window horizontally.
      • starty:If it is positive, set the top edge of the turtle graphics windowstartyin pixels away from the top edge of the screen. If it is negative, set the bottom edge of the turtle graphics window-startyin pixels away from the bottom edge of the screen. If it is 0 or None, center the window vertically.
    • title(titleString): Set the title of the turtle graphics window totitleString.titleStringis a string that is shown in the titlebar of the turtle graphics window.