-7 Removals
+241 Additions
##
# turtle.py: a Tkinter based turtle graphics module for Python# turtle.py: a Tkinter based turtle graphics module for Python
# Version 1.1b - 4. 5. 2009# Version 1.1b - 4. 5. 2009
##
# Copyright (C) 2006 - 2010 Gregor Lingl# Copyright (C) 2006 - 2010 Gregor Lingl
# email: glingl@aon.at# email: glingl@aon.at
##
# This software is provided 'as-is', without any express or implied# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.# arising from the use of this software.
##
# Permission is granted to anyone to use this software for any purpose,# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:# freely, subject to the following restrictions:
##
# 1. The origin of this software must not be misrepresented; you must not# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.# 3. This notice may not be removed or altered from any source distribution.
""""""
Turtle graphics is a popular way for introducing programming toTurtle graphics is a popular way for introducing programming to
kids. It was part of the original Logo programming language developedkids. It was part of the original Logo programming language developed
by Wally Feurzig and Seymour Papert in 1966.by Wally Feurzig and Seymour Papert in 1966.
Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give itImagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it
the command turtle.forward(15), and it moves (on-screen!) 15 pixels inthe command turtle.forward(15), and it moves (on-screen!) 15 pixels in
the direction it is facing, drawing a line as it moves. Give it thethe direction it is facing, drawing a line as it moves. Give it the
command turtle.right(25), and it rotates in-place 25 degrees clockwise.command turtle.right(25), and it rotates in-place 25 degrees clockwise.
By combining together these and similar commands, intricate shapes andBy combining together these and similar commands, intricate shapes and
pictures can easily be drawn.pictures can easily be drawn.
----- turtle.py----- turtle.py
This module is an extended reimplementation of turtle.py from theThis module is an extended reimplementation of turtle.py from the
Python standard distribution up to Python 2.5. (See: http://www.python.org)Python standard distribution up to Python 2.5. (See: http://www.python.org)
It tries to keep the merits of turtle.py and to be (nearly) 100%It tries to keep the merits of turtle.py and to be (nearly) 100%
compatible with it. This means in the first place to enable thecompatible with it. This means in the first place to enable the
learning programmer to use all the commands, classes and methodslearning programmer to use all the commands, classes and methods
interactively when using the module from within IDLE run withinteractively when using the module from within IDLE run with
the -n switch.the -n switch.
Roughly it has the following features added:Roughly it has the following features added:
- Better animation of the turtle movements, especially of turning the- Better animation of the turtle movements, especially of turning the
turtle. So the turtles can more easily be used as a visual feedback turtle. So the turtles can more easily be used as a visual feedback
instrument by the (beginning) programmer. instrument by the (beginning) programmer.
- Different turtle shapes, gif-images as turtle shapes, user defined- Different turtle shapes, gif-images as turtle shapes, user defined
and user controllable turtle shapes, among them compound and user controllable turtle shapes, among them compound
(multicolored) shapes. Turtle shapes can be stretched and tilted, which (multicolored) shapes. Turtle shapes can be stretched and tilted, which
makes turtles very versatile geometrical objects. makes turtles very versatile geometrical objects.
- Fine control over turtle movement and screen updates via delay(),- Fine control over turtle movement and screen updates via delay(),
and enhanced tracer() and speed() methods. and enhanced tracer() and speed() methods.
- Aliases for the most commonly used commands, like fd for forward etc.,- Aliases for the most commonly used commands, like fd for forward etc.,
following the early Logo traditions. This reduces the boring work of following the early Logo traditions. This reduces the boring work of
typing long sequences of commands, which often occur in a natural way typing long sequences of commands, which often occur in a natural way
when kids try to program fancy pictures on their first encounter with when kids try to program fancy pictures on their first encounter with
turtle graphics. turtle graphics.
- Turtles now have an undo()-method with configurable undo-buffer.- Turtles now have an undo()-method with configurable undo-buffer.
- Some simple commands/methods for creating event driven programs- Some simple commands/methods for creating event driven programs
(mouse-, key-, timer-events). Especially useful for programming games. (mouse-, key-, timer-events). Especially useful for programming games.
- A scrollable Canvas class. The default scrollable Canvas can be- A scrollable Canvas class. The default scrollable Canvas can be
extended interactively as needed while playing around with the turtle(s). extended interactively as needed while playing around with the turtle(s).
- A TurtleScreen class with methods controlling background color or- A TurtleScreen class with methods controlling background color or
background image, window and canvas size and other properties of the background image, window and canvas size and other properties of the
TurtleScreen. TurtleScreen.
- There is a method, setworldcoordinates(), to install a user defined- There is a method, setworldcoordinates(), to install a user defined
coordinate-system for the TurtleScreen. coordinate-system for the TurtleScreen.
- The implementation uses a 2-vector class named Vec2D, derived from tuple.- The implementation uses a 2-vector class named Vec2D, derived from tuple.
This class is public, so it can be imported by the application programmer, This class is public, so it can be imported by the application programmer,
which makes certain types of computations very natural and compact. which makes certain types of computations very natural and compact.
- Appearance of the TurtleScreen and the Turtles at startup/import can be- Appearance of the TurtleScreen and the Turtles at startup/import can be
configured by means of a turtle.cfg configuration file. configured by means of a turtle.cfg configuration file.
The default configuration mimics the appearance of the old turtle module. The default configuration mimics the appearance of the old turtle module.
- If configured appropriately the module reads in docstrings from a docstring- If configured appropriately the module reads in docstrings from a docstring
dictionary in some different language, supplied separately and replaces dictionary in some different language, supplied separately and replaces
the English ones by those read in. There is a utility function the English ones by those read in. There is a utility function
write_docstringdict() to write a dictionary with the original (English) write_docstringdict() to write a dictionary with the original (English)
docstrings to disc, so it can serve as a template for translations. docstrings to disc, so it can serve as a template for translations.
Behind the scenes there are some features included with possibleBehind the scenes there are some features included with possible
extensions in mind. These will be commented and documented elsewhere.extensions in mind. These will be commented and documented elsewhere.
""""""
_ver = "turtle 1.1b- - for Python 3.1 - 4. 5. 2009"_ver = "turtle 1.1b- - for Python 3.1 - 4. 5. 2009"
# print(_ver)# print(_ver)
import tkinter as TKimport sys
if sys.version_info[0] == 2:
import Tkinter as TK
else:
import tkinter as TK
from tkinter import simpledialog
import typesimport types
import mathimport math
import timeimport time
import inspectimport inspect
import sys
from os.path import isfile, split, joinfrom os.path import isfile, split, join
from copy import deepcopyfrom copy import deepcopy
from tkinter import simpledialog
_SPANISH = {'TurtleScreen': 'PantallaTortuga',
'RawTurtle': 'TortugaBruta',
'RawPen': 'LapizBruto',
'Turtle': 'Tortuga',
'Pen': 'Lapiz',
'forward': 'adelante',
'back': 'atras',
'right': 'derecho',
'left': 'izquierda',
'goto': 'ir_a',
'setx': 'fijar_x',
'sety': 'fijar_y',
'setheading': 'fijar_direccion',
'home': 'origen',
'circle': 'circulo',
'dot': 'punto',
'stamp': 'sello',
'clearstamp': 'borrar_sello',
'clearstamps': 'borrar_sellos',
'undo': 'deshacer',
'speed': 'velocidad',
'position': 'posicion',
'towards': 'hacia',
'xcor': 'posicion_x',
'ycor': 'posicion_y',
'heading': 'direccion',
'distance': 'distancia',
'degrees': 'grados',
'radians': 'radianes',
'pendown': 'bajar_lapiz',
'penup': 'subir_lapiz',
'pensize': 'tamano_lapiz',
'pen': 'lapiz',
'isdown': 'esta_presionada',
'color': 'color',
'pencolor': 'color_de_lapiz',
'fillcolor': 'color_de_relleno',
'reset': 'reiniciar',
'clear': 'borrar',
'write': 'escribir',
'showturtle': 'mostrar',
'hideturtle': 'esconder',
'isvisible': 'esta_visible',
'shape': 'figura',
'resizemode': 'modo_cambio_tamano',
'shapesize': 'tamano_de_figura',
'shearfactor': 'factor_de_inclinacion',
'settiltangle': 'fijar_angulo_rotacion',
'tiltangle': 'angulo_de_rotacion',
'tilt': 'rotar',
'shapetransform': 'transformar_figura',
'get_shapepoly': 'obtener_poligono',
'onclick': 'al_hacer_clic',
'onrelease': 'al_liberar',
'ondrag': 'al_arrastrar',
'begin_poly': 'comienzar_poligono',
'end_poly': 'terminar_poligono',
'get_poly': 'obtener_poligono',
'filling': 'relleno',
'begin_fill': 'comienzar_relleno',
'end_fill': 'cterminar_relleno',
'clone': 'clonar',
'getturtle': 'obtener_tortuga',
'getpen': 'obtener_lapiz',
'getscreen': 'obtener_pantalla',
'setundobuffer': 'establecer_bufer_deshacer',
'undobufferentries': 'tamano_bufer_deshacer',
'bgcolor': 'color_fondo',
'bgpic': 'imagen_fondo',
'clear': 'borrar',
'reset': 'reiniciar',
'screensize': 'tamano_de_pantalla',
'setworldcoordinates': 'fijar_coordenadas_mundo',
'delay': 'retraso',
'tracer': 'animacion',
'update': 'redibujar',
'listen': 'escuchar',
'onkey': 'al_soltar_la_tecla',
'onkeypress': 'al_pulsar_la_tecla',
'ontimer': 'temporizador',
'mainloop': 'bucle_principal',
'done': 'hecho',
'mode': 'modo',
'colormode': 'modo_de_color',
'getcanvas': 'obtener_el_lienzo',
'getshapes': 'conseguir_figuras',
'register_shape': 'registrar_figura',
'turtles': 'tortugas',
'window_height': 'altura_de_ventana',
'window_width': 'ancho_de_ventana',
'textinput': 'entrada_texto',
'numinput': 'entrada_numero',
'bye': 'adios',
'exitonclick': 'salida_en_clic',
'setup': 'configurar',
'title': 'titulo',
}
_SPANISH_SETTING_WORDS = {'negro': 'black',
'azul': 'blue',
'marron': 'brown',
'naranja': 'orange',
'gris': 'gray',
'verde': 'green',
'morado': 'purple',
'rosa': 'pink',
'amarillo': 'yellow',
'blanco': 'white',
'rojo': 'red',
'auto': 'auto',
'usuario': 'user',
'sin_cambio_de_tamano': 'noresize',
'derecho': 'right',
'izquierda': 'left',
'centro': 'center',
'tortuga': 'turtle',
'cuadrado': 'square',
'triangulo': 'triangle',
'clasico': 'classic',
'flecha': 'arrow',
'nada': 'blank',
'circulo': 'circle',
'se_muestra': 'shown',
'bajar_lapiz': 'pendown',
'color_de_lapiz': 'pencolor',
'color_de_relleno': 'fillcolor',
'tamano_lapiz': 'pensize',
'velocidad': 'speed',
'modo_cambio_tamano': 'resizemode',
'factor_inclinacion': 'stretchfactor',
'ancho_contorno': 'outline',
'rotar': 'tilt'
}
_tg_classes = ['ScrolledCanvas', 'TurtleScreen', 'Screen',_tg_classes = ['ScrolledCanvas', 'TurtleScreen', 'Screen',
'RawTurtle', 'Turtle', 'RawPen', 'Pen', 'Shape', 'Vec2D'] 'RawTurtle', 'Turtle', 'RawPen', 'Pen', 'Shape', 'Vec2D']
_tg_screen_functions = ['addshape', 'bgcolor', 'bgpic', 'bye',_tg_screen_functions = ['addshape', 'bgcolor', 'bgpic', 'bye',
'clearscreen', 'colormode', 'delay', 'exitonclick', 'getcanvas', 'clearscreen', 'colormode', 'delay', 'exitonclick', 'getcanvas',
'getshapes', 'listen', 'mainloop', 'mode', 'numinput', 'getshapes', 'listen', 'mainloop', 'mode', 'numinput',
'onkey', 'onkeypress', 'onkeyrelease', 'onscreenclick', 'ontimer', 'onkey', 'onkeypress', 'onkeyrelease', 'onscreenclick', 'ontimer',
'register_shape', 'resetscreen', 'screensize', 'setup', 'register_shape', 'resetscreen', 'screensize', 'setup',
'setworldcoordinates', 'textinput', 'title', 'tracer', 'turtles', 'update', 'setworldcoordinates', 'textinput', 'title', 'tracer', 'turtles', 'update',
'window_height', 'window_width'] 'window_height', 'window_width']
_tg_turtle_functions = ['back', 'backward', 'begin_fill', 'begin_poly', 'bk',_tg_turtle_functions = ['back', 'backward', 'begin_fill', 'begin_poly', 'bk',
'circle', 'clear', 'clearstamp', 'clearstamps', 'clone', 'color', 'circle', 'clear', 'clearstamp', 'clearstamps', 'clone', 'color',
'degrees', 'distance', 'dot', 'down', 'end_fill', 'end_poly', 'fd', 'degrees', 'distance', 'dot', 'down', 'end_fill', 'end_poly', 'fd',
'fillcolor', 'filling', 'forward', 'get_poly', 'getpen', 'getscreen', 'get_shapepoly', 'fillcolor', 'filling', 'forward', 'get_poly', 'getpen', 'getscreen', 'get_shapepoly',
'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'isdown', 'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'isdown',
'isvisible', 'left', 'lt', 'onclick', 'ondrag', 'onrelease', 'pd', 'isvisible', 'left', 'lt', 'onclick', 'ondrag', 'onrelease', 'pd',
'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position', 'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position',
'pu', 'radians', 'right', 'reset', 'resizemode', 'rt', 'pu', 'radians', 'right', 'reset', 'resizemode', 'rt',
'seth', 'setheading', 'setpos', 'setposition', 'settiltangle', 'seth', 'setheading', 'setpos', 'setposition', 'settiltangle',
'setundobuffer', 'setx', 'sety', 'shape', 'shapesize', 'shapetransform', 'shearfactor', 'showturtle', 'setundobuffer', 'setx', 'sety', 'shape', 'shapesize', 'shapetransform', 'shearfactor', 'showturtle',
'speed', 'st', 'stamp', 'tilt', 'tiltangle', 'towards', 'speed', 'st', 'stamp', 'tilt', 'tiltangle', 'towards',
'turtlesize', 'undo', 'undobufferentries', 'up', 'width', 'turtlesize', 'undo', 'undobufferentries', 'up', 'width',
'write', 'xcor', 'ycor'] 'write', 'xcor', 'ycor']
_tg_utilities = ['write_docstringdict', 'done']_tg_utilities = ['write_docstringdict', 'done']
__all__ = (_tg_classes + _tg_screen_functions + _tg_turtle_functions +__all__ = (_tg_classes + _tg_screen_functions + _tg_turtle_functions +
_tg_utilities + ['Terminator']) # + _math_functions) _tg_utilities + ['Terminator'] + list(_SPANISH.values())) # + _math_functions)
_alias_list = ['addshape', 'backward', 'bk', 'fd', 'ht', 'lt', 'pd', 'pos',_alias_list = ['addshape', 'backward', 'bk', 'fd', 'ht', 'lt', 'pd', 'pos',
'pu', 'rt', 'seth', 'setpos', 'setposition', 'st', 'pu', 'rt', 'seth', 'setpos', 'setposition', 'st',
'turtlesize', 'up', 'width'] 'turtlesize', 'up', 'width']
_CFG = {"width" : 0.5, # Screen_CFG = {"width" : 0.5, # Screen
"height" : 0.75, "height" : 0.75,
"canvwidth" : 400, "canvwidth" : 400,
"canvheight": 300, "canvheight": 300,
"leftright": None, "leftright": None,
"topbottom": None, "topbottom": None,
"mode": "standard", # TurtleScreen "mode": "standard", # TurtleScreen
"colormode": 1.0, "colormode": 1.0,
"delay": 10, "delay": 10,
"undobuffersize": 1000, # RawTurtle "undobuffersize": 1000, # RawTurtle
"shape": "classic", "shape": "classic",
"pencolor" : "black", "pencolor" : "black",
"fillcolor" : "black", "fillcolor" : "black",
"resizemode" : "noresize", "resizemode" : "noresize",
"visible" : True, "visible" : True,
"language": "english", # docstrings "language": "english", # docstrings
"exampleturtle": "turtle", "exampleturtle": "turtle",
"examplescreen": "screen", "examplescreen": "screen",
"title": "Python Turtle Graphics", "title": "Python Turtle Graphics",
"using_IDLE": False "using_IDLE": False
} }
def config_dict(filename):def config_dict(filename):
"""Convert content of config-file into dictionary.""" """Convert content of config-file into dictionary."""
with open(filename, "r") as f: with open(filename, "r") as f:
cfglines = f.readlines() cfglines = f.readlines()
cfgdict = {} cfgdict = {}
for line in cfglines: for line in cfglines:
line = line.strip() line = line.strip()
if not line or line.startswith("#"): if not line or line.startswith("#"):
continue continue
try: try:
key, value = line.split("=") key, value = line.split("=")
except: except:
print("Bad line in config-file %s:\n%s" % (filename,line)) print("Bad line in config-file %s:\n%s" % (filename,line))
continue continue
key = key.strip() key = key.strip()
value = value.strip() value = value.strip()
if value in ["True", "False", "None", "''", '""']: if value in ["True", "False", "None", "''", '""']:
value = eval(value) value = eval(value)
else: else:
try: try:
if "." in value: if "." in value:
value = float(value) value = float(value)
else: else:
value = int(value) value = int(value)
except: except:
pass # value need not be converted pass # value need not be converted
cfgdict[key] = value cfgdict[key] = value
return cfgdict return cfgdict
def readconfig(cfgdict):def readconfig(cfgdict):
"""Read config-files, change configuration-dict accordingly. """Read config-files, change configuration-dict accordingly.
If there is a turtle.cfg file in the current working directory, If there is a turtle.cfg file in the current working directory,
read it from there. If this contains an importconfig-value, read it from there. If this contains an importconfig-value,
say 'myway', construct filename turtle_mayway.cfg else use say 'myway', construct filename turtle_mayway.cfg else use
turtle.cfg and read it from the import-directory, where turtle.cfg and read it from the import-directory, where
turtle.py is located. turtle.py is located.
Update configuration dictionary first according to config-file, Update configuration dictionary first according to config-file,
in the import directory, then according to config-file in the in the import directory, then according to config-file in the
current working directory. current working directory.
If no config-file is found, the default configuration is used. If no config-file is found, the default configuration is used.
""" """
default_cfg = "turtle.cfg" default_cfg = "turtle.cfg"
cfgdict1 = {} cfgdict1 = {}
cfgdict2 = {} cfgdict2 = {}
if isfile(default_cfg): if isfile(default_cfg):
cfgdict1 = config_dict(default_cfg) cfgdict1 = config_dict(default_cfg)
if "importconfig" in cfgdict1: if "importconfig" in cfgdict1:
default_cfg = "turtle_%s.cfg" % cfgdict1["importconfig"] default_cfg = "turtle_%s.cfg" % cfgdict1["importconfig"]
try: try:
head, tail = split(__file__) head, tail = split(__file__)
cfg_file2 = join(head, default_cfg) cfg_file2 = join(head, default_cfg)
except: except:
cfg_file2 = "" cfg_file2 = ""
if isfile(cfg_file2): if isfile(cfg_file2):
cfgdict2 = config_dict(cfg_file2) cfgdict2 = config_dict(cfg_file2)
_CFG.update(cfgdict2) _CFG.update(cfgdict2)
_CFG.update(cfgdict1) _CFG.update(cfgdict1)
try:try:
readconfig(_CFG) readconfig(_CFG)
except:except:
print ("No configfile read, reason unknown") print ("No configfile read, reason unknown")
class Vec2D(tuple):class Vec2D(tuple):
"""A 2 dimensional vector class, used as a helper class """A 2 dimensional vector class, used as a helper class
for implementing turtle graphics. for implementing turtle graphics.
May be useful for turtle graphics programs also. May be useful for turtle graphics programs also.
Derived from tuple, so a vector is a tuple! Derived from tuple, so a vector is a tuple!
Provides (for a, b vectors, k number): Provides (for a, b vectors, k number):
a+b vector addition a+b vector addition
a-b vector subtraction a-b vector subtraction
a*b inner product a*b inner product
k*a and a*k multiplication with scalar k*a and a*k multiplication with scalar
|a| absolute value of a |a| absolute value of a
a.rotate(angle) rotation a.rotate(angle) rotation
""" """
def __new__(cls, x, y): def __new__(cls, x, y):
return tuple.__new__(cls, (x, y)) return tuple.__new__(cls, (x, y))
def __add__(self, other): def __add__(self, other):
return Vec2D(self[0]+other[0], self[1]+other[1]) return Vec2D(self[0]+other[0], self[1]+other[1])
def __mul__(self, other): def __mul__(self, other):
if isinstance(other, Vec2D): if isinstance(other, Vec2D):
return self[0]*other[0]+self[1]*other[1] return self[0]*other[0]+self[1]*other[1]
return Vec2D(self[0]*other, self[1]*other) return Vec2D(self[0]*other, self[1]*other)
def __rmul__(self, other): def __rmul__(self, other):
if isinstance(other, int) or isinstance(other, float): if isinstance(other, int) or isinstance(other, float):
return Vec2D(self[0]*other, self[1]*other) return Vec2D(self[0]*other, self[1]*other)
def __sub__(self, other): def __sub__(self, other):
return Vec2D(self[0]-other[0], self[1]-other[1]) return Vec2D(self[0]-other[0], self[1]-other[1])
def __neg__(self): def __neg__(self):
return Vec2D(-self[0], -self[1]) return Vec2D(-self[0], -self[1])
def __abs__(self): def __abs__(self):
return (self[0]**2 + self[1]**2)**0.5 return (self[0]**2 + self[1]**2)**0.5
def rotate(self, angle): def rotate(self, angle):
"""rotate self counterclockwise by angle """rotate self counterclockwise by angle
""" """
perp = Vec2D(-self[1], self[0]) perp = Vec2D(-self[1], self[0])
angle = angle * math.pi / 180.0 angle = angle * math.pi / 180.0
c, s = math.cos(angle), math.sin(angle) c, s = math.cos(angle), math.sin(angle)
return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s) return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s)
def __getnewargs__(self): def __getnewargs__(self):
return (self[0], self[1]) return (self[0], self[1])
def __repr__(self): def __repr__(self):
return "(%.2f,%.2f)" % self return "(%.2f,%.2f)" % self
############################################################################################################################################################
### From here up to line : Tkinter - Interface for turtle.py ###### From here up to line : Tkinter - Interface for turtle.py ###
### May be replaced by an interface to some different graphics toolkit ###### 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## to ScrolledCanvas class
def __methodDict(cls, _dict):def __methodDict(cls, _dict):
"""helper function for Scrolled Canvas""" """helper function for Scrolled Canvas"""
baseList = list(cls.__bases__) baseList = list(cls.__bases__)
baseList.reverse() baseList.reverse()
for _super in baseList: for _super in baseList:
__methodDict(_super, _dict) __methodDict(_super, _dict)
for key, value in cls.__dict__.items(): for key, value in cls.__dict__.items():
if type(value) == types.FunctionType: if type(value) == types.FunctionType:
_dict[key] = value _dict[key] = value
def __methods(cls):def __methods(cls):
"""helper function for Scrolled Canvas""" """helper function for Scrolled Canvas"""
_dict = {} _dict = {}
__methodDict(cls, _dict) __methodDict(cls, _dict)
return _dict.keys() return _dict.keys()
__stringBody = (__stringBody = (
'def %(method)s(self, *args, **kw): return ' + 'def %(method)s(self, *args, **kw): return ' +
'self.%(attribute)s.%(method)s(*args, **kw)') 'self.%(attribute)s.%(method)s(*args, **kw)')
def __forwardmethods(fromClass, toClass, toPart, exclude = ()):def __forwardmethods(fromClass, toClass, toPart, exclude = ()):
### MANY CHANGES ### ### MANY CHANGES ###
_dict_1 = {} _dict_1 = {}
__methodDict(toClass, _dict_1) __methodDict(toClass, _dict_1)
_dict = {} _dict = {}
mfc = __methods(fromClass) mfc = __methods(fromClass)
for ex in _dict_1.keys(): for ex in _dict_1.keys():
if ex[:1] == '_' or ex[-1:] == '_' or ex in exclude or ex in mfc: if ex[:1] == '_' or ex[-1:] == '_' or ex in exclude or ex in mfc:
pass pass
else: else:
_dict[ex] = _dict_1[ex] _dict[ex] = _dict_1[ex]
for method, func in _dict.items(): for method, func in _dict.items():
d = {'method': method, 'func': func} d = {'method': method, 'func': func}
if isinstance(toPart, str): if isinstance(toPart, str):
execString = \ execString = \
__stringBody % {'method' : method, 'attribute' : toPart} __stringBody % {'method' : method, 'attribute' : toPart}
exec(execString, d) exec(execString, d)
setattr(fromClass, method, d[method]) ### NEWU! setattr(fromClass, method, d[method]) ### NEWU!
class ScrolledCanvas(TK.Frame):class ScrolledCanvas(TK.Frame):
"""Modeled after the scrolled canvas class from Grayons's Tkinter book. """Modeled after the scrolled canvas class from Grayons's Tkinter book.
Used as the default canvas, which pops up automatically when Used as the default canvas, which pops up automatically when
using turtle graphics functions or the Turtle class. using turtle graphics functions or the Turtle class.
""" """
def __init__(self, master, width=500, height=350, def __init__(self, master, width=500, height=350,
canvwidth=600, canvheight=500): canvwidth=600, canvheight=500):
TK.Frame.__init__(self, master, width=width, height=height) TK.Frame.__init__(self, master, width=width, height=height)
self._rootwindow = self.winfo_toplevel() self._rootwindow = self.winfo_toplevel()
self.width, self.height = width, height self.width, self.height = width, height
self.canvwidth, self.canvheight = canvwidth, canvheight self.canvwidth, self.canvheight = canvwidth, canvheight
self.bg = "white" self.bg = "white"
self._canvas = TK.Canvas(master, width=width, height=height, self._canvas = TK.Canvas(master, width=width, height=height,
bg=self.bg, relief=TK.SUNKEN, borderwidth=2) bg=self.bg, relief=TK.SUNKEN, borderwidth=2)
self.hscroll = TK.Scrollbar(master, command=self._canvas.xview, self.hscroll = TK.Scrollbar(master, command=self._canvas.xview,
orient=TK.HORIZONTAL) orient=TK.HORIZONTAL)
self.vscroll = TK.Scrollbar(master, command=self._canvas.yview) self.vscroll = TK.Scrollbar(master, command=self._canvas.yview)
self._canvas.configure(xscrollcommand=self.hscroll.set, self._canvas.configure(xscrollcommand=self.hscroll.set,
yscrollcommand=self.vscroll.set) yscrollcommand=self.vscroll.set)
self.rowconfigure(0, weight=1, minsize=0) self.rowconfigure(0, weight=1, minsize=0)
self.columnconfigure(0, weight=1, minsize=0) self.columnconfigure(0, weight=1, minsize=0)
self._canvas.grid(padx=1, in_ = self, pady=1, row=0, self._canvas.grid(padx=1, in_ = self, pady=1, row=0,
column=0, rowspan=1, columnspan=1, sticky='news') column=0, rowspan=1, columnspan=1, sticky='news')
self.vscroll.grid(padx=1, in_ = self, pady=1, row=0, self.vscroll.grid(padx=1, in_ = self, pady=1, row=0,
column=1, rowspan=1, columnspan=1, sticky='news') column=1, rowspan=1, columnspan=1, sticky='news')
self.hscroll.grid(padx=1, in_ = self, pady=1, row=1, self.hscroll.grid(padx=1, in_ = self, pady=1, row=1,
column=0, rowspan=1, columnspan=1, sticky='news') column=0, rowspan=1, columnspan=1, sticky='news')
self.reset() self.reset()
self._rootwindow.bind('<Configure>', self.onResize) self._rootwindow.bind('<Configure>', self.onResize)
def reset(self, canvwidth=None, canvheight=None, bg = None): def reset(self, canvwidth=None, canvheight=None, bg = None):
"""Adjust canvas and scrollbars according to given canvas size.""" """Adjust canvas and scrollbars according to given canvas size."""
if canvwidth: if canvwidth:
self.canvwidth = canvwidth self.canvwidth = canvwidth
if canvheight: if canvheight:
self.canvheight = canvheight self.canvheight = canvheight
if bg: if bg:
self.bg = bg self.bg = bg
self._canvas.config(bg=bg, self._canvas.config(bg=bg,
scrollregion=(-self.canvwidth//2, -self.canvheight//2, scrollregion=(-self.canvwidth//2, -self.canvheight//2,
self.canvwidth//2, self.canvheight//2)) self.canvwidth//2, self.canvheight//2))
self._canvas.xview_moveto(0.5*(self.canvwidth - self.width + 30) / self._canvas.xview_moveto(0.5*(self.canvwidth - self.width + 30) /
self.canvwidth) self.canvwidth)
self._canvas.yview_moveto(0.5*(self.canvheight- self.height + 30) / self._canvas.yview_moveto(0.5*(self.canvheight- self.height + 30) /
self.canvheight) self.canvheight)
self.adjustScrolls() self.adjustScrolls()
def adjustScrolls(self): def adjustScrolls(self):
""" Adjust scrollbars according to window- and canvas-size. """ Adjust scrollbars according to window- and canvas-size.
""" """
cwidth = self._canvas.winfo_width() cwidth = self._canvas.winfo_width()
cheight = self._canvas.winfo_height() cheight = self._canvas.winfo_height()
self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth) self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth)
self._canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight) self._canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight)
if cwidth < self.canvwidth or cheight < self.canvheight: if cwidth < self.canvwidth or cheight < self.canvheight:
self.hscroll.grid(padx=1, in_ = self, pady=1, row=1, self.hscroll.grid(padx=1, in_ = self, pady=1, row=1,
column=0, rowspan=1, columnspan=1, sticky='news') column=0, rowspan=1, columnspan=1, sticky='news')
self.vscroll.grid(padx=1, in_ = self, pady=1, row=0, self.vscroll.grid(padx=1, in_ = self, pady=1, row=0,
column=1, rowspan=1, columnspan=1, sticky='news') column=1, rowspan=1, columnspan=1, sticky='news')
else: else:
self.hscroll.grid_forget() self.hscroll.grid_forget()
self.vscroll.grid_forget() self.vscroll.grid_forget()
def onResize(self, event): def onResize(self, event):
"""self-explanatory""" """self-explanatory"""
self.adjustScrolls() self.adjustScrolls()
def bbox(self, *args): def bbox(self, *args):
""" 'forward' method, which canvas itself has inherited... """ 'forward' method, which canvas itself has inherited...
""" """
return self._canvas.bbox(*args) return self._canvas.bbox(*args)
def cget(self, *args, **kwargs): def cget(self, *args, **kwargs):
""" 'forward' method, which canvas itself has inherited... """ 'forward' method, which canvas itself has inherited...
""" """
return self._canvas.cget(*args, **kwargs) return self._canvas.cget(*args, **kwargs)
def config(self, *args, **kwargs): def config(self, *args, **kwargs):
""" 'forward' method, which canvas itself has inherited... """ 'forward' method, which canvas itself has inherited...
""" """
self._canvas.config(*args, **kwargs) self._canvas.config(*args, **kwargs)
def bind(self, *args, **kwargs): def bind(self, *args, **kwargs):
""" 'forward' method, which canvas itself has inherited... """ 'forward' method, which canvas itself has inherited...
""" """
self._canvas.bind(*args, **kwargs) self._canvas.bind(*args, **kwargs)
def unbind(self, *args, **kwargs): def unbind(self, *args, **kwargs):
""" 'forward' method, which canvas itself has inherited... """ 'forward' method, which canvas itself has inherited...
""" """
self._canvas.unbind(*args, **kwargs) self._canvas.unbind(*args, **kwargs)
def focus_force(self): def focus_force(self):
""" 'forward' method, which canvas itself has inherited... """ 'forward' method, which canvas itself has inherited...
""" """
self._canvas.focus_force() self._canvas.focus_force()
__forwardmethods(ScrolledCanvas, TK.Canvas, '_canvas')__forwardmethods(ScrolledCanvas, TK.Canvas, '_canvas')
class _Root(TK.Tk):class _Root(TK.Tk):
"""Root class for Screen based on Tkinter.""" """Root class for Screen based on Tkinter."""
def __init__(self): def __init__(self):
TK.Tk.__init__(self) TK.Tk.__init__(self)
def setupcanvas(self, width, height, cwidth, cheight): def setupcanvas(self, width, height, cwidth, cheight):
self._canvas = ScrolledCanvas(self, width, height, cwidth, cheight) self._canvas = ScrolledCanvas(self, width, height, cwidth, cheight)
self._canvas.pack(expand=1, fill="both") self._canvas.pack(expand=1, fill="both")
def _getcanvas(self): def _getcanvas(self):
return self._canvas return self._canvas
def set_geometry(self, width, height, startx, starty): def set_geometry(self, width, height, startx, starty):
self.geometry("%dx%d%+d%+d"%(width, height, startx, starty)) self.geometry("%dx%d%+d%+d"%(width, height, startx, starty))
def ondestroy(self, destroy): def ondestroy(self, destroy):
self.wm_protocol("WM_DELETE_WINDOW", destroy) self.wm_protocol("WM_DELETE_WINDOW", destroy)
def win_width(self): def win_width(self):
return self.winfo_screenwidth() return self.winfo_screenwidth()
def win_height(self): def win_height(self):
return self.winfo_screenheight() return self.winfo_screenheight()
Canvas = TK.CanvasCanvas = TK.Canvas
class TurtleScreenBase(object):class TurtleScreenBase(object):
"""Provide the basic graphics functionality. """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 To port turtle.py to some different graphics toolkit
a corresponding TurtleScreenBase class has to be implemented. a corresponding TurtleScreenBase class has to be implemented.
""" """
@staticmethod @staticmethod
def _blankimage(): def _blankimage():
"""return a blank image object """return a blank image object
""" """
img = TK.PhotoImage(width=1, height=1) img = TK.PhotoImage(width=1, height=1)
img.blank() img.blank()
return img return img
@staticmethod @staticmethod
def _image(filename): def _image(filename):
"""return an image object containing the """return an image object containing the
imagedata from a gif-file named filename. imagedata from a gif-file named filename.
""" """
return TK.PhotoImage(file=filename) return TK.PhotoImage(file=filename)
def __init__(self, cv): def __init__(self, cv):
self.cv = cv self.cv = cv
if isinstance(cv, ScrolledCanvas): if isinstance(cv, ScrolledCanvas):
w = self.cv.canvwidth w = self.cv.canvwidth
h = self.cv.canvheight h = self.cv.canvheight
else: # expected: ordinary TK.Canvas else: # expected: ordinary TK.Canvas
w = int(self.cv.cget("width")) w = int(self.cv.cget("width"))
h = int(self.cv.cget("height")) h = int(self.cv.cget("height"))
self.cv.config(scrollregion = (-w//2, -h//2, w//2, h//2 )) self.cv.config(scrollregion = (-w//2, -h//2, w//2, h//2 ))
self.canvwidth = w self.canvwidth = w
self.canvheight = h self.canvheight = h
self.xscale = self.yscale = 1.0 self.xscale = self.yscale = 1.0
def _createpoly(self): def _createpoly(self):
"""Create an invisible polygon item on canvas self.cv) """Create an invisible polygon item on canvas self.cv)
""" """
return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill="", outline="") return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill="", outline="")
def _drawpoly(self, polyitem, coordlist, fill=None, def _drawpoly(self, polyitem, coordlist, fill=None,
outline=None, width=None, top=False): outline=None, width=None, top=False):
"""Configure polygonitem polyitem according to provided """Configure polygonitem polyitem according to provided
arguments: arguments:
coordlist is sequence of coordinates coordlist is sequence of coordinates
fill is filling color fill is filling color
outline is outline color outline is outline color
top is a boolean value, which specifies if polyitem top is a boolean value, which specifies if polyitem
will be put on top of the canvas' displaylist so it will be put on top of the canvas' displaylist so it
will not be covered by other items. will not be covered by other items.
""" """
cl = [] cl = []
for x, y in coordlist: for x, y in coordlist:
cl.append(x * self.xscale) cl.append(x * self.xscale)
cl.append(-y * self.yscale) cl.append(-y * self.yscale)
self.cv.coords(polyitem, *cl) self.cv.coords(polyitem, *cl)
if fill is not None: if fill is not None:
self.cv.itemconfigure(polyitem, fill=fill) self.cv.itemconfigure(polyitem, fill=fill)
if outline is not None: if outline is not None:
self.cv.itemconfigure(polyitem, outline=outline) self.cv.itemconfigure(polyitem, outline=outline)
if width is not None: if width is not None:
self.cv.itemconfigure(polyitem, width=width) self.cv.itemconfigure(polyitem, width=width)
if top: if top:
self.cv.tag_raise(polyitem) self.cv.tag_raise(polyitem)
def _createline(self): def _createline(self):
"""Create an invisible line item on canvas self.cv) """Create an invisible line item on canvas self.cv)
""" """
return self.cv.create_line(0, 0, 0, 0, fill="", width=2, return self.cv.create_line(0, 0, 0, 0, fill="", width=2,
capstyle = TK.ROUND) capstyle = TK.ROUND)
def _drawline(self, lineitem, coordlist=None, def _drawline(self, lineitem, coordlist=None,
fill=None, width=None, top=False): fill=None, width=None, top=False):
"""Configure lineitem according to provided arguments: """Configure lineitem according to provided arguments:
coordlist is sequence of coordinates coordlist is sequence of coordinates
fill is drawing color fill is drawing color
width is width of drawn line. width is width of drawn line.
top is a boolean value, which specifies if polyitem top is a boolean value, which specifies if polyitem
will be put on top of the canvas' displaylist so it will be put on top of the canvas' displaylist so it
will not be covered by other items. will not be covered by other items.
""" """
if coordlist is not None: if coordlist is not None:
cl = [] cl = []
for x, y in coordlist: for x, y in coordlist:
cl.append(x * self.xscale) cl.append(x * self.xscale)
cl.append(-y * self.yscale) cl.append(-y * self.yscale)
self.cv.coords(lineitem, *cl) self.cv.coords(lineitem, *cl)
if fill is not None: if fill is not None:
self.cv.itemconfigure(lineitem, fill=fill) self.cv.itemconfigure(lineitem, fill=fill)
if width is not None: if width is not None:
self.cv.itemconfigure(lineitem, width=width) self.cv.itemconfigure(lineitem, width=width)
if top: if top:
self.cv.tag_raise(lineitem) self.cv.tag_raise(lineitem)
def _delete(self, item): def _delete(self, item):
"""Delete graphics item from canvas. """Delete graphics item from canvas.
If item is"all" delete all graphics items. If item is"all" delete all graphics items.
""" """
self.cv.delete(item) self.cv.delete(item)
def _update(self): def _update(self):
"""Redraw graphics items on canvas """Redraw graphics items on canvas
""" """
self.cv.update() self.cv.update()
def _delay(self, delay): def _delay(self, delay):
"""Delay subsequent canvas actions for delay ms.""" """Delay subsequent canvas actions for delay ms."""
self.cv.after(delay) self.cv.after(delay)
def _iscolorstring(self, color): def _iscolorstring(self, color):
"""Check if the string color is a legal Tkinter color string. """Check if the string color is a legal Tkinter color string.
""" """
color = _convertNonEnglish(color)
try: try:
rgb = self.cv.winfo_rgb(color) rgb = self.cv.winfo_rgb(color)
ok = True ok = True
except TK.TclError: except TK.TclError:
ok = False ok = False
return ok return ok
def _bgcolor(self, color=None): def _bgcolor(self, color=None):
"""Set canvas' backgroundcolor if color is not None, """Set canvas' backgroundcolor if color is not None,
else return backgroundcolor.""" else return backgroundcolor."""
color = _convertNonEnglish(color)
if color is not None: if color is not None:
self.cv.config(bg = color) self.cv.config(bg = color)
self._update() self._update()
else: else:
return self.cv.cget("bg") return self.cv.cget("bg")
def _write(self, pos, txt, align, font, pencolor): def _write(self, pos, txt, align, font, pencolor):
"""Write txt at pos in canvas with specified font """Write txt at pos in canvas with specified font
and color. and color.
Return text item and x-coord of right bottom corner Return text item and x-coord of right bottom corner
of text's bounding box.""" of text's bounding box."""
pencolor = _convertNonEnglish(pencolor)
align = _convertNonEnglish(align)
x, y = pos x, y = pos
x = x * self.xscale x = x * self.xscale
y = y * self.yscale y = y * self.yscale
anchor = {"left":"sw", "center":"s", "right":"se" } anchor = {"left":"sw", "center":"s", "right":"se" }
item = self.cv.create_text(x-1, -y, text = txt, anchor = anchor[align], item = self.cv.create_text(x-1, -y, text = txt, anchor = anchor[align],
fill = pencolor, font = font) fill = pencolor, font = font)
x0, y0, x1, y1 = self.cv.bbox(item) x0, y0, x1, y1 = self.cv.bbox(item)
self.cv.update() self.cv.update()
return item, x1-1 return item, x1-1
## def _dot(self, pos, size, color):## def _dot(self, pos, size, color):
## """may be implemented for some other graphics toolkit"""## """may be implemented for some other graphics toolkit"""
def _onclick(self, item, fun, num=1, add=None): def _onclick(self, item, fun, num=1, add=None):
"""Bind fun to mouse-click event on turtle. """Bind fun to mouse-click event on turtle.
fun must be a function with two arguments, the coordinates fun must be a function with two arguments, the coordinates
of the clicked point on the canvas. of the clicked point on the canvas.
num, the number of the mouse-button defaults to 1 num, the number of the mouse-button defaults to 1
""" """
if fun is None: if fun is None:
self.cv.tag_unbind(item, "<Button-%s>" % num) self.cv.tag_unbind(item, "<Button-%s>" % num)
else: else:
def eventfun(event): def eventfun(event):
x, y = (self.cv.canvasx(event.x)/self.xscale, x, y = (self.cv.canvasx(event.x)/self.xscale,
-self.cv.canvasy(event.y)/self.yscale) -self.cv.canvasy(event.y)/self.yscale)
fun(x, y) fun(x, y)
self.cv.tag_bind(item, "<Button-%s>" % num, eventfun, add) self.cv.tag_bind(item, "<Button-%s>" % num, eventfun, add)
def _onrelease(self, item, fun, num=1, add=None): def _onrelease(self, item, fun, num=1, add=None):
"""Bind fun to mouse-button-release event on turtle. """Bind fun to mouse-button-release event on turtle.
fun must be a function with two arguments, the coordinates fun must be a function with two arguments, the coordinates
of the point on the canvas where mouse button is released. of the point on the canvas where mouse button is released.
num, the number of the mouse-button defaults to 1 num, the number of the mouse-button defaults to 1
If a turtle is clicked, first _onclick-event will be performed, If a turtle is clicked, first _onclick-event will be performed,
then _onscreensclick-event. then _onscreensclick-event.
""" """
if fun is None: if fun is None:
self.cv.tag_unbind(item, "<Button%s-ButtonRelease>" % num) self.cv.tag_unbind(item, "<Button%s-ButtonRelease>" % num)
else: else:
def eventfun(event): def eventfun(event):
x, y = (self.cv.canvasx(event.x)/self.xscale, x, y = (self.cv.canvasx(event.x)/self.xscale,
-self.cv.canvasy(event.y)/self.yscale) -self.cv.canvasy(event.y)/self.yscale)
fun(x, y) fun(x, y)
self.cv.tag_bind(item, "<Button%s-ButtonRelease>" % num, self.cv.tag_bind(item, "<Button%s-ButtonRelease>" % num,
eventfun, add) eventfun, add)
def _ondrag(self, item, fun, num=1, add=None): def _ondrag(self, item, fun, num=1, add=None):
"""Bind fun to mouse-move-event (with pressed mouse button) on turtle. """Bind fun to mouse-move-event (with pressed mouse button) on turtle.
fun must be a function with two arguments, the coordinates of the fun must be a function with two arguments, the coordinates of the
actual mouse position on the canvas. actual mouse position on the canvas.
num, the number of the mouse-button defaults to 1 num, the number of the mouse-button defaults to 1
Every sequence of mouse-move-events on a turtle is preceded by a Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that turtle. mouse-click event on that turtle.
""" """
if fun is None: if fun is None:
self.cv.tag_unbind(item, "<Button%s-Motion>" % num) self.cv.tag_unbind(item, "<Button%s-Motion>" % num)
else: else:
def eventfun(event): def eventfun(event):
try: try:
x, y = (self.cv.canvasx(event.x)/self.xscale, x, y = (self.cv.canvasx(event.x)/self.xscale,
-self.cv.canvasy(event.y)/self.yscale) -self.cv.canvasy(event.y)/self.yscale)
fun(x, y) fun(x, y)
except: except:
pass pass
self.cv.tag_bind(item, "<Button%s-Motion>" % num, eventfun, add) self.cv.tag_bind(item, "<Button%s-Motion>" % num, eventfun, add)
def _onscreenclick(self, fun, num=1, add=None): def _onscreenclick(self, fun, num=1, add=None):
"""Bind fun to mouse-click event on canvas. """Bind fun to mouse-click event on canvas.
fun must be a function with two arguments, the coordinates fun must be a function with two arguments, the coordinates
of the clicked point on the canvas. of the clicked point on the canvas.
num, the number of the mouse-button defaults to 1 num, the number of the mouse-button defaults to 1
If a turtle is clicked, first _onclick-event will be performed, If a turtle is clicked, first _onclick-event will be performed,
then _onscreensclick-event. then _onscreensclick-event.
""" """
if fun is None: if fun is None:
self.cv.unbind("<Button-%s>" % num) self.cv.unbind("<Button-%s>" % num)
else: else:
def eventfun(event): def eventfun(event):
x, y = (self.cv.canvasx(event.x)/self.xscale, x, y = (self.cv.canvasx(event.x)/self.xscale,
-self.cv.canvasy(event.y)/self.yscale) -self.cv.canvasy(event.y)/self.yscale)
fun(x, y) fun(x, y)
self.cv.bind("<Button-%s>" % num, eventfun, add) self.cv.bind("<Button-%s>" % num, eventfun, add)
def _onkeyrelease(self, fun, key): def _onkeyrelease(self, fun, key):
"""Bind fun to key-release event of key. """Bind fun to key-release event of key.
Canvas must have focus. See method listen Canvas must have focus. See method listen
""" """
if fun is None: if fun is None:
self.cv.unbind("<KeyRelease-%s>" % key, None) self.cv.unbind("<KeyRelease-%s>" % key, None)
else: else:
def eventfun(event): def eventfun(event):
fun() fun()
self.cv.bind("<KeyRelease-%s>" % key, eventfun) self.cv.bind("<KeyRelease-%s>" % key, eventfun)
def _onkeypress(self, fun, key=None): def _onkeypress(self, fun, key=None):
"""If key is given, bind fun to key-press event of key. """If key is given, bind fun to key-press event of key.
Otherwise bind fun to any key-press. Otherwise bind fun to any key-press.
Canvas must have focus. See method listen. Canvas must have focus. See method listen.
""" """
if fun is None: if fun is None:
if key is None: if key is None:
self.cv.unbind("<KeyPress>", None) self.cv.unbind("<KeyPress>", None)
else: else:
self.cv.unbind("<KeyPress-%s>" % key, None) self.cv.unbind("<KeyPress-%s>" % key, None)
else: else:
def eventfun(event): def eventfun(event):
fun() fun()
if key is None: if key is None:
self.cv.bind("<KeyPress>", eventfun) self.cv.bind("<KeyPress>", eventfun)
else: else:
self.cv.bind("<KeyPress-%s>" % key, eventfun) self.cv.bind("<KeyPress-%s>" % key, eventfun)
def _listen(self): def _listen(self):
"""Set focus on canvas (in order to collect key-events) """Set focus on canvas (in order to collect key-events)
""" """
self.cv.focus_force() self.cv.focus_force()
def _ontimer(self, fun, t): def _ontimer(self, fun, t):
"""Install a timer, which calls fun after t milliseconds. """Install a timer, which calls fun after t milliseconds.
""" """
if t == 0: if t == 0:
self.cv.after_idle(fun) self.cv.after_idle(fun)
else: else:
self.cv.after(t, fun) self.cv.after(t, fun)
def _createimage(self, image): def _createimage(self, image):
"""Create and return image item on canvas. """Create and return image item on canvas.
""" """
return self.cv.create_image(0, 0, image=image) return self.cv.create_image(0, 0, image=image)
def _drawimage(self, item, pos, image): def _drawimage(self, item, pos, image):
"""Configure image item as to draw image object """Configure image item as to draw image object
at position (x,y) on canvas) at position (x,y) on canvas)
""" """
x, y = pos x, y = pos
self.cv.coords(item, (x * self.xscale, -y * self.yscale)) self.cv.coords(item, (x * self.xscale, -y * self.yscale))
self.cv.itemconfig(item, image=image) self.cv.itemconfig(item, image=image)
def _setbgpic(self, item, image): def _setbgpic(self, item, image):
"""Configure image item as to draw image object """Configure image item as to draw image object
at center of canvas. Set item to the first item at center of canvas. Set item to the first item
in the displaylist, so it will be drawn below in the displaylist, so it will be drawn below
any other item .""" any other item ."""
self.cv.itemconfig(item, image=image) self.cv.itemconfig(item, image=image)
self.cv.tag_lower(item) self.cv.tag_lower(item)
def _type(self, item): def _type(self, item):
"""Return 'line' or 'polygon' or 'image' depending on """Return 'line' or 'polygon' or 'image' depending on
type of item. type of item.
""" """
return self.cv.type(item) return self.cv.type(item)
def _pointlist(self, item): def _pointlist(self, item):
"""returns list of coordinate-pairs of points of item """returns list of coordinate-pairs of points of item
Example (for insiders): Example (for insiders):
>>> from turtle import * >>> from turtle import *
>>> getscreen()._pointlist(getturtle().turtle._item) >>> getscreen()._pointlist(getturtle().turtle._item)
[(0.0, 9.9999999999999982), (0.0, -9.9999999999999982), [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982),
(9.9999999999999982, 0.0)] (9.9999999999999982, 0.0)]
>>> """ >>> """
cl = self.cv.coords(item) cl = self.cv.coords(item)
pl = [(cl[i], -cl[i+1]) for i in range(0, len(cl), 2)] pl = [(cl[i], -cl[i+1]) for i in range(0, len(cl), 2)]
return pl return pl
def _setscrollregion(self, srx1, sry1, srx2, sry2): def _setscrollregion(self, srx1, sry1, srx2, sry2):
self.cv.config(scrollregion=(srx1, sry1, srx2, sry2)) self.cv.config(scrollregion=(srx1, sry1, srx2, sry2))
def _rescale(self, xscalefactor, yscalefactor): def _rescale(self, xscalefactor, yscalefactor):
items = self.cv.find_all() items = self.cv.find_all()
for item in items: for item in items:
coordinates = list(self.cv.coords(item)) coordinates = list(self.cv.coords(item))
newcoordlist = [] newcoordlist = []
while coordinates: while coordinates:
x, y = coordinates[:2] x, y = coordinates[:2]
newcoordlist.append(x * xscalefactor) newcoordlist.append(x * xscalefactor)
newcoordlist.append(y * yscalefactor) newcoordlist.append(y * yscalefactor)
coordinates = coordinates[2:] coordinates = coordinates[2:]
self.cv.coords(item, *newcoordlist) self.cv.coords(item, *newcoordlist)
def _resize(self, canvwidth=None, canvheight=None, bg=None): def _resize(self, canvwidth=None, canvheight=None, bg=None):
"""Resize the canvas the turtles are drawing on. Does """Resize the canvas the turtles are drawing on. Does
not alter the drawing window. not alter the drawing window.
""" """
# needs amendment # needs amendment
if not isinstance(self.cv, ScrolledCanvas): if not isinstance(self.cv, ScrolledCanvas):
return self.canvwidth, self.canvheight return self.canvwidth, self.canvheight
if canvwidth is canvheight is bg is None: if canvwidth is canvheight is bg is None:
return self.cv.canvwidth, self.cv.canvheight return self.cv.canvwidth, self.cv.canvheight
if canvwidth is not None: if canvwidth is not None:
self.canvwidth = canvwidth self.canvwidth = canvwidth
if canvheight is not None: if canvheight is not None:
self.canvheight = canvheight self.canvheight = canvheight
self.cv.reset(canvwidth, canvheight, bg) self.cv.reset(canvwidth, canvheight, bg)
def _window_size(self): def _window_size(self):
""" Return the width and height of the turtle window. """ Return the width and height of the turtle window.
""" """
width = self.cv.winfo_width() width = self.cv.winfo_width()
if width <= 1: # the window isn't managed by a geometry manager if width <= 1: # the window isn't managed by a geometry manager
width = self.cv['width'] width = self.cv['width']
height = self.cv.winfo_height() height = self.cv.winfo_height()
if height <= 1: # the window isn't managed by a geometry manager if height <= 1: # the window isn't managed by a geometry manager
height = self.cv['height'] height = self.cv['height']
return width, height return width, height
def mainloop(self): def mainloop(self):
"""Starts event loop - calling Tkinter's mainloop function. """Starts event loop - calling Tkinter's mainloop function.
No argument. No argument.
Must be last statement in a turtle graphics program. Must be last statement in a turtle graphics program.
Must NOT be used if a script is run from within IDLE in -n mode Must NOT be used if a script is run from within IDLE in -n mode
(No subprocess) - for interactive use of turtle graphics. (No subprocess) - for interactive use of turtle graphics.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.mainloop() >>> screen.mainloop()
""" """
TK.mainloop() TK.mainloop()
def textinput(self, title, prompt): def textinput(self, title, prompt):
"""Pop up a dialog window for input of a string. """Pop up a dialog window for input of a string.
Arguments: title is the title of the dialog window, Arguments: title is the title of the dialog window,
prompt is a text mostly describing what information to input. prompt is a text mostly describing what information to input.
Return the string input Return the string input
If the dialog is canceled, return None. If the dialog is canceled, return None.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.textinput("NIM", "Name of first player:") >>> screen.textinput("NIM", "Name of first player:")
""" """
return simpledialog.askstring(title, prompt) if sys.version_info[0] == 2:
# In Python 2, use pymsgbox for message box
import pymsgbox
return pymsgbox.prompt(prompt, title)
else:
return simpledialog.askstring(title, prompt)
def numinput(self, title, prompt, default=None, minval=None, maxval=None): def numinput(self, title, prompt, default=None, minval=None, maxval=None):
"""Pop up a dialog window for input of a number. """Pop up a dialog window for input of a number.
Arguments: title is the title of the dialog window, Arguments: title is the title of the dialog window,
prompt is a text mostly describing what numerical information to input. prompt is a text mostly describing what numerical information to input.
default: default value default: default value
minval: minimum value for imput minval: minimum value for imput
maxval: maximum value for input maxval: maximum value for input
The number input must be in the range minval .. maxval if these are The number input must be in the range minval .. maxval if these are
given. If not, a hint is issued and the dialog remains open for given. If not, a hint is issued and the dialog remains open for
correction. Return the number input. correction. Return the number input.
If the dialog is canceled, return None. If the dialog is canceled, return None.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000) >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
""" """
return simpledialog.askfloat(title, prompt, initialvalue=default, if sys.version_info[0] == 2:
# In Python 2, use pymsgbox for message box
import pymsgbox
if default is None:
default = ''
while True:
val = pymsgbox.prompt(prompt, title, default=default)
if val is None:
return None
try:
val = float(val)
except:
pymsgbox.alert(text='Not a floating point value.\nPlease try again.', title='Illegal value')
continue
if minval is not None and val < minval:
pymsgbox.alert(text='The allowed minimum value is %s. Please try again.' % (minval), title='Too small')
continue
if maxval is not None and val > maxval:
pymsgbox.alert(text='The allowed maximum value is %s. Please try again.' % (maxval), title='Too large')
continue
return val
else:
return simpledialog.askfloat(title, prompt, initialvalue=default,
minvalue=minval, maxvalue=maxval) minvalue=minval, maxvalue=maxval)
############################################################################################################################################################
### End of Tkinter - interface ###### End of Tkinter - interface ###
############################################################################################################################################################
class Terminator (Exception):class Terminator (Exception):
"""Will be raised in TurtleScreen.update, if _RUNNING becomes False. """Will be raised in TurtleScreen.update, if _RUNNING becomes False.
This stops execution of a turtle graphics script. This stops execution of a turtle graphics script.
Main purpose: use in the Demo-Viewer turtle.Demo.py. Main purpose: use in the Demo-Viewer turtle.Demo.py.
""" """
pass pass
class TurtleGraphicsError(Exception):class TurtleGraphicsError(Exception):
"""Some TurtleGraphics Error """Some TurtleGraphics Error
""" """
class Shape(object):class Shape(object):
"""Data structure modeling shapes. """Data structure modeling shapes.
attribute _type is one of "polygon", "image", "compound" attribute _type is one of "polygon", "image", "compound"
attribute _data is - depending on _type a poygon-tuple, attribute _data is - depending on _type a poygon-tuple,
an image or a list constructed using the addcomponent method. an image or a list constructed using the addcomponent method.
""" """
def __init__(self, type_, data=None): def __init__(self, type_, data=None):
self._type = type_ self._type = type_
if type_ == "polygon": if type_ == "polygon":
if isinstance(data, list): if isinstance(data, list):
data = tuple(data) data = tuple(data)
elif type_ == "image": elif type_ == "image":
if isinstance(data, str): if isinstance(data, str):
if data.lower().endswith(".gif") and isfile(data): if data.lower().endswith(".gif") and isfile(data):
data = TurtleScreen._image(data) data = TurtleScreen._image(data)
# else data assumed to be Photoimage # else data assumed to be Photoimage
elif type_ == "compound": elif type_ == "compound":
data = [] data = []
else: else:
raise TurtleGraphicsError("There is no shape type %s" % type_) raise TurtleGraphicsError("There is no shape type %s" % type_)
self._data = data self._data = data
def addcomponent(self, poly, fill, outline=None): def addcomponent(self, poly, fill, outline=None):
"""Add component to a shape of type compound. """Add component to a shape of type compound.
Arguments: poly is a polygon, i. e. a tuple of number pairs. Arguments: poly is a polygon, i. e. a tuple of number pairs.
fill is the fillcolor of the component, fill is the fillcolor of the component,
outline is the outline color of the component. outline is the outline color of the component.
call (for a Shapeobject namend s): call (for a Shapeobject namend s):
-- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue") -- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue")
Example: Example:
>>> poly = ((0,0),(10,-5),(0,10),(-10,-5)) >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
>>> s = Shape("compound") >>> s = Shape("compound")
>>> s.addcomponent(poly, "red", "blue") >>> s.addcomponent(poly, "red", "blue")
>>> # .. add more components and then use register_shape() >>> # .. add more components and then use register_shape()
""" """
fill = _convertNonEnglish(fill)
outline = _convertNonEnglish(outline)
if self._type != "compound": if self._type != "compound":
raise TurtleGraphicsError("Cannot add component to %s Shape" raise TurtleGraphicsError("Cannot add component to %s Shape"
% self._type) % self._type)
if outline is None: if outline is None:
outline = fill outline = fill
self._data.append([poly, fill, outline]) self._data.append([poly, fill, outline])
class Tbuffer(object):class Tbuffer(object):
"""Ring buffer used as undobuffer for RawTurtle objects.""" """Ring buffer used as undobuffer for RawTurtle objects."""
def __init__(self, bufsize=10): def __init__(self, bufsize=10):
self.bufsize = bufsize self.bufsize = bufsize
self.buffer = [[None]] * bufsize self.buffer = [[None]] * bufsize
self.ptr = -1 self.ptr = -1
self.cumulate = False self.cumulate = False
def reset(self, bufsize=None): def reset(self, bufsize=None):
if bufsize is None: if bufsize is None:
for i in range(self.bufsize): for i in range(self.bufsize):
self.buffer[i] = [None] self.buffer[i] = [None]
else: else:
self.bufsize = bufsize self.bufsize = bufsize
self.buffer = [[None]] * bufsize self.buffer = [[None]] * bufsize
self.ptr = -1 self.ptr = -1
def push(self, item): def push(self, item):
if self.bufsize > 0: if self.bufsize > 0:
if not self.cumulate: if not self.cumulate:
self.ptr = (self.ptr + 1) % self.bufsize self.ptr = (self.ptr + 1) % self.bufsize
self.buffer[self.ptr] = item self.buffer[self.ptr] = item
else: else:
self.buffer[self.ptr].append(item) self.buffer[self.ptr].append(item)
def pop(self): def pop(self):
if self.bufsize > 0: if self.bufsize > 0:
item = self.buffer[self.ptr] item = self.buffer[self.ptr]
if item is None: if item is None:
return None return None
else: else:
self.buffer[self.ptr] = [None] self.buffer[self.ptr] = [None]
self.ptr = (self.ptr - 1) % self.bufsize self.ptr = (self.ptr - 1) % self.bufsize
return (item) return (item)
def nr_of_items(self): def nr_of_items(self):
return self.bufsize - self.buffer.count([None]) return self.bufsize - self.buffer.count([None])
def __repr__(self): def __repr__(self):
return str(self.buffer) + " " + str(self.ptr) return str(self.buffer) + " " + str(self.ptr)
class TurtleScreen(TurtleScreenBase):class TurtleScreen(TurtleScreenBase):
"""Provides screen oriented methods like setbg etc. """Provides screen oriented methods like setbg etc.
Only relies upon the methods of TurtleScreenBase and NOT Only relies upon the methods of TurtleScreenBase and NOT
upon components of the underlying graphics toolkit - upon components of the underlying graphics toolkit -
which is Tkinter in this case. which is Tkinter in this case.
""" """
_RUNNING = True _RUNNING = True
def __init__(self, cv, mode=_CFG["mode"], def __init__(self, cv, mode=_CFG["mode"],
colormode=_CFG["colormode"], delay=_CFG["delay"]): colormode=_CFG["colormode"], delay=_CFG["delay"]):
self._shapes = { self._shapes = {
"arrow" : Shape("polygon", ((-10,0), (10,0), (0,10))), "arrow" : Shape("polygon", ((-10,0), (10,0), (0,10))),
"turtle" : Shape("polygon", ((0,16), (-2,14), (-1,10), (-4,7), "turtle" : Shape("polygon", ((0,16), (-2,14), (-1,10), (-4,7),
(-7,9), (-9,8), (-6,5), (-7,1), (-5,-3), (-8,-6), (-7,9), (-9,8), (-6,5), (-7,1), (-5,-3), (-8,-6),
(-6,-8), (-4,-5), (0,-7), (4,-5), (6,-8), (8,-6), (-6,-8), (-4,-5), (0,-7), (4,-5), (6,-8), (8,-6),
(5,-3), (7,1), (6,5), (9,8), (7,9), (4,7), (1,10), (5,-3), (7,1), (6,5), (9,8), (7,9), (4,7), (1,10),
(2,14))), (2,14))),
"circle" : Shape("polygon", ((10,0), (9.51,3.09), (8.09,5.88), "circle" : Shape("polygon", ((10,0), (9.51,3.09), (8.09,5.88),
(5.88,8.09), (3.09,9.51), (0,10), (-3.09,9.51), (5.88,8.09), (3.09,9.51), (0,10), (-3.09,9.51),
(-5.88,8.09), (-8.09,5.88), (-9.51,3.09), (-10,0), (-5.88,8.09), (-8.09,5.88), (-9.51,3.09), (-10,0),
(-9.51,-3.09), (-8.09,-5.88), (-5.88,-8.09), (-9.51,-3.09), (-8.09,-5.88), (-5.88,-8.09),
(-3.09,-9.51), (-0.00,-10.00), (3.09,-9.51), (-3.09,-9.51), (-0.00,-10.00), (3.09,-9.51),
(5.88,-8.09), (8.09,-5.88), (9.51,-3.09))), (5.88,-8.09), (8.09,-5.88), (9.51,-3.09))),
"square" : Shape("polygon", ((10,-10), (10,10), (-10,10), "square" : Shape("polygon", ((10,-10), (10,10), (-10,10),
(-10,-10))), (-10,-10))),
"triangle" : Shape("polygon", ((10,-5.77), (0,11.55), "triangle" : Shape("polygon", ((10,-5.77), (0,11.55),
(-10,-5.77))), (-10,-5.77))),
"classic": Shape("polygon", ((0,0),(-5,-9),(0,-7),(5,-9))), "classic": Shape("polygon", ((0,0),(-5,-9),(0,-7),(5,-9))),
"blank" : Shape("image", self._blankimage()) "blank" : Shape("image", self._blankimage())
} }
self._bgpics = {"nopic" : ""} self._bgpics = {"nopic" : ""}
TurtleScreenBase.__init__(self, cv) TurtleScreenBase.__init__(self, cv)
self._mode = mode self._mode = mode
self._delayvalue = delay self._delayvalue = delay
self._colormode = _CFG["colormode"] self._colormode = _CFG["colormode"]
self._keys = [] self._keys = []
self.clear() self.clear()
if sys.platform == 'darwin': if sys.platform == 'darwin':
# Force Turtle window to the front on OS X. This is needed because # Force Turtle window to the front on OS X. This is needed because
# the Turtle window will show behind the Terminal window when you # the Turtle window will show behind the Terminal window when you
# start the demo from the command line. # start the demo from the command line.
rootwindow = cv.winfo_toplevel() rootwindow = cv.winfo_toplevel()
rootwindow.call('wm', 'attributes', '.', '-topmost', '1') rootwindow.call('wm', 'attributes', '.', '-topmost', '1')
rootwindow.call('wm', 'attributes', '.', '-topmost', '0') rootwindow.call('wm', 'attributes', '.', '-topmost', '0')
def clear(self): def clear(self):
"""Delete all drawings and all turtles from the TurtleScreen. """Delete all drawings and all turtles from the TurtleScreen.
No argument. No argument.
Reset empty TurtleScreen to its initial state: white background, Reset empty TurtleScreen to its initial state: white background,
no backgroundimage, no eventbindings and tracing on. no backgroundimage, no eventbindings and tracing on.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.clear() >>> screen.clear()
Note: this method is not available as function. Note: this method is not available as function.
""" """
self._delayvalue = _CFG["delay"] self._delayvalue = _CFG["delay"]
self._colormode = _CFG["colormode"] self._colormode = _CFG["colormode"]
self._delete("all") self._delete("all")
self._bgpic = self._createimage("") self._bgpic = self._createimage("")
self._bgpicname = "nopic" self._bgpicname = "nopic"
self._tracing = 1 self._tracing = 1
self._updatecounter = 0 self._updatecounter = 0
self._turtles = [] self._turtles = []
self.bgcolor("white") self.bgcolor("white")
for btn in 1, 2, 3: for btn in 1, 2, 3:
self.onclick(None, btn) self.onclick(None, btn)
self.onkeypress(None) self.onkeypress(None)
for key in self._keys[:]: for key in self._keys[:]:
self.onkey(None, key) self.onkey(None, key)
self.onkeypress(None, key) self.onkeypress(None, key)
Turtle._pen = None Turtle._pen = None
def mode(self, mode=None): def mode(self, mode=None):
"""Set turtle-mode ('standard', 'logo' or 'world') and perform reset. """Set turtle-mode ('standard', 'logo' or 'world') and perform reset.
Optional argument: Optional argument:
mode -- on of the strings 'standard', 'logo' or 'world' mode -- on of the strings 'standard', 'logo' or 'world'
Mode 'standard' is compatible with turtle.py. Mode 'standard' is compatible with turtle.py.
Mode 'logo' is compatible with most Logo-Turtle-Graphics. Mode 'logo' is compatible with most Logo-Turtle-Graphics.
Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in
this mode angles appear distorted if x/y unit-ratio doesn't equal 1. this mode angles appear distorted if x/y unit-ratio doesn't equal 1.
If mode is not given, return the current mode. If mode is not given, return the current mode.
Mode Initial turtle heading positive angles Mode Initial turtle heading positive angles
------------|-------------------------|------------------- ------------|-------------------------|-------------------
'standard' to the right (east) counterclockwise 'standard' to the right (east) counterclockwise
'logo' upward (north) clockwise 'logo' upward (north) clockwise
Examples: Examples:
>>> mode('logo') # resets turtle heading to north >>> mode('logo') # resets turtle heading to north
>>> mode() >>> mode()
'logo' 'logo'
""" """
if mode is None: if mode is None:
return self._mode return self._mode
mode = mode.lower() mode = mode.lower()
if mode not in ["standard", "logo", "world"]: if mode not in ["standard", "logo", "world"]:
raise TurtleGraphicsError("No turtle-graphics-mode %s" % mode) raise TurtleGraphicsError("No turtle-graphics-mode %s" % mode)
self._mode = mode self._mode = mode
if mode in ["standard", "logo"]: if mode in ["standard", "logo"]:
self._setscrollregion(-self.canvwidth//2, -self.canvheight//2, self._setscrollregion(-self.canvwidth//2, -self.canvheight//2,
self.canvwidth//2, self.canvheight//2) self.canvwidth//2, self.canvheight//2)
self.xscale = self.yscale = 1.0 self.xscale = self.yscale = 1.0
self.reset() self.reset()
def setworldcoordinates(self, llx, lly, urx, ury): def setworldcoordinates(self, llx, lly, urx, ury):
"""Set up a user defined coordinate-system. """Set up a user defined coordinate-system.
Arguments: Arguments:
llx -- a number, x-coordinate of lower left corner of canvas llx -- a number, x-coordinate of lower left corner of canvas
lly -- a number, y-coordinate of lower left corner of canvas lly -- a number, y-coordinate of lower left corner of canvas
urx -- a number, x-coordinate of upper right corner of canvas urx -- a number, x-coordinate of upper right corner of canvas
ury -- a number, y-coordinate of upper right corner of canvas ury -- a number, y-coordinate of upper right corner of canvas
Set up user coodinat-system and switch to mode 'world' if necessary. Set up user coodinat-system and switch to mode 'world' if necessary.
This performs a screen.reset. If mode 'world' is already active, This performs a screen.reset. If mode 'world' is already active,
all drawings are redrawn according to the new coordinates. all drawings are redrawn according to the new coordinates.
But ATTENTION: in user-defined coordinatesystems angles may appear But ATTENTION: in user-defined coordinatesystems angles may appear
distorted. (see Screen.mode()) distorted. (see Screen.mode())
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.setworldcoordinates(-10,-0.5,50,1.5) >>> screen.setworldcoordinates(-10,-0.5,50,1.5)
>>> for _ in range(36): >>> for _ in range(36):
... left(10) ... left(10)
... forward(0.5) ... forward(0.5)
""" """
if self.mode() != "world": if self.mode() != "world":
self.mode("world") self.mode("world")
xspan = float(urx - llx) xspan = float(urx - llx)
yspan = float(ury - lly) yspan = float(ury - lly)
wx, wy = self._window_size() wx, wy = self._window_size()
self.screensize(wx-20, wy-20) self.screensize(wx-20, wy-20)
oldxscale, oldyscale = self.xscale, self.yscale oldxscale, oldyscale = self.xscale, self.yscale
self.xscale = self.canvwidth / xspan self.xscale = self.canvwidth / xspan
self.yscale = self.canvheight / yspan self.yscale = self.canvheight / yspan
srx1 = llx * self.xscale srx1 = llx * self.xscale
sry1 = -ury * self.yscale sry1 = -ury * self.yscale
srx2 = self.canvwidth + srx1 srx2 = self.canvwidth + srx1
sry2 = self.canvheight + sry1 sry2 = self.canvheight + sry1
self._setscrollregion(srx1, sry1, srx2, sry2) self._setscrollregion(srx1, sry1, srx2, sry2)
self._rescale(self.xscale/oldxscale, self.yscale/oldyscale) self._rescale(self.xscale/oldxscale, self.yscale/oldyscale)
self.update() self.update()
def register_shape(self, name, shape=None): def register_shape(self, name, shape=None):
"""Adds a turtle shape to TurtleScreen's shapelist. """Adds a turtle shape to TurtleScreen's shapelist.
Arguments: Arguments:
(1) name is the name of a gif-file and shape is None. (1) name is the name of a gif-file and shape is None.
Installs the corresponding image shape. Installs the corresponding image shape.
!! Image-shapes DO NOT rotate when turning the turtle, !! Image-shapes DO NOT rotate when turning the turtle,
!! so they do not display the heading of the turtle! !! so they do not display the heading of the turtle!
(2) name is an arbitrary string and shape is a tuple (2) name is an arbitrary string and shape is a tuple
of pairs of coordinates. Installs the corresponding of pairs of coordinates. Installs the corresponding
polygon shape polygon shape
(3) name is an arbitrary string and shape is a (3) name is an arbitrary string and shape is a
(compound) Shape object. Installs the corresponding (compound) Shape object. Installs the corresponding
compound shape. compound shape.
To use a shape, you have to issue the command shape(shapename). To use a shape, you have to issue the command shape(shapename).
call: register_shape("turtle.gif") call: register_shape("turtle.gif")
--or: register_shape("tri", ((0,0), (10,10), (-10,10))) --or: register_shape("tri", ((0,0), (10,10), (-10,10)))
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3))) >>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3)))
""" """
name = _convertNonEnglish(name)
if shape is None: if shape is None:
# image # image
if name.lower().endswith(".gif"): if name.lower().endswith(".gif"):
shape = Shape("image", self._image(name)) shape = Shape("image", self._image(name))
else: else:
raise TurtleGraphicsError("Bad arguments for register_shape.\n" raise TurtleGraphicsError("Bad arguments for register_shape.\n"
+ "Use help(register_shape)" ) + "Use help(register_shape)" )
elif isinstance(shape, tuple): elif isinstance(shape, tuple):
shape = Shape("polygon", shape) shape = Shape("polygon", shape)
## else shape assumed to be Shape-instance ## else shape assumed to be Shape-instance
self._shapes[name] = shape self._shapes[name] = shape
def _colorstr(self, color): def _colorstr(self, color):
"""Return color string corresponding to args. """Return color string corresponding to args.
Argument may be a string or a tuple of three Argument may be a string or a tuple of three
numbers corresponding to actual colormode, numbers corresponding to actual colormode,
i.e. in the range 0<=n<=colormode. i.e. in the range 0<=n<=colormode.
If the argument doesn't represent a color, If the argument doesn't represent a color,
an error is raised. an error is raised.
""" """
if len(color) == 1: if len(color) == 1:
color = color[0] color = _convertNonEnglish(color[0])
if isinstance(color, str): if isinstance(color, str):
color = _convertNonEnglish(color)
if self._iscolorstring(color) or color == "": if self._iscolorstring(color) or color == "":
return color return color
else: else:
raise TurtleGraphicsError("bad color string: %s" % str(color)) raise TurtleGraphicsError("bad color string: %s" % str(color))
try: try:
r, g, b = color r, g, b = color
except: except:
raise TurtleGraphicsError("bad color arguments: %s" % str(color)) raise TurtleGraphicsError("bad color arguments: %s" % str(color))
if self._colormode == 1.0: if self._colormode == 1.0:
r, g, b = [round(255.0*x) for x in (r, g, b)] r, g, b = [round(255.0*x) for x in (r, g, b)]
if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)): if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)):
raise TurtleGraphicsError("bad color sequence: %s" % str(color)) raise TurtleGraphicsError("bad color sequence: %s" % str(color))
return "#%02x%02x%02x" % (r, g, b) return "#%02x%02x%02x" % (r, g, b)
def _color(self, cstr): def _color(self, cstr):
cstr = _convertNonEnglish(cstr)
if not cstr.startswith("#"): if not cstr.startswith("#"):
return cstr return cstr
if len(cstr) == 7: if len(cstr) == 7:
cl = [int(cstr[i:i+2], 16) for i in (1, 3, 5)] cl = [int(cstr[i:i+2], 16) for i in (1, 3, 5)]
elif len(cstr) == 4: elif len(cstr) == 4:
cl = [16*int(cstr[h], 16) for h in cstr[1:]] cl = [16*int(cstr[h], 16) for h in cstr[1:]]
else: else:
raise TurtleGraphicsError("bad colorstring: %s" % cstr) raise TurtleGraphicsError("bad colorstring: %s" % cstr)
return tuple([c * self._colormode/255 for c in cl]) return tuple([c * self._colormode/255 for c in cl])
def colormode(self, cmode=None): def colormode(self, cmode=None):
"""Return the colormode or set it to 1.0 or 255. """Return the colormode or set it to 1.0 or 255.
Optional argument: Optional argument:
cmode -- one of the values 1.0 or 255 cmode -- one of the values 1.0 or 255
r, g, b values of colortriples have to be in range 0..cmode. r, g, b values of colortriples have to be in range 0..cmode.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.colormode() >>> screen.colormode()
1.0 1.0
>>> screen.colormode(255) >>> screen.colormode(255)
>>> pencolor(240,160,80) >>> pencolor(240,160,80)
""" """
if cmode is None: if cmode is None:
return self._colormode return self._colormode
if cmode == 1.0: if cmode == 1.0:
self._colormode = float(cmode) self._colormode = float(cmode)
elif cmode == 255: elif cmode == 255:
self._colormode = int(cmode) self._colormode = int(cmode)
def reset(self): def reset(self):
"""Reset all Turtles on the Screen to their initial state. """Reset all Turtles on the Screen to their initial state.
No argument. No argument.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.reset() >>> screen.reset()
""" """
for turtle in self._turtles: for turtle in self._turtles:
turtle._setmode(self._mode) turtle._setmode(self._mode)
turtle.reset() turtle.reset()
def turtles(self): def turtles(self):
"""Return the list of turtles on the screen. """Return the list of turtles on the screen.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.turtles() >>> screen.turtles()
[<turtle.Turtle object at 0x00E11FB0>] [<turtle.Turtle object at 0x00E11FB0>]
""" """
return self._turtles return self._turtles
def bgcolor(self, *args): def bgcolor(self, *args):
"""Set or return backgroundcolor of the TurtleScreen. """Set or return backgroundcolor of the TurtleScreen.
Arguments (if given): a color string or three numbers Arguments (if given): a color string or three numbers
in the range 0..colormode or a 3-tuple of such numbers. in the range 0..colormode or a 3-tuple of such numbers.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.bgcolor("orange") >>> screen.bgcolor("orange")
>>> screen.bgcolor() >>> screen.bgcolor()
'orange' 'orange'
>>> screen.bgcolor(0.5,0,0.5) >>> screen.bgcolor(0.5,0,0.5)
>>> screen.bgcolor() >>> screen.bgcolor()
'#800080' '#800080'
""" """
if args: if args:
color = self._colorstr(args) color = self._colorstr(args)
else: else:
color = None color = None
color = self._bgcolor(color) color = self._bgcolor(color)
if color is not None: if color is not None:
color = self._color(color) color = self._color(color)
return color return color
def tracer(self, n=None, delay=None): def tracer(self, n=None, delay=None):
"""Turns turtle animation on/off and set delay for update drawings. """Turns turtle animation on/off and set delay for update drawings.
Optional arguments: Optional arguments:
n -- nonnegative integer n -- nonnegative integer
delay -- nonnegative integer delay -- nonnegative integer
If n is given, only each n-th regular screen update is really performed. If n is given, only each n-th regular screen update is really performed.
(Can be used to accelerate the drawing of complex graphics.) (Can be used to accelerate the drawing of complex graphics.)
Second arguments sets delay value (see RawTurtle.delay()) Second arguments sets delay value (see RawTurtle.delay())
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.tracer(8, 25) >>> screen.tracer(8, 25)
>>> dist = 2 >>> dist = 2
>>> for i in range(200): >>> for i in range(200):
... fd(dist) ... fd(dist)
... rt(90) ... rt(90)
... dist += 2 ... dist += 2
""" """
if n is None: if n is None:
return self._tracing return self._tracing
self._tracing = int(n) self._tracing = int(n)
self._updatecounter = 0 self._updatecounter = 0
if delay is not None: if delay is not None:
self._delayvalue = int(delay) self._delayvalue = int(delay)
if self._tracing: if self._tracing:
self.update() self.update()
def delay(self, delay=None): def delay(self, delay=None):
""" Return or set the drawing delay in milliseconds. """ Return or set the drawing delay in milliseconds.
Optional argument: Optional argument:
delay -- positive integer delay -- positive integer
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.delay(15) >>> screen.delay(15)
>>> screen.delay() >>> screen.delay()
15 15
""" """
if delay is None: if delay is None:
return self._delayvalue return self._delayvalue
self._delayvalue = int(delay) self._delayvalue = int(delay)
def _incrementudc(self): def _incrementudc(self):
"""Increment update counter.""" """Increment update counter."""
if not TurtleScreen._RUNNING: if not TurtleScreen._RUNNING:
TurtleScreen._RUNNNING = True TurtleScreen._RUNNNING = True
raise Terminator raise Terminator
if self._tracing > 0: if self._tracing > 0:
self._updatecounter += 1 self._updatecounter += 1
self._updatecounter %= self._tracing self._updatecounter %= self._tracing
def update(self): def update(self):
"""Perform a TurtleScreen update. """Perform a TurtleScreen update.
""" """
tracing = self._tracing tracing = self._tracing
self._tracing = True self._tracing = True
for t in self.turtles(): for t in self.turtles():
t._update_data() t._update_data()
t._drawturtle() t._drawturtle()
self._tracing = tracing self._tracing = tracing
self._update() self._update()
def window_width(self): def window_width(self):
""" Return the width of the turtle window. """ Return the width of the turtle window.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.window_width() >>> screen.window_width()
640 640
""" """
return self._window_size()[0] return self._window_size()[0]
def window_height(self): def window_height(self):
""" Return the height of the turtle window. """ Return the height of the turtle window.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.window_height() >>> screen.window_height()
480 480
""" """
return self._window_size()[1] return self._window_size()[1]
def getcanvas(self): def getcanvas(self):
"""Return the Canvas of this TurtleScreen. """Return the Canvas of this TurtleScreen.
No argument. No argument.
Example (for a Screen instance named screen): Example (for a Screen instance named screen):
>>> cv = screen.getcanvas() >>> cv = screen.getcanvas()
>>> cv >>> cv
<turtle.ScrolledCanvas instance at 0x010742D8> <turtle.ScrolledCanvas instance at 0x010742D8>
""" """
return self.cv return self.cv
def getshapes(self): def getshapes(self):
"""Return a list of names of all currently available turtle shapes. """Return a list of names of all currently available turtle shapes.
No argument. No argument.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.getshapes() >>> screen.getshapes()
['arrow', 'blank', 'circle', ... , 'turtle'] ['arrow', 'blank', 'circle', ... , 'turtle']
""" """
return sorted(self._shapes.keys()) return sorted(self._shapes.keys())
def onclick(self, fun, btn=1, add=None): def onclick(self, fun, btn=1, add=None):
"""Bind fun to mouse-click event on canvas. """Bind fun to mouse-click event on canvas.
Arguments: Arguments:
fun -- a function with two arguments, the coordinates of the fun -- a function with two arguments, the coordinates of the
clicked point on the canvas. clicked point on the canvas.
num -- the number of the mouse-button, defaults to 1 num -- the number of the mouse-button, defaults to 1
Example (for a TurtleScreen instance named screen) Example (for a TurtleScreen instance named screen)
>>> screen.onclick(goto) >>> screen.onclick(goto)
>>> # Subsequently clicking into the TurtleScreen will >>> # Subsequently clicking into the TurtleScreen will
>>> # make the turtle move to the clicked point. >>> # make the turtle move to the clicked point.
>>> screen.onclick(None) >>> screen.onclick(None)
""" """
self._onscreenclick(fun, btn, add) self._onscreenclick(fun, btn, add)
def onkey(self, fun, key): def onkey(self, fun, key):
"""Bind fun to key-release event of key. """Bind fun to key-release event of key.
Arguments: Arguments:
fun -- a function with no arguments fun -- a function with no arguments
key -- a string: key (e.g. "a") or key-symbol (e.g. "space") key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
In order to be able to register key-events, TurtleScreen In order to be able to register key-events, TurtleScreen
must have focus. (See method listen.) must have focus. (See method listen.)
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> def f(): >>> def f():
... fd(50) ... fd(50)
... lt(60) ... lt(60)
... ...
>>> screen.onkey(f, "Up") >>> screen.onkey(f, "Up")
>>> screen.listen() >>> screen.listen()
Subsequently the turtle can be moved by repeatedly pressing Subsequently the turtle can be moved by repeatedly pressing
the up-arrow key, consequently drawing a hexagon the up-arrow key, consequently drawing a hexagon
""" """
if fun is None: if fun is None:
if key in self._keys: if key in self._keys:
self._keys.remove(key) self._keys.remove(key)
elif key not in self._keys: elif key not in self._keys:
self._keys.append(key) self._keys.append(key)
self._onkeyrelease(fun, key) self._onkeyrelease(fun, key)
def onkeypress(self, fun, key=None): def onkeypress(self, fun, key=None):
"""Bind fun to key-press event of key if key is given, """Bind fun to key-press event of key if key is given,
or to any key-press-event if no key is given. or to any key-press-event if no key is given.
Arguments: Arguments:
fun -- a function with no arguments fun -- a function with no arguments
key -- a string: key (e.g. "a") or key-symbol (e.g. "space") key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
In order to be able to register key-events, TurtleScreen In order to be able to register key-events, TurtleScreen
must have focus. (See method listen.) must have focus. (See method listen.)
Example (for a TurtleScreen instance named screen Example (for a TurtleScreen instance named screen
and a Turtle instance named turtle): and a Turtle instance named turtle):
>>> def f(): >>> def f():
... fd(50) ... fd(50)
... lt(60) ... lt(60)
... ...
>>> screen.onkeypress(f, "Up") >>> screen.onkeypress(f, "Up")
>>> screen.listen() >>> screen.listen()
Subsequently the turtle can be moved by repeatedly pressing Subsequently the turtle can be moved by repeatedly pressing
the up-arrow key, or by keeping pressed the up-arrow key. the up-arrow key, or by keeping pressed the up-arrow key.
consequently drawing a hexagon. consequently drawing a hexagon.
""" """
if fun is None: if fun is None:
if key in self._keys: if key in self._keys:
self._keys.remove(key) self._keys.remove(key)
elif key is not None and key not in self._keys: elif key is not None and key not in self._keys:
self._keys.append(key) self._keys.append(key)
self._onkeypress(fun, key) self._onkeypress(fun, key)
def listen(self, xdummy=None, ydummy=None): def listen(self, xdummy=None, ydummy=None):
"""Set focus on TurtleScreen (in order to collect key-events) """Set focus on TurtleScreen (in order to collect key-events)
No arguments. No arguments.
Dummy arguments are provided in order Dummy arguments are provided in order
to be able to pass listen to the onclick method. to be able to pass listen to the onclick method.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.listen() >>> screen.listen()
""" """
self._listen() self._listen()
def ontimer(self, fun, t=0): def ontimer(self, fun, t=0):
"""Install a timer, which calls fun after t milliseconds. """Install a timer, which calls fun after t milliseconds.
Arguments: Arguments:
fun -- a function with no arguments. fun -- a function with no arguments.
t -- a number >= 0 t -- a number >= 0
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> running = True >>> running = True
>>> def f(): >>> def f():
... if running: ... if running:
... fd(50) ... fd(50)
... lt(60) ... lt(60)
... screen.ontimer(f, 250) ... screen.ontimer(f, 250)
... ...
>>> f() # makes the turtle marching around >>> f() # makes the turtle marching around
>>> running = False >>> running = False
""" """
self._ontimer(fun, t) self._ontimer(fun, t)
def bgpic(self, picname=None): def bgpic(self, picname=None):
"""Set background image or return name of current backgroundimage. """Set background image or return name of current backgroundimage.
Optional argument: Optional argument:
picname -- a string, name of a gif-file or "nopic". picname -- a string, name of a gif-file or "nopic".
If picname is a filename, set the corresponding image as background. If picname is a filename, set the corresponding image as background.
If picname is "nopic", delete backgroundimage, if present. If picname is "nopic", delete backgroundimage, if present.
If picname is None, return the filename of the current backgroundimage. If picname is None, return the filename of the current backgroundimage.
Example (for a TurtleScreen instance named screen): Example (for a TurtleScreen instance named screen):
>>> screen.bgpic() >>> screen.bgpic()
'nopic' 'nopic'
>>> screen.bgpic("landscape.gif") >>> screen.bgpic("landscape.gif")
>>> screen.bgpic() >>> screen.bgpic()
'landscape.gif' 'landscape.gif'
""" """
if picname is None: if picname is None:
return self._bgpicname return self._bgpicname
if picname not in self._bgpics: if picname not in self._bgpics:
self._bgpics[picname] = self._image(picname) self._bgpics[picname] = self._image(picname)
self._setbgpic(self._bgpic, self._bgpics[picname]) self._setbgpic(self._bgpic, self._bgpics[picname])
self._bgpicname = picname self._bgpicname = picname
def screensize(self, canvwidth=None, canvheight=None, bg=None): def screensize(self, canvwidth=None, canvheight=None, bg=None):
"""Resize the canvas the turtles are drawing on. """Resize the canvas the turtles are drawing on.
Optional arguments: Optional arguments:
canvwidth -- positive integer, new width of canvas in pixels canvwidth -- positive integer, new width of canvas in pixels
canvheight -- positive integer, new height of canvas in pixels canvheight -- positive integer, new height of canvas in pixels
bg -- colorstring or color-tuple, new backgroundcolor bg -- colorstring or color-tuple, new backgroundcolor
If no arguments are given, return current (canvaswidth, canvasheight) If no arguments are given, return current (canvaswidth, canvasheight)
Do not alter the drawing window. To observe hidden parts of Do not alter the drawing window. To observe hidden parts of
the canvas use the scrollbars. (Can make visible those parts the canvas use the scrollbars. (Can make visible those parts
of a drawing, which were outside the canvas before!) of a drawing, which were outside the canvas before!)
Example (for a Turtle instance named turtle): Example (for a Turtle instance named turtle):
>>> turtle.screensize(2000,1500) >>> turtle.screensize(2000,1500)
>>> # e.g. to search for an erroneously escaped turtle ;-) >>> # e.g. to search for an erroneously escaped turtle ;-)
""" """
bg = _convertNonEnglish(bg)
return self._resize(canvwidth, canvheight, bg) return self._resize(canvwidth, canvheight, bg)
onscreenclick = onclick onscreenclick = onclick
resetscreen = reset resetscreen = reset
clearscreen = clear clearscreen = clear
addshape = register_shape addshape = register_shape
onkeyrelease = onkey onkeyrelease = onkey
class TNavigator(object):class TNavigator(object):
"""Navigation part of the RawTurtle. """Navigation part of the RawTurtle.
Implements methods for turtle movement. Implements methods for turtle movement.
""" """
START_ORIENTATION = { START_ORIENTATION = {
"standard": Vec2D(1.0, 0.0), "standard": Vec2D(1.0, 0.0),
"world" : Vec2D(1.0, 0.0), "world" : Vec2D(1.0, 0.0),
"logo" : Vec2D(0.0, 1.0) } "logo" : Vec2D(0.0, 1.0) }
DEFAULT_MODE = "standard" DEFAULT_MODE = "standard"
DEFAULT_ANGLEOFFSET = 0 DEFAULT_ANGLEOFFSET = 0
DEFAULT_ANGLEORIENT = 1 DEFAULT_ANGLEORIENT = 1
def __init__(self, mode=DEFAULT_MODE): def __init__(self, mode=DEFAULT_MODE):
self._angleOffset = self.DEFAULT_ANGLEOFFSET self._angleOffset = self.DEFAULT_ANGLEOFFSET
self._angleOrient = self.DEFAULT_ANGLEORIENT self._angleOrient = self.DEFAULT_ANGLEORIENT
self._mode = mode self._mode = mode
self.undobuffer = None self.undobuffer = None
self.degrees() self.degrees()
self._mode = None self._mode = None
self._setmode(mode) self._setmode(mode)
TNavigator.reset(self) TNavigator.reset(self)
def reset(self): def reset(self):
"""reset turtle to its initial values """reset turtle to its initial values
Will be overwritten by parent class Will be overwritten by parent class
""" """
self._position = Vec2D(0.0, 0.0) self._position = Vec2D(0.0, 0.0)
self._orient = TNavigator.START_ORIENTATION[self._mode] self._orient = TNavigator.START_ORIENTATION[self._mode]
def _setmode(self, mode=None): def _setmode(self, mode=None):
"""Set turtle-mode to 'standard', 'world' or 'logo'. """Set turtle-mode to 'standard', 'world' or 'logo'.
""" """
mode = _convertNonEnglish(mode)
if mode is None: if mode is None:
return self._mode return self._mode
if mode not in ["standard", "logo", "world"]: if mode not in ["standard", "logo", "world"]:
return return
self._mode = mode self._mode = mode
if mode in ["standard", "world"]: if mode in ["standard", "world"]:
self._angleOffset = 0 self._angleOffset = 0
self._angleOrient = 1 self._angleOrient = 1
else: # mode == "logo": else: # mode == "logo":
self._angleOffset = self._fullcircle/4. self._angleOffset = self._fullcircle/4.
self._angleOrient = -1 self._angleOrient = -1
def _setDegreesPerAU(self, fullcircle): def _setDegreesPerAU(self, fullcircle):
"""Helper function for degrees() and radians()""" """Helper function for degrees() and radians()"""
self._fullcircle = fullcircle self._fullcircle = fullcircle
self._degreesPerAU = 360/fullcircle self._degreesPerAU = 360/fullcircle
if self._mode == "standard": if self._mode == "standard":
self._angleOffset = 0 self._angleOffset = 0
else: else:
self._angleOffset = fullcircle/4. self._angleOffset = fullcircle/4.
def degrees(self, fullcircle=360.0): def degrees(self, fullcircle=360.0):
""" Set angle measurement units to degrees. """ Set angle measurement units to degrees.
Optional argument: Optional argument:
fullcircle - a number fullcircle - a number
Set angle measurement units, i. e. set number Set angle measurement units, i. e. set number
of 'degrees' for a full circle. Dafault value is of 'degrees' for a full circle. Dafault value is
360 degrees. 360 degrees.
Example (for a Turtle instance named turtle): Example (for a Turtle instance named turtle):
>>> turtle.left(90) >>> turtle.left(90)
>>> turtle.heading() >>> turtle.heading()
90 90
Change angle measurement unit to grad (also known as gon, Change angle measurement unit to grad (also known as gon,
grade, or gradian and equals 1/100-th of the right angle.) grade, or gradian and equals 1/100-th of the right angle.)
>>> turtle.degrees(400.0) >>> turtle.degrees(400.0)
>>> turtle.heading() >>> turtle.heading()
100 100
""" """
self._setDegreesPerAU(fullcircle) self._setDegreesPerAU(fullcircle)
def radians(self): def radians(self):
""" Set the angle measurement units to radians. """ Set the angle measurement units to radians.
No arguments. No arguments.
Example (for a Turtle instance named turtle): Example (for a Turtle instance named turtle):
>>> turtle.heading() >>> turtle.heading()
90 90
>>> turtle.radians() >>> turtle.radians()
>>> turtle.heading() >>> turtle.heading()
1.5707963267948966 1.5707963267948966
""" """
self._setDegreesPerAU(2*math.pi) self._setDegreesPerAU(2*math.pi)
def _go(self, distance): def _go(self, distance):
"""move turtle forward by specified distance""" """move turtle forward by specified distance"""
ende = self._position + self._orient * distance ende = self._position + self._orient * distance
self._goto(ende) self._goto(ende)
def _rotate(self, angle): def _rotate(self, angle):
"""Turn turtle counterclockwise by specified angle if angle > 0.""" """Turn turtle counterclockwise by specified angle if angle > 0."""
angle *= self._degreesPerAU angle *= self._degreesPerAU
self._orient = self._orient.rotate(angle) self._orient = self._orient.rotate(angle)
def _goto(self, end): def _goto(self, end):
"""move turtle to position end.""" """move turtle to position end."""
self._position = end self._position = end
def forward(self, distance): def forward(self, distance):
"""Move the turtle forward by the specified distance. """Move the turtle forward by the specified distance.
Aliases: forward | fd Aliases: forward | fd
Argument: Argument:
distance -- a number (integer or float) distance -- a number (integer or float)
Move the turtle forward by the specified distance, in the direction Move the turtle forward by the specified distance, in the direction
the turtle is headed. the turtle is headed.
Example (for a Turtle instance named turtle): Example (for a Turtle instance named turtle):
>>> turtle.position() >>> turtle.position()
(0.00, 0.00) (0.00, 0.00)
>>> turtle.forward(25) >>> turtle.forward(25)
>>> turtle.position() >>> turtle.position()
(25.00,0.00) (25.00,0.00)
>>> turtle.forward(-75) >>> turtle.forward(-75)
>>> turtle.position() >>> turtle.position()
(-50.00,0.00) (-50.00,0.00)
""" """
self._go(distance) self._go(distance)
def back(self, distance): def back(self, distance):
"""Move the turtle backward by distance. """Move the turtle backward by distance.
Aliases: back | backward | bk Aliases: back | backward | bk
Argument: Argument: