<turtle.Turtle object at 0x0187D810>
[<turtle.Turtle object at 0x0187D810>]
################################################################
### screen oriented methods recurring to methods of TurtleScreen
################################################################
def _delay(self, delay=None):
"""Set delay value which determines speed of turtle animation.
return self.screen.delay(delay)
def onclick(self, fun, btn=1, add=None):
"""Bind fun to mouse-click event on this turtle on canvas.
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).
add -- True or False. If True, new binding will be added, otherwise
it will replace a former binding.
Example for the anonymous turtle, i. e. the procedural way:
>>> onclick(turn) # Now clicking into the turtle will turn it.
>>> onclick(None) # event-binding will be removed
self.screen._onclick(self.turtle._item, fun, btn, add)
def onrelease(self, fun, btn=1, add=None):
"""Bind fun to mouse-button-release event on this turtle on canvas.
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).
Example (for a MyTurtle instance named joe):
>>> class MyTurtle(Turtle):
... self.fillcolor("red")
... def unglow(self,x,y):
>>> joe.onclick(joe.glow)
>>> joe.onrelease(joe.unglow)
Clicking on joe turns fillcolor red, unclicking turns it to
self.screen._onrelease(self.turtle._item, fun, btn, add)
def ondrag(self, fun, btn=1, add=None):
"""Bind fun to mouse-move event on this turtle on canvas.
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).
Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that turtle.
Example (for a Turtle instance named turtle):
>>> turtle.ondrag(turtle.goto)
Subsequently clicking and dragging a Turtle will move it
across the screen thereby producing handdrawings (if pen is
self.screen._ondrag(self.turtle._item, fun, btn, add)
def _undo(self, action, data):
"""Does the main part of the work for undo()
if self.undobuffer is None:
self._rotate(-angle*degPAU/self._degreesPerAU)
dummy = self.undobuffer.pop()
elif action in ["wri", "dot"]:
self.screen._delete(item)
self.screen._drawpoly(item, ((0, 0),(0, 0),(0, 0)),
elif action == "beginfill":
self._fillitem = self._fillpath = None
self.screen._delete(item)
"""undo (repeatedly) the last turtle action.
undo (repeatedly) the last turtle action.
Number of available undo actions is determined by the size of
Example (for a Turtle instance named turtle):
... turtle.fd(50); turtle.lt(80)
if self.undobuffer is None:
item = self.undobuffer.pop()
self._undo(item[0], item[1:])
### Screen - Singleton ########################
"""Return the singleton screen object.
If none exists at the moment, create a new one and return it,
else return the existing one."""
if Turtle._screen is None:
Turtle._screen = _Screen()
class _Screen(TurtleScreen):
# XXX there is no need for this code to be conditional,
# as there will be only a single _Screen instance, anyway
# XXX actually, the turtle demo is injecting root window,
# so perhaps the conditional creation of a root should be
# preserved (perhaps by passing it as an optional parameter)
if _Screen._root is None:
_Screen._root = self._root = _Root()
self._root.title(_Screen._title)
self._root.ondestroy(self._destroy)
if _Screen._canvas is None:
canvwidth = _CFG["canvwidth"]
canvheight = _CFG["canvheight"]
leftright = _CFG["leftright"]
topbottom = _CFG["topbottom"]
self._root.setupcanvas(width, height, canvwidth, canvheight)
_Screen._canvas = self._root._getcanvas()
TurtleScreen.__init__(self, _Screen._canvas)
self.setup(width, height, leftright, topbottom)
def setup(self, width=_CFG["width"], height=_CFG["height"],
startx=_CFG["leftright"], starty=_CFG["topbottom"]):
""" Set the size and position of the main window.
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.
Examples (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=.75, height=0.5, startx=None, starty=None)
sets window to 75% of screen by 50% of screen and centers
if not hasattr(self._root, "set_geometry"):
sw = self._root.win_width()
sh = self._root.win_height()
if isinstance(width, float) and 0 <= width <= 1:
startx = (sw - width) / 2
if isinstance(height, float) and 0 <= height <= 1:
starty = (sh - height) / 2
self._root.set_geometry(width, height, startx, starty)
def title(self, titlestring):
"""Set title of turtle-window
titlestring -- a string, to appear in the titlebar of the
This is a method of Screen-class. Not available for TurtleScreen-
Example (for a Screen instance named screen):
>>> screen.title("Welcome to the turtle-zoo!")
if _Screen._root is not None:
_Screen._root.title(titlestring)
_Screen._title = titlestring
if root is _Screen._root:
TurtleScreen._RUNNING = False
"""Shut the turtlegraphics window.
Example (for a TurtleScreen instance named screen):
"""Go into mainloop until the mouse is clicked.
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.
This is a method of the Screen-class and not available for
Example (for a Screen instance named screen):
def exitGracefully(x, y):
"""Screen.bye() with two dummy-parameters"""
self.onclick(exitGracefully)
"""RawTurtle auto-creating (scrolled) canvas.
When a Turtle object is created or a function derived from some
Turtle method is called a TurtleScreen object is automatically created.
undobuffersize=_CFG["undobuffersize"],
visible=_CFG["visible"]):
if Turtle._screen is None:
Turtle._screen = Screen()
RawTurtle.__init__(self, Turtle._screen,
undobuffersize=undobuffersize,
def write_docstringdict(filename="turtle_docstringdict"):
"""Create and write docstring-dictionary to file.
filename -- a string, used as filename
default value is turtle_docstringdict
Has to be called explicitly, (not used by the turtle-graphics classes)
The docstring dictionary will be written to the Python script <filname>.py
It is intended to serve as a template for translation of the docstrings
into different languages.
for methodname in _tg_screen_functions:
key = "_Screen."+methodname
docsdict[key] = eval(key).__doc__
for methodname in _tg_turtle_functions:
key = "Turtle."+methodname
docsdict[key] = eval(key).__doc__
with open("%s.py" % filename,"w") as f:
keys = sorted(x for x in docsdict
if x.split('.')[1] not in _alias_list)
f.write('docsdict = {\n\n')
f.write('%s :\n' % repr(key))
f.write(' """%s\n""",\n\n' % docsdict[key])
f.write('%s :\n' % repr(key))
f.write(' """%s\n"""\n\n' % docsdict[key])
def read_docstrings(lang):
"""Read in docstrings from lang-specific docstring dictionary.
Transfer docstrings, translated to lang, from a dictionary-file
to the methods of classes Screen and Turtle and - in revised form -
to the corresponding functions.
modname = "turtle_docstringdict_%(language)s" % {'language':lang.lower()}
module = __import__(modname)
docsdict = module.docsdict
# eval(key).im_func.__doc__ = docsdict[key]
eval(key).__doc__ = docsdict[key]
print("Bad docstring-entry: %s" % key)
_LANGUAGE = _CFG["language"]
if _LANGUAGE != "english":
read_docstrings(_LANGUAGE)
print("Cannot find docsdict for", _LANGUAGE)
print ("Unknown Error when trying to import %s-docstring-dictionary" %
"""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
function definition and the second is suitable for use in function
call. The "self" parameter is not included.
# bit of a hack for methods - turn it into a function
# but we drop the "self" param.
# Try and build one for Python defined functions
args, varargs, varkw = inspect.getargs(ob.__code__)
defaults = ob.__defaults__ or []
defaults = ["=%r" % (value,) for value in defaults]
defaults = [""] * (len(realArgs)-len(defaults)) + defaults
items1 = [arg + dflt for arg, dflt in zip(realArgs, defaults)]
items1.append("*" + varargs)
items2.append("*" + varargs)
items1.append("**" + varkw)
items2.append("**" + varkw)
defText = ", ".join(items1)
defText = "(%s)" % defText
callText = ", ".join(items2)
callText = "(%s)" % callText
def _turtle_docrevise(docstr):
"""To reduce docstrings from RawTurtle class for functions
turtlename = _CFG["exampleturtle"]
newdocstr = docstr.replace("%s." % turtlename,"")
parexp = re.compile(r' \(.+ %s\):' % turtlename)
newdocstr = parexp.sub(":", newdocstr)
def _screen_docrevise(docstr):
"""To reduce docstrings from TurtleScreen class for functions
screenname = _CFG["examplescreen"]
newdocstr = docstr.replace("%s." % screenname,"")
parexp = re.compile(r' \(.+ %s\):' % screenname)
newdocstr = parexp.sub(":", newdocstr)
## The following mechanism makes all methods of RawTurtle and Turtle available
## as functions. So we can enhance, change, add, delete methods to these
## classes and do not need to change anything here.
if not TurtleScreen._RUNNING:
TurtleScreen._RUNNING = True
return {obj}.{name}{argslist}
if not TurtleScreen._RUNNING:
TurtleScreen._RUNNING = True
def _make_global_funcs(functions, cls, obj, init, docrevise):
for methodname in functions:
method = getattr(cls, methodname)
pl1, pl2 = getmethparlist(method)
print(">>>>>>", pl1, pl2)
defstr = __func_body.format(obj=obj, init=init, name=methodname,
paramslist=pl1, argslist=pl2)
globals()[methodname].__doc__ = docrevise(method.__doc__)
_make_global_funcs(_tg_screen_functions, _Screen,
'Turtle._screen', 'Screen()', _screen_docrevise)
_make_global_funcs(_tg_turtle_functions, Turtle,
'Turtle._pen', 'Turtle()', _turtle_docrevise)
if __name__ == "__main__":
"""Demo of old turtle.py - module"""
# draw 3 squares; the last filled