https://github.com/python/cpython/commit/863630a31913d567a6fd40475222e21c4ef4e6f7
commit: 863630a31913d567a6fd40475222e21c4ef4e6f7
branch: 3.15
author: Stan Ulbrych <[email protected]>
committer: StanFromIreland <[email protected]>
date: 2026-11-22T11:44:25Z
summary:
[3.15] gh-157847: Tidy up the remaining `turtle` reference docs (GH-162014)
(#162431)
(cherry picked from commit 51e0ff084c2668002a1516a3968874a9b18da555)
files:
M Doc/library/turtle.rst
M Lib/turtle.py
diff --git a/Doc/library/turtle.rst b/Doc/library/turtle.rst
index 3b7c72385d5654..471e0f6da2ecbe 100644
--- a/Doc/library/turtle.rst
+++ b/Doc/library/turtle.rst
@@ -496,9 +496,9 @@ Move and draw
of the turtle; *extent*, an angle, determines which part of the circle is
drawn. If *extent* is not given, draw the entire circle. If *extent* is
not a full circle, one endpoint of the arc is the current pen position.
- Draw the arc in counterclockwise direction if *radius* is positive,
- otherwise in clockwise direction. Finally, the turtle's heading is changed
- by *extent*.
+ Draw the arc in the counterclockwise direction if *radius* is positive,
+ otherwise in the clockwise direction. Finally, the turtle's heading is
+ changed by *extent*.
As the circle is approximated by an inscribed regular polygon, *steps*
determines the number of steps to use. If not given, it will be calculated
@@ -606,8 +606,9 @@ Move and draw
.. function:: undo()
- Undo (repeatedly) the last turtle action(s). Number of available
- undo actions is determined by the size of the undobuffer.
+ Undo the last turtle action. Calling :func:`!undo` repeatedly undoes one
+ action at a time. The number of actions that can be undone is set by the
+ size of the undo buffer, see :func:`setundobuffer`.
.. doctest::
:skipif: _tkinter is None
@@ -625,8 +626,9 @@ Move and draw
Return or set the turtle's speed. If *speed* is not given, return the
current speed. Otherwise set the turtle's speed to an integer from 0 to 10.
- If *speed* is a number greater than 10 or smaller than 0.5, the speed is
- set to 0. You can also use these names instead of numbers:
+ A number above 0.5 and below 10.5 is rounded to the nearest integer. Any
+ other number sets the speed to 0. You can also use these names instead of
+ numbers:
* "fastest": 0
* "fast": 10
@@ -1210,7 +1212,7 @@ Appearance
Set the turtle shape to the named shape. If *name* is not given, return the
name of the current shape. The shape must exist in the
- :class:`TurtleScreen`'s shape dictionary. Initially there are the following
+ :class:`TurtleScreen`'s shape list. Initially there are the following
shapes: "arrow", "turtle", "circle", "square", "triangle" and "classic". To
add shapes, see the :class:`Screen` method :func:`register_shape`.
@@ -1380,7 +1382,7 @@ Appearance
Return the points that form the outline of the current turtle shape
as a tuple of ``(x, y)`` coordinate pairs. These points can be used
- to define a new shape or parts of a :ref:`compound shape <compound-shapes>`
+ to define a new shape or parts of a :ref:`compound shape <compound-shapes>`.
.. doctest::
:skipif: _tkinter is None
@@ -1405,7 +1407,7 @@ Using events
coordinates of the clicked point on the canvas. If *fun* is ``None``,
existing bindings are removed. *btn* is the number of the mouse button and
defaults to 1, the left mouse button. If *add* is ``True``, a new binding
- is added, otherwise it replaces a former binding. Example for the
+ is added, otherwise it replaces a previous binding. Example for the
anonymous turtle, that is, the procedural way:
.. doctest::
@@ -1420,14 +1422,16 @@ Using events
.. function:: onrelease(fun, btn=1, add=None)
- :param fun: a function with two arguments which will be called with the
- coordinates of the clicked point on the canvas
- :param btn: number of the mouse-button, defaults to 1 (left mouse button)
- :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
- added, otherwise it will replace a former binding
+ :param fun: a function with two arguments or ``None``
+ :param btn: an integer
+ :param add: a boolean or ``None``
- Bind *fun* to mouse-button-release events on this turtle. If *fun* is
- ``None``, existing bindings are removed.
+ Bind *fun* to mouse-button-release events on this turtle. *fun* is called
+ with the coordinates of the point on the canvas where the mouse button is
+ released. If *fun* is ``None``, existing bindings are removed. *btn* is the
+ number of the mouse button and defaults to 1, the left mouse button. If
+ *add* is ``True``, a new binding is added, otherwise it replaces a previous
+ binding.
.. doctest::
:skipif: _tkinter is None
@@ -1435,6 +1439,7 @@ Using events
>>> class MyTurtle(Turtle):
... def glow(self,x,y):
... self.fillcolor("red")
+ ...
... def unglow(self,x,y):
... self.fillcolor("")
...
@@ -1445,25 +1450,25 @@ Using events
.. function:: ondrag(fun, btn=1, add=None)
- :param fun: a function with two arguments which will be called with the
- coordinates of the clicked point on the canvas
- :param btn: number of the mouse-button, defaults to 1 (left mouse button)
- :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
- added, otherwise it will replace a former binding
-
- Bind *fun* to mouse-move events on this turtle. If *fun* is ``None``,
- existing bindings are removed.
+ :param fun: a function with two arguments or ``None``
+ :param btn: an integer
+ :param add: a boolean or ``None``
- Remark: Every sequence of mouse-move-events on a turtle is preceded by a
- mouse-click event on that turtle.
+ Bind *fun* to mouse-move events on this turtle. *fun* is called with the
+ coordinates of the mouse pointer on the canvas. If *fun* is ``None``,
+ existing bindings are removed. *btn* is the number of the mouse button and
+ defaults to 1, the left mouse button. If *add* is ``True``, a new binding
+ is added, otherwise it replaces a previous binding. Every sequence of
+ mouse-move events on a turtle is preceded by a mouse-click event on that
+ turtle.
.. doctest::
:skipif: _tkinter is None
>>> turtle.ondrag(turtle.goto)
- Subsequently, clicking and dragging the Turtle will move it across
- the screen thereby producing handdrawings (if pen is down).
+ Clicking and dragging the turtle then moves it across the screen, drawing
+ by hand if the pen is down.
Special Turtle methods
@@ -1593,8 +1598,8 @@ Special Turtle methods
.. doctest::
:skipif: _tkinter is None
- >>> while undobufferentries():
- ... undo()
+ >>> while turtle.undobufferentries():
+ ... turtle.undo()
.. _methods-of-turtlescreen-screen:
@@ -1706,7 +1711,7 @@ Window control
:param canvwidth: a positive integer or ``None``
:param canvheight: a positive integer or ``None``
- :param bg: a colorstring or a color tuple or ``None``
+ :param bg: a colorstring or ``None``
Resize the canvas the turtles are drawing on. *canvwidth* and *canvheight*
are the new width and height of the canvas in pixels, and *bg* is the new
@@ -1826,7 +1831,7 @@ Animation control
.. function:: update()
- Perform a TurtleScreen update. To be used when tracer is turned off.
+ Perform a TurtleScreen update. To be used when :func:`tracer` is turned off.
See also the RawTurtle/Turtle method :func:`speed`.
@@ -1905,7 +1910,7 @@ Using screen events
coordinates of the clicked point on the canvas. If *fun* is ``None``,
existing bindings are removed. *btn* is the number of the mouse button and
defaults to 1, the left mouse button. If *add* is ``True``, a new binding
- is added, otherwise it replaces a former binding.
+ is added, otherwise it replaces a previous binding.
Example for a TurtleScreen instance named ``screen`` and a Turtle instance
named ``turtle``:
@@ -1978,10 +1983,10 @@ Input methods
Pop up a dialog window for input of a number. *title* is the title of the
dialog window and *prompt* is a text describing what numerical information
to input. *default* is the default value, *minval* and *maxval* are the
- minimum and maximum values for input. If these are given, the number
- entered must be between *minval* and *maxval*. If not, a hint is issued
- and the dialog remains open for correction. Return the number entered. If
- the dialog is canceled, return ``None``. ::
+ minimum and maximum values for input. If these are given and the number
+ entered is not between *minval* and *maxval*, a hint is issued and the
+ dialog remains open for correction. Return the number entered. If the
+ dialog is canceled, return ``None``. ::
>>> screen.numinput("Poker", "Your stakes:", 1000, minval=10,
maxval=10000)
@@ -2031,7 +2036,7 @@ Settings and special methods
>>> turtle.pencolor(240, 160, 80)
Traceback (most recent call last):
...
- TurtleGraphicsError: bad color sequence: (240, 160, 80)
+ turtle.TurtleGraphicsError: bad color sequence: (240, 160, 80)
>>> screen.colormode()
1.0
>>> screen.colormode(255)
@@ -2131,29 +2136,6 @@ Settings and special methods
640
-.. _screenspecific:
-.. _methods-specific-to-screen-not-inherited-from-turtlescreen:
-
-Screen-only methods
-^^^^^^^^^^^^^^^^^^^
-
-.. function:: bye()
-
- Close the turtle graphics window.
-
-
-.. function:: exitonclick()
-
- Bind ``bye()`` method to mouse clicks on the Screen.
-
-
- If the value "using_IDLE" in the configuration dictionary is ``False``
- (default value), also enter mainloop. Remark: If IDLE with the ``-n``
switch
- (no subprocess) is used, this value should be set to ``True`` in
- :file:`turtle.cfg`. In this case IDLE's own mainloop is active also for the
- client script.
-
-
.. function:: save(filename, *, overwrite=False)
:param filename: a string
@@ -2174,30 +2156,53 @@ Screen-only methods
.. versionadded:: 3.14
+.. _screenspecific:
+.. _methods-specific-to-screen-not-inherited-from-turtlescreen:
+
+Screen-only methods
+^^^^^^^^^^^^^^^^^^^
+
+.. function:: bye()
+
+ Close the turtle graphics window.
+
+
+.. function:: exitonclick()
+
+ Bind :func:`bye` to mouse clicks on the screen and start the event loop.
+ Clicking on the screen then closes the turtle graphics window. If the
+ configuration value ``using_IDLE`` is ``True``, the event loop is not
+ started, see :func:`mainloop`.
+
+
.. function:: 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 arguments
- are stored in the configuration dictionary and can be changed via a
- :file:`turtle.cfg` file.
+ :param width: an integer or a float
+ :param height: an integer or a float
+ :param startx: an integer or ``None``
+ :param starty: an integer or ``None``
+
+ Set the size and position of the main window.
- :param width: if an integer, a size in pixels, if a float, a fraction of the
- screen; default is 50% of screen
- :param height: if an integer, the height in pixels, if a float, a fraction
of
- the screen; default is 75% of screen
- :param 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
- :param starty: if positive, starting position in pixels from the top
- edge of the screen, if negative from the bottom edge, if
``None``,
- center window vertically
+ *width* and *height* are the size of the window. As integers they are sizes
+ in pixels, as floats they are fractions of the screen, so 0.5 is half the
+ screen. The defaults are 50% of the screen width and 75% of its height.
+
+ *startx* and *starty* are the position of the window. If positive, they are
+ the distance in pixels from the left and top edges of the screen, if
+ negative from the right and bottom edges. If ``None``, the window is
+ centered in that direction.
+
+ The default values of all arguments are stored in the configuration
+ dictionary and can be changed with a :file:`turtle.cfg` file.
.. doctest::
:skipif: _tkinter is None
- >>> screen.setup (width=200, height=200, startx=0, starty=0)
- >>> # sets window to 200x200 pixels, in upper left of screen
- >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
- >>> # sets window to 75% of screen by 50% of screen and
centers
+ >>> screen.setup(width=200, height=200, startx=0, starty=0)
+ >>> # sets window to 200x200 pixels, in upper left of screen
+ >>> screen.setup(width=0.75, height=0.5)
+ >>> # sets window to 75% of screen by 50% of screen and centers
.. function:: title(titlestring)
@@ -2222,8 +2227,8 @@ Public classes
:param canvas: a :class:`!tkinter.Canvas`, a :class:`ScrolledCanvas` or a
:class:`TurtleScreen`
- Create a turtle. The turtle has all methods described above as "methods of
- Turtle/RawTurtle".
+ Create a turtle. The turtle has all the methods described in
+ :ref:`turtle-methods`.
.. class:: Turtle()
@@ -2236,8 +2241,8 @@ Public classes
:param cv: a :class:`!tkinter.Canvas`
- Provides screen oriented methods like :func:`bgcolor` etc. that are
described
- above.
+ Provides the screen-oriented methods, such as :func:`bgcolor`, that are
+ described above.
.. class:: Screen()
@@ -2250,13 +2255,13 @@ Public classes
.. class:: ScrolledCanvas(master)
- :param master: some Tkinter widget to contain the ScrolledCanvas, i.e.
- a Tkinter-canvas with scrollbars added
+ :param master: a Tkinter widget
- Used by class Screen, which thus automatically provides a ScrolledCanvas as
- playground for the turtles.
+ A Tkinter canvas with scrollbars added. *master* is the widget that contains
+ it. Used by class :class:`Screen`, which thus automatically provides a
+ ScrolledCanvas as playground for the turtles.
-.. class:: Shape(type_, data)
+.. class:: Shape(type_, data=None)
:param type\_: a string
:param data: depends on *type_*
@@ -2388,7 +2393,7 @@ below:
>>> poly2 = ((0,0), (10,-5), (-10,-5))
>>> s.addcomponent(poly2, "blue", "red")
-3. Now add the Shape to the Screen's shapelist and use it:
+3. Now add the Shape to the Screen's shape list and use it:
.. doctest::
:skipif: _tkinter is None
@@ -2491,38 +2496,52 @@ via docstrings. So these can be used as online-help
via the Python help
facilities:
- When using IDLE, tooltips show the signatures and first lines of the
- docstrings of typed in function-/method calls.
+ docstrings of typed in function/method calls.
- Calling :func:`help` on methods or functions displays the docstrings::
- >>> help(Screen.bgcolor)
- Help on method bgcolor in module turtle:
-
- bgcolor(self, *args) unbound turtle.Screen method
- Set or return backgroundcolor of the TurtleScreen.
-
- Arguments (if given): a color string or three numbers
- in the range 0..colormode or a 3-tuple of such numbers.
-
+ >>> help(TurtleScreen.bgcolor)
+ Help on function bgcolor in module turtle:
- >>> screen.bgcolor("orange")
- >>> screen.bgcolor()
- "orange"
- >>> screen.bgcolor(0.5,0,0.5)
- >>> screen.bgcolor()
- "#800080"
+ bgcolor(self, *args)
+ Return or set the background color of the TurtleScreen.
+
+ Four input formats are allowed:
+ - bgcolor()
+ Return the current background color as a color specification
+ string or as a tuple (see example). May be used as input
+ to another color(), pencolor(), fillcolor() or bgcolor() call.
+ - bgcolor(colorstring)
+ Set the background color to colorstring, which is a Tk color
+ specification string, such as "red", "yellow", or "#33cc8c".
+ - bgcolor((r, g, b))
+ Set the background color to the RGB color represented by
+ the tuple of r, g, and b. Each of r, g, and b must be
+ between 0 and colormode, where colormode is either 1.0 or 255
+ (see colormode()).
+ - bgcolor(r, g, b)
+ Set the background color to the RGB color represented by
+ r, g, and b. Each of r, g, and b must be between 0 and
+ colormode.
+
+ Example (for a TurtleScreen instance named screen):
+ >>> screen.bgcolor("orange")
+ >>> screen.bgcolor()
+ 'orange'
+ >>> screen.colormode(255)
+ >>> screen.bgcolor("#800080")
+ >>> screen.bgcolor()
+ (128.0, 0.0, 128.0)
>>> help(Turtle.penup)
- Help on method penup in module turtle:
+ Help on function penup in module turtle:
- penup(self) unbound turtle.Turtle method
- Pull the pen up -- no drawing when moving.
+ penup(self)
+ Lift the pen.
Aliases: penup | pu | up
- No argument
-
- >>> turtle.penup()
+ The turtle does not draw when it moves.
- The docstrings of the functions which are derived from methods have a
modified
form::
@@ -2531,32 +2550,44 @@ facilities:
Help on function bgcolor in module turtle:
bgcolor(*args)
- Set or return backgroundcolor of the TurtleScreen.
-
- Arguments (if given): a color string or three numbers
- in the range 0..colormode or a 3-tuple of such numbers.
+ Return or set the background color of the TurtleScreen.
+
+ Four input formats are allowed:
+ - bgcolor()
+ Return the current background color as a color specification
+ string or as a tuple (see example). May be used as input
+ to another color(), pencolor(), fillcolor() or bgcolor() call.
+ - bgcolor(colorstring)
+ Set the background color to colorstring, which is a Tk color
+ specification string, such as "red", "yellow", or "#33cc8c".
+ - bgcolor((r, g, b))
+ Set the background color to the RGB color represented by
+ the tuple of r, g, and b. Each of r, g, and b must be
+ between 0 and colormode, where colormode is either 1.0 or 255
+ (see colormode()).
+ - bgcolor(r, g, b)
+ Set the background color to the RGB color represented by
+ r, g, and b. Each of r, g, and b must be between 0 and
+ colormode.
- Example::
-
- >>> bgcolor("orange")
- >>> bgcolor()
- "orange"
- >>> bgcolor(0.5,0,0.5)
- >>> bgcolor()
- "#800080"
+ Example:
+ >>> bgcolor("orange")
+ >>> bgcolor()
+ 'orange'
+ >>> colormode(255)
+ >>> bgcolor("#800080")
+ >>> bgcolor()
+ (128.0, 0.0, 128.0)
>>> help(penup)
Help on function penup in module turtle:
penup()
- Pull the pen up -- no drawing when moving.
+ Lift the pen.
Aliases: penup | pu | up
- No argument
-
- Example:
- >>> penup()
+ The turtle does not draw when it moves.
These modified docstrings are created automatically together with the function
definitions that are derived from the methods at import time.
@@ -2571,17 +2602,16 @@ Screen and Turtle.
.. function:: write_docstringdict(filename="turtle_docstringdict")
- :param filename: a string, used as filename
+ :param filename: a string
- Create and write docstring-dictionary to a Python script with the given
- filename. This function has to be called explicitly (it is not used by the
- turtle graphics classes). The docstring dictionary will be written to the
- Python script :file:`{filename}.py`. It is intended to serve as a template
- for translation of the docstrings into different languages.
+ Write the docstring dictionary to a Python script. The dictionary is written
+ to the file :file:`{filename}.py`. It is intended to serve as a template for
+ translating the docstrings into different languages. This function has to
+ be called explicitly. It is not used by the turtle graphics classes.
If you (or your students) want to use :mod:`!turtle` with online help in your
native language, you have to translate the docstrings and save the resulting
-file as e.g. :file:`turtle_docstringdict_german.py`.
+file as, for example, :file:`turtle_docstringdict_german.py`.
If you have an appropriate entry in your :file:`turtle.cfg` file this
dictionary
will be read in at import time and will replace the original English
docstrings.
@@ -2598,11 +2628,11 @@ The built-in default configuration mimics the
appearance and behaviour of the
old turtle module in order to retain best possible compatibility with it.
If you want to use a different configuration which better reflects the features
-of this module or which better fits to your needs, e.g. for use in a classroom,
-you can prepare a configuration file ``turtle.cfg`` which will be read at
import
-time and modify the configuration according to its settings.
+of this module or which better fits to your needs, for example for use in a
+classroom, you can prepare a configuration file ``turtle.cfg`` which will be
+read at import time and modify the configuration according to its settings.
-The built in configuration would correspond to the following ``turtle.cfg``:
+The built-in configuration would correspond to the following ``turtle.cfg``:
.. code-block:: ini
@@ -2633,23 +2663,23 @@ Short explanation of selected entries:
method.
- Line 5 and 6 correspond to the arguments of the method
:func:`Screen.screensize <screensize>`.
-- *shape* can be any of the built-in shapes, e.g: arrow, turtle, etc. For more
- info try ``help(shape)``.
-- If you want to use no fill color (i.e. make the turtle transparent), you have
- to write ``fillcolor = ""`` (but all nonempty strings must not have quotes in
- the cfg file).
-- If you want to reflect the turtle its state, you have to use ``resizemode =
- auto``.
-- If you set e.g. ``language = italian`` the docstringdict
+- *shape* can be any of the built-in shapes, such as arrow or turtle. For more
+ information, see :func:`shape`.
+- If you want to use no fill color (that is, make the turtle transparent), you
+ have to write ``fillcolor = ""`` (but all nonempty strings must not have
+ quotes in the cfg file).
+- If you want the turtle's appearance to reflect its state, you have to set
+ ``resizemode = auto``.
+- If you set, for example, ``language = italian`` the docstringdict
:file:`turtle_docstringdict_italian.py` will be loaded at import time (if
- present on the import path, e.g. in the same directory as :mod:`!turtle`).
+ present on the import path, for example, in the same directory as
:mod:`!turtle`).
- The entries *exampleturtle* and *examplescreen* define the names of these
objects as they occur in the docstrings. The transformation of
method-docstrings to function-docstrings will delete these names from the
docstrings.
- *using_IDLE*: Set this to ``True`` if you regularly work with IDLE and its
``-n``
- switch ("no subprocess"). This will prevent :func:`exitonclick` to enter the
- mainloop.
+ switch ("no subprocess"). This will prevent :func:`exitonclick` from
+ entering the mainloop.
There can be a :file:`turtle.cfg` file in the directory where :mod:`!turtle` is
stored and an additional one in the current working directory. The latter will
@@ -2665,7 +2695,7 @@ not from within the demo-viewer).
Explanation
===========
-A turtle object draws on a screen object, and there a number of key classes in
+A turtle object draws on a screen object, and there are a number of key
classes in
the turtle object-oriented interface that can be used to create them and relate
them to each other.
@@ -2748,7 +2778,7 @@ The demo scripts are:
| ``fractalcurves`` | Hilbert & Koch curves | recursion
|
+------------------------+------------------------------+--------------------------------------+
| ``lindenmayer`` | ethnomathematics | L-System
|
-| | (indian kolams) |
|
+| | (Indian kolams) |
|
+------------------------+------------------------------+--------------------------------------+
| ``minimal_hanoi`` | Towers of Hanoi | Rectangular Turtles
|
| | | as Hanoi discs
|
@@ -2770,10 +2800,10 @@ The demo scripts are:
| ``planet_and_moon`` | simulation of | compound shapes,
|
| | gravitational system | :class:`Vec2D`
|
+------------------------+------------------------------+--------------------------------------+
-| ``rosette`` | a pattern from the wikipedia | :func:`clone`,
|
+| ``rosette`` | a pattern from the Wikipedia | :func:`clone`,
|
| | article on turtle graphics | :func:`undo`
|
+------------------------+------------------------------+--------------------------------------+
-| ``round_dance`` | dancing turtles rotating | compound shapes,
:func:`clone` |
+| ``round_dance`` | dancing turtles rotating | compound shapes,
:func:`clone`, |
| | pairwise in opposite | :func:`shapesize`,
:func:`tilt`, |
| | direction |
:func:`get_shapepoly`, :func:`update`|
+------------------------+------------------------------+--------------------------------------+
diff --git a/Lib/turtle.py b/Lib/turtle.py
index 9e310cee8086f2..849b9e14bb8d7b 100644
--- a/Lib/turtle.py
+++ b/Lib/turtle.py
@@ -1,4 +1,3 @@
-#
# turtle.py: a Tkinter based turtle graphics module for Python
# Version 1.1b - 4. 5. 2009
#
@@ -114,7 +113,7 @@ def config_dict(filename):
try:
key, value = line.split("=")
except ValueError:
- print("Bad line in config-file %s:\n%s" % (filename,line))
+ print(f"Bad line in config-file {filename}:\n{line}")
continue
key = key.strip()
value = value.strip()
@@ -225,7 +224,7 @@ def __repr__(self):
### May be replaced by an interface to some different graphics toolkit ###
##############################################################################
-## helper functions for Scrolled Canvas, to forward Canvas-methods
+## Helper functions for Scrolled Canvas, to forward Canvas-methods
## to ScrolledCanvas class
def __methodDict(cls, _dict):
@@ -270,11 +269,12 @@ def __forwardmethods(fromClass, toClass, toPart, exclude
= ()):
class ScrolledCanvas(TK.Frame):
- """Modeled after the scrolled canvas class from Grayons's Tkinter book.
+ """Modeled after the scrolled canvas class from Grayson's Tkinter book.
Used as the default canvas, which pops up automatically when
using turtle graphics functions or the Turtle class.
"""
+
def __init__(self, master, width=500, height=350,
canvwidth=600, canvheight=500):
TK.Frame.__init__(self, master, width=width, height=height)
@@ -366,6 +366,7 @@ def focus_force(self):
class _Root(TK.Tk):
"""Root class for Screen based on Tkinter."""
+
def __init__(self):
TK.Tk.__init__(self)
@@ -393,10 +394,10 @@ def win_height(self):
class TurtleScreenBase:
"""Provide the basic graphics functionality.
- Interface between Tkinter and turtle.py.
+ Interface between Tkinter and turtle.py.
- To port turtle.py to some different graphics toolkit
- a corresponding TurtleScreenBase class has to be implemented.
+ To port turtle.py to a different graphics toolkit,
+ a corresponding TurtleScreenBase class must be implemented.
"""
def _blankimage(self):
@@ -550,22 +551,19 @@ def _onclick(self, item, fun, num=1, add=None):
num, the number of the mouse-button defaults to 1
"""
if fun is None:
- self.cv.tag_unbind(item, "<Button-%s>" % num)
+ self.cv.tag_unbind(item, f"<Button-{num}>")
else:
def eventfun(event):
x, y = (self.cv.canvasx(event.x)/self.xscale,
-self.cv.canvasy(event.y)/self.yscale)
fun(x, y)
- self.cv.tag_bind(item, "<Button-%s>" % num, eventfun, add)
+ self.cv.tag_bind(item, f"<Button-{num}>", eventfun, add)
def _onrelease(self, item, fun, num=1, add=None):
"""Bind fun to mouse-button-release event on turtle.
fun must be a function with two arguments, the coordinates
of the point on the canvas where mouse button is released.
num, the number of the mouse-button defaults to 1
-
- If a turtle is clicked, first _onclick-event will be performed,
- then _onscreensclick-event.
"""
if fun is None:
self.cv.tag_unbind(item, f"<Button{num}-ButtonRelease>")
@@ -605,7 +603,7 @@ def _onscreenclick(self, fun, num=1, add=None):
num, the number of the mouse-button defaults to 1
If a turtle is clicked, first _onclick-event will be performed,
- then _onscreensclick-event.
+ then _onscreenclick-event.
"""
if fun is None:
self.cv.unbind(f"<Button-{num}>")
@@ -733,7 +731,7 @@ def _window_size(self):
return width, height
def mainloop(self):
- """Start the event loop by calling Tkinter's mainloop function.
+ """Start the event loop by calling Tkinter's mainloop method.
Must be the last statement in a turtle graphics program. Must not
be used if a script is run from within IDLE in -n mode (no
@@ -763,10 +761,10 @@ def numinput(self, title, prompt, default=None,
minval=None, maxval=None):
title is the title of the dialog window and prompt is a text
describing what numerical information to input. default is the
default value, minval and maxval are the minimum and maximum
- values for input. If these are given, the number entered must be
- between minval and maxval. If not, a hint is issued and the dialog
- remains open for correction. Return the number entered.
- If the dialog is canceled, return None.
+ values for input. If these are given and the number entered is not
+ between minval and maxval, a hint is issued and the dialog remains
+ open for correction. Return the number entered. If the dialog is
+ canceled, return None.
Arguments:
title -- a string
@@ -810,6 +808,7 @@ class Shape:
"compound" None, as a compound shape is built up using the
addcomponent method.
"""
+
def __init__(self, type_, data=None):
self._type = type_
if type_ == "polygon":
@@ -820,7 +819,7 @@ def __init__(self, type_, data=None):
elif type_ == "compound":
data = []
else:
- raise TurtleGraphicsError("There is no shape type %s" % type_)
+ raise TurtleGraphicsError(f"There is no shape type {type_!r}")
self._data = data
def addcomponent(self, poly, fill, outline=None):
@@ -842,8 +841,8 @@ def addcomponent(self, poly, fill, outline=None):
>>> # ... add more components and then use register_shape()
"""
if self._type != "compound":
- raise TurtleGraphicsError("Cannot add component to %s Shape"
- % self._type)
+ raise TurtleGraphicsError(f"Cannot add component to {self._type!r}
Shape")
+
if outline is None:
outline = fill
self._data.append([poly, fill, outline])
@@ -901,14 +900,14 @@ def __repr__(self):
return str(self.buffer) + " " + str(self.ptr)
-
class TurtleScreen(TurtleScreenBase):
- """Provides screen oriented methods like bgcolor etc.
+ """Provides the screen-oriented methods, such as bgcolor().
Only relies upon the methods of TurtleScreenBase and not upon
components of the underlying graphics toolkit, which is Tkinter
in this case.
"""
+
_RUNNING = True
def __init__(self, cv, mode=_CFG["mode"],
@@ -1151,7 +1150,7 @@ def colormode(self, cmode=None):
>>> turtle.pencolor(240, 160, 80)
Traceback (most recent call last):
...
- TurtleGraphicsError: bad color sequence: (240, 160, 80)
+ turtle.TurtleGraphicsError: bad color sequence: (240, 160, 80)
>>> screen.colormode()
1.0
>>> screen.colormode(255)
@@ -1310,7 +1309,10 @@ def _incrementudc(self):
self._updatecounter %= self._tracing
def update(self):
- """Perform a TurtleScreen update."""
+ """Perform a TurtleScreen update.
+
+ To be used when tracer() is turned off.
+ """
tracing = self._tracing
self._tracing = True
for t in self.turtles():
@@ -1365,7 +1367,7 @@ def onclick(self, fun, btn=1, add=None):
canvas. If fun is None, existing bindings are removed. btn is the
number of the mouse button and defaults to 1, the left mouse
button. If add is True, a new binding is added, otherwise it
- replaces a former binding. As a function, this method is only
+ replaces a previous binding. As a function, this method is only
available under the name onscreenclick. The function onclick is
derived from the Turtle method onclick.
@@ -1516,7 +1518,7 @@ def screensize(self, canvwidth=None, canvheight=None,
bg=None):
Arguments:
canvwidth -- a positive integer or None
canvheight -- a positive integer or None
- bg -- a colorstring or a color tuple or None
+ bg -- a colorstring or None
Example (for a TurtleScreen instance named screen):
>>> screen.screensize()
@@ -1571,11 +1573,13 @@ def save(self, filename, *, overwrite=False):
addshape = register_shape
onkeyrelease = onkey
+
class TNavigator:
"""The navigation part of RawTurtle.
Implements methods for turtle movement.
"""
+
START_ORIENTATION = {
"standard": Vec2D(1.0, 0.0),
"world" : Vec2D(1.0, 0.0),
@@ -1816,7 +1820,7 @@ def ycor(self):
"""Return the turtle's y coordinate.
Example (for a Turtle instance named turtle):
- >>> reset()
+ >>> turtle.home()
>>> turtle.left(60)
>>> turtle.forward(100)
>>> print(round(turtle.ycor(), 5))
@@ -2168,7 +2172,6 @@ def pensize(self, width=None):
return self._pensize
self.pen(pensize=width)
-
def penup(self):
"""Lift the pen.
@@ -2208,9 +2211,9 @@ def speed(self, speed=None):
"""Return or set the turtle's speed.
If speed is not given, return the current speed. Otherwise set the
- turtle's speed to an integer from 0 to 10. If speed is a number
- greater than 10 or smaller than 0.5, the speed is set to 0. You
- can also use these names instead of numbers:
+ turtle's speed to an integer from 0 to 10. A number above 0.5 and
+ below 10.5 is rounded to the nearest integer. Any other number sets
+ the speed to 0. You can also use these names instead of numbers:
"fastest": 0
"fast": 10
@@ -2617,7 +2620,7 @@ def __init__(self, canvas=None,
self.screen = TurtleScreen(canvas)
RawTurtle.screens.append(self.screen)
else:
- raise TurtleGraphicsError("bad canvas argument %s" % canvas)
+ raise TurtleGraphicsError(f"Bad canvas argument {canvas!r}")
screen = self.screen
TNavigator.__init__(self, screen.mode())
@@ -2684,8 +2687,8 @@ def undobufferentries(self):
"""Return the number of entries in the undo buffer.
Example (for a Turtle instance named turtle):
- >>> while undobufferentries():
- ... undo()
+ >>> while turtle.undobufferentries():
+ ... turtle.undo()
"""
if self.undobuffer is None:
return 0
@@ -2851,7 +2854,7 @@ def shape(self, name=None):
"""Set the turtle shape to the named shape.
If name is not given, return the name of the current shape. The
- shape must exist in the TurtleScreen's shape dictionary. Initially
+ shape must exist in the TurtleScreen's shape list. Initially
there are the following shapes: "arrow", "turtle", "circle",
"square", "triangle" and "classic". To add shapes, see the Screen
method register_shape().
@@ -2975,12 +2978,12 @@ def tiltangle(self, angle=None):
>>> turtle.tiltangle(45)
>>> turtle.tiltangle()
45.0
- >>> turtle.stamp()
+ >>> stamp_id = turtle.stamp()
>>> turtle.fd(50)
>>> turtle.tiltangle(-45)
>>> turtle.tiltangle()
315.0
- >>> turtle.stamp()
+ >>> stamp_id = turtle.stamp()
>>> turtle.fd(50)
"""
if angle is None:
@@ -3017,9 +3020,9 @@ def shapetransform(self, t11=None, t12=None, t21=None,
t22=None):
tilt angle of the turtle shape into four numbers: t11 and t12 form
its first row, t21 and t22 its second. If none of them are given,
return the current matrix as a tuple of four numbers. Otherwise
- set the given elements and update stretch factors, shear factor and
- tilt angle accordingly. t11 * t22 - t12 * t21 must not be zero,
- otherwise an error is raised.
+ set the given elements and update the stretch factors, shear
+ factor and tilt angle accordingly. t11 * t22 - t12 * t21 must not
+ be zero, otherwise an error is raised.
Arguments:
t11 -- a number or None
@@ -3070,8 +3073,8 @@ def get_shapepoly(self):
"""Return the points that form the outline of the current turtle shape
as a tuple of (x, y) coordinate pairs.
- This can be used to define a new shape or components of a compound
- shape.
+ These points can be used to define a new shape or parts of a
+ compound shape.
Example (for a Turtle instance named turtle):
>>> turtle.shape("square")
@@ -3361,7 +3364,7 @@ def _undogoto(self, entry):
self._update() #count=True)
def _rotate(self, angle):
- """Turns pen clockwise by angle."""
+ """Turn the turtle counterclockwise by angle."""
if self.undobuffer:
self.undobuffer.push(("rot", angle, self._degreesPerAU))
angle *= self._degreesPerAU
@@ -3653,7 +3656,7 @@ def onclick(self, fun, btn=1, add=None):
canvas. If fun is None, existing bindings are removed. btn is the
number of the mouse button and defaults to 1, the left mouse
button. If add is True, a new binding is added, otherwise it
- replaces a former binding.
+ replaces a previous binding.
Arguments:
fun -- a function with two arguments or None
@@ -3671,47 +3674,57 @@ def onclick(self, fun, btn=1, add=None):
self._update()
def onrelease(self, fun, btn=1, add=None):
- """Bind fun to mouse-button-release event on this turtle on canvas.
+ """Bind fun to mouse-button-release events on this turtle.
+
+ fun is called with the coordinates of the point on the canvas
+ where the mouse button is released. If fun is None, existing
+ bindings are removed. btn is the number of the mouse button and
+ defaults to 1, the left mouse button. If add is True, a new
+ binding is added, otherwise it replaces a previous binding.
Arguments:
- fun -- a function with two arguments, to which will be assigned
- the coordinates of the clicked point on the canvas.
- btn -- number of the mouse-button defaults to 1 (left mouse button).
+ fun -- a function with two arguments or None
+ btn -- an integer
+ add -- a boolean or None
Example (for a MyTurtle instance named joe):
- >>> class MyTurtle(Turtle):
- ... def glow(self,x,y):
- ... self.fillcolor("red")
- ... def unglow(self,x,y):
- ... self.fillcolor("")
- ...
- >>> joe = MyTurtle()
- >>> joe.onclick(joe.glow)
- >>> joe.onrelease(joe.unglow)
-
- Clicking on joe turns fillcolor red, unclicking turns it to
- transparent.
+ >>> class MyTurtle(Turtle):
+ ... def glow(self,x,y):
+ ... self.fillcolor("red")
+ ...
+ ... def unglow(self,x,y):
+ ... self.fillcolor("")
+ ...
+ >>> joe = MyTurtle()
+ >>> joe.onclick(joe.glow)
+ >>> joe.onrelease(joe.unglow)
+
+ Clicking on joe turns its fill color red, releasing the mouse button
+ turns it transparent again.
"""
self.screen._onrelease(self.turtle._item, fun, btn, add)
self._update()
def ondrag(self, fun, btn=1, add=None):
- """Bind fun to mouse-move event on this turtle on canvas.
+ """Bind fun to mouse-move events on this turtle.
- Arguments:
- fun -- a function with two arguments, to which will be assigned
- the coordinates of the clicked point on the canvas.
- btn -- number of the mouse-button defaults to 1 (left mouse button).
+ fun is called with the coordinates of the mouse pointer on the
+ canvas. If fun is None, existing bindings are removed. btn is the
+ number of the mouse button and defaults to 1, the left mouse
+ button. If add is True, a new binding is added, otherwise it
+ replaces a previous binding. Every sequence of mouse-move events on
+ a turtle is preceded by a mouse-click event on that turtle.
- Every sequence of mouse-move-events on a turtle is preceded by a
- mouse-click event on that turtle.
+ Arguments:
+ fun -- a function with two arguments or None
+ btn -- an integer
+ add -- a boolean or None
Example (for a Turtle instance named turtle):
- >>> turtle.ondrag(turtle.goto)
+ >>> turtle.ondrag(turtle.goto)
- Subsequently clicking and dragging a Turtle will move it
- across the screen thereby producing handdrawings (if pen is
- down).
+ Clicking and dragging the turtle then moves it across the screen,
+ drawing by hand if the pen is down.
"""
self.screen._ondrag(self.turtle._item, fun, btn, add)
@@ -3751,21 +3764,19 @@ def _undo(self, action, data):
self.undobuffer.pop()
def undo(self):
- """undo (repeatedly) the last turtle action.
-
- No argument.
+ """Undo the last turtle action.
- undo (repeatedly) the last turtle action.
- Number of available undo actions is determined by the size of
- the undobuffer.
+ Calling undo() repeatedly undoes one action at a time. The number
+ of actions that can be undone is set by the size of the undo
+ buffer, see setundobuffer().
Example (for a Turtle instance named turtle):
- >>> for i in range(4):
- ... turtle.fd(50); turtle.lt(80)
- ...
- >>> for i in range(8):
- ... turtle.undo()
- ...
+ >>> for i in range(4):
+ ... turtle.fd(50); turtle.lt(80)
+ ...
+ >>> for i in range(8):
+ ... turtle.undo()
+ ...
"""
if self.undobuffer is None:
return
@@ -3819,28 +3830,32 @@ def __init__(self):
def setup(self, width=_CFG["width"], height=_CFG["height"],
startx=_CFG["leftright"], starty=_CFG["topbottom"]):
- """ Set the size and position of the main window.
+ """Set the size and position of the main window.
- Arguments:
- width: as integer a size in pixels, as float a fraction of the screen.
- Default is 50% of screen.
- height: as integer the height in pixels, as float a fraction of the
- screen. Default is 75% of screen.
- startx: if positive, starting position in pixels from the left
- edge of the screen, if negative from the right edge
- Default, startx=None is to center window horizontally.
- starty: if positive, starting position in pixels from the top
- edge of the screen, if negative from the bottom edge
- Default, starty=None is to center window vertically.
+ width and height are the size of the window. As integers they are
+ sizes in pixels, as floats they are fractions of the screen, so
+ 0.5 is half the screen. The defaults are 50% of the screen width
+ and 75% of its height.
- Examples (for a Screen instance named screen):
- >>> screen.setup (width=200, height=200, startx=0, starty=0)
+ startx and starty are the position of the window. If positive,
+ they are the distance in pixels from the left and top edges of the
+ screen, if negative from the right and bottom edges. If None, the
+ window is centered in that direction.
- sets window to 200x200 pixels, in upper left of screen
+ The default values of all arguments are stored in the
+ configuration dictionary and can be changed with a turtle.cfg file.
- >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
+ Arguments:
+ width -- an integer or a float
+ height -- an integer or a float
+ startx -- an integer or None
+ starty -- an integer or None
- sets window to 75% of screen by 50% of screen and centers
+ Example (for a Screen instance named screen):
+ >>> screen.setup(width=200, height=200, startx=0, starty=0)
+ >>> # sets window to 200x200 pixels, in upper left of screen
+ >>> screen.setup(width=0.75, height=0.5)
+ >>> # sets window to 75% of screen by 50% of screen and centers
"""
if not hasattr(self._root, "set_geometry"):
return
@@ -3889,19 +3904,14 @@ def bye(self):
self._destroy()
def exitonclick(self):
- """Go into mainloop until the mouse is clicked.
-
- No arguments.
+ """Bind bye() to mouse clicks on the screen and start the event loop.
- Bind bye() method to mouseclick on TurtleScreen.
- If "using_IDLE" - value in configuration dictionary is False
- (default value), enter mainloop.
- If IDLE with -n switch (no subprocess) is used, this value should be
- set to True in turtle.cfg. In this case IDLE's mainloop
- is active also for the client script.
+ Clicking on the screen then closes the turtle graphics window. If
+ the configuration value using_IDLE is True, the event loop is not
+ started, see mainloop().
- This is a method of the Screen-class and not available for
- TurtleScreen instances.
+ This is a method of the Screen class. It is not available for
+ TurtleScreen objects.
"""
def exitGracefully(x, y):
"""Screen.bye() with two dummy-parameters"""
@@ -3937,16 +3947,15 @@ def __init__(self,
Pen = Turtle
def write_docstringdict(filename="turtle_docstringdict"):
- """Create and write docstring-dictionary to file.
+ """Write the docstring dictionary to a Python script.
- Optional argument:
- filename -- a string, used as filename
- default value is turtle_docstringdict
+ The dictionary is written to the file filename.py. It is intended to
+ serve as a template for translating the docstrings into different
+ languages. This function has to be called explicitly. It is not used
+ by the turtle graphics classes.
- Has to be called explicitly, (not used by the turtle-graphics classes)
- The docstring dictionary will be written to the Python script <filename>.py
- It is intended to serve as a template for translation of the docstrings
- into different languages.
+ Argument:
+ filename -- a string
"""
docsdict = {}
@@ -4000,10 +4009,10 @@ def read_docstrings(lang):
def getmethparlist(ob):
- """Get strings describing the arguments for the given object
+ """Get strings describing the arguments for the given object.
Returns a pair of strings representing function parameter lists
- including parenthesis. The first string is suitable for use in
+ including parentheses. The first string is suitable for use in
function definition and the second is suitable for use in function
call. The "self" parameter is not included.
"""
_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]