desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Truncate the file\'s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed unless the position is beyond the new file size. If the specified size exceeds the file\'s current size, the file remains unchanged.'
def truncate(self, size=None):
_complain_ifclosed(self.closed) if (size is None): size = self.pos elif (size < 0): raise IOError(EINVAL, 'Negative size not allowed') elif (size < self.pos): self.pos = size self.buf = self.getvalue()[:size] self.len = size
'Write a string to the file. There is no return value.'
def write(self, s):
_complain_ifclosed(self.closed) if (not s): return if (not isinstance(s, basestring)): s = str(s) spos = self.pos slen = self.len if (spos == slen): self.buflist.append(s) self.len = self.pos = (spos + len(s)) return if (spos > slen): self.buflist.append(('\x00' * (spos - slen))) slen = spos newpos = (spos + len(s)) if (spos < slen): if self.buflist: self.buf += ''.join(self.buflist) self.buflist = [self.buf[:spos], s, self.buf[newpos:]] self.buf = '' if (newpos > slen): slen = newpos else: self.buflist.append(s) slen = newpos self.len = slen self.pos = newpos
'Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value. (The name is intended to match readlines(); writelines() does not add line separators.)'
def writelines(self, iterable):
write = self.write for line in iterable: write(line)
'Flush the internal buffer'
def flush(self):
_complain_ifclosed(self.closed)
'Retrieve the entire contents of the "file" at any time before the StringIO object\'s close() method is called. The StringIO object can accept either Unicode or 8-bit strings, but mixing the two may take some care. If both are used, 8-bit strings that cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause a UnicodeError to be raised when getvalue() is called.'
def getvalue(self):
_complain_ifclosed(self.closed) if self.buflist: self.buf += ''.join(self.buflist) self.buflist = [] return self.buf
'real_value, coded_value = value_decode(STRING) Called prior to setting a cookie\'s value from the network representation. The VALUE is the value read from HTTP header. Override this function to modify the behavior of cookies.'
def value_decode(self, val):
return (val, val)
'real_value, coded_value = value_encode(VALUE) Called prior to setting a cookie\'s value from the dictionary representation. The VALUE is the value being assigned. Override this function to modify the behavior of cookies.'
def value_encode(self, val):
strval = str(val) return (strval, strval)
'Private method for setting a cookie\'s value'
def __set(self, key, real_value, coded_value):
M = self.get(key, Morsel()) M.set(key, real_value, coded_value) dict.__setitem__(self, key, M)
'Dictionary style assignment.'
def __setitem__(self, key, value):
(rval, cval) = self.value_encode(value) self.__set(key, rval, cval)
'Return a string suitable for HTTP.'
def output(self, attrs=None, header='Set-Cookie:', sep='\r\n'):
result = [] items = self.items() items.sort() for (K, V) in items: result.append(V.output(attrs, header)) return sep.join(result)
'Return a string suitable for JavaScript.'
def js_output(self, attrs=None):
result = [] items = self.items() items.sort() for (K, V) in items: result.append(V.js_output(attrs)) return _nulljoin(result)
'Load cookies from a string (presumably HTTP_COOKIE) or from a dictionary. Loading cookies from a dictionary \'d\' is equivalent to calling: map(Cookie.__setitem__, d.keys(), d.values())'
def load(self, rawdata):
if (type(rawdata) == type('')): self.__ParseString(rawdata) else: for (k, v) in rawdata.items(): self[k] = v return
'Remove current thread from the dict of currently running threads.'
def __delete(self):
try: with _active_limbo_lock: del _active[_get_ident()] except KeyError: if ('dummy_threading' not in _sys.modules): raise
'Stop the timer if it hasn\'t finished yet'
def cancel(self):
self.finished.set()
'Return a distinct copy of the current font'
def copy(self):
return Font(self._root, **self.actual())
'Return actual font attributes'
def actual(self, option=None):
if option: return self._call('font', 'actual', self.name, ('-' + option)) else: return self._mkdict(self._split(self._call('font', 'actual', self.name)))
'Get font attribute'
def cget(self, option):
return self._call('font', 'config', self.name, ('-' + option))
'Modify font attributes'
def config(self, **options):
if options: self._call('font', 'config', self.name, *self._set(options)) else: return self._mkdict(self._split(self._call('font', 'config', self.name)))
'Return text width'
def measure(self, text):
return int(self._call('font', 'measure', self.name, text))
'Return font metrics. For best performance, create a dummy widget using this font before calling this method.'
def metrics(self, *options):
if options: return int(self._call('font', 'metrics', self.name, self._get(options))) else: res = self._split(self._call('font', 'metrics', self.name)) options = {} for i in range(0, len(res), 2): options[res[i][1:]] = int(res[(i + 1)]) return options
'rotate self counterclockwise by angle'
def rotate(self, angle):
perp = Vec2D((- self[1]), self[0]) angle = ((angle * math.pi) / 180.0) (c, s) = (math.cos(angle), math.sin(angle)) return Vec2D(((self[0] * c) + (perp[0] * s)), ((self[1] * c) + (perp[1] * s)))
'Adjust canvas and scrollbars according to given canvas size.'
def reset(self, canvwidth=None, canvheight=None, bg=None):
if canvwidth: self.canvwidth = canvwidth if canvheight: self.canvheight = canvheight if bg: self.bg = bg self._canvas.config(bg=bg, scrollregion=(((- self.canvwidth) // 2), ((- self.canvheight) // 2), (self.canvwidth // 2), (self.canvheight // 2))) self._canvas.xview_moveto(((0.5 * ((self.canvwidth - self.width) + 30)) / self.canvwidth)) self._canvas.yview_moveto(((0.5 * ((self.canvheight - self.height) + 30)) / self.canvheight)) self.adjustScrolls()
'Adjust scrollbars according to window- and canvas-size.'
def adjustScrolls(self):
cwidth = self._canvas.winfo_width() cheight = self._canvas.winfo_height() self._canvas.xview_moveto(((0.5 * (self.canvwidth - cwidth)) / self.canvwidth)) self._canvas.yview_moveto(((0.5 * (self.canvheight - cheight)) / self.canvheight)) if ((cwidth < self.canvwidth) or (cheight < self.canvheight)): self.hscroll.grid(padx=1, in_=self, pady=1, row=1, column=0, rowspan=1, columnspan=1, sticky='news') self.vscroll.grid(padx=1, in_=self, pady=1, row=0, column=1, rowspan=1, columnspan=1, sticky='news') else: self.hscroll.grid_forget() self.vscroll.grid_forget()
'self-explanatory'
def onResize(self, event):
self.adjustScrolls()
'\'forward\' method, which canvas itself has inherited...'
def bbox(self, *args):
return self._canvas.bbox(*args)
'\'forward\' method, which canvas itself has inherited...'
def cget(self, *args, **kwargs):
return self._canvas.cget(*args, **kwargs)
'\'forward\' method, which canvas itself has inherited...'
def config(self, *args, **kwargs):
self._canvas.config(*args, **kwargs)
'\'forward\' method, which canvas itself has inherited...'
def bind(self, *args, **kwargs):
self._canvas.bind(*args, **kwargs)
'\'forward\' method, which canvas itself has inherited...'
def unbind(self, *args, **kwargs):
self._canvas.unbind(*args, **kwargs)
'\'forward\' method, which canvas itself has inherited...'
def focus_force(self):
self._canvas.focus_force()
'return a blank image object'
@staticmethod def _blankimage():
img = TK.PhotoImage(width=1, height=1) img.blank() return img
'return an image object containing the imagedata from a gif-file named filename.'
@staticmethod def _image(filename):
return TK.PhotoImage(file=filename)
'Create an invisible polygon item on canvas self.cv)'
def _createpoly(self):
return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill='', outline='')
'Configure polygonitem polyitem according to provided arguments: coordlist is sequence of coordinates fill is filling color outline is outline color top is a boolean value, which specifies if polyitem will be put on top of the canvas\' displaylist so it will not be covered by other items.'
def _drawpoly(self, polyitem, coordlist, fill=None, outline=None, width=None, top=False):
cl = [] for (x, y) in coordlist: cl.append((x * self.xscale)) cl.append(((- y) * self.yscale)) self.cv.coords(polyitem, *cl) if (fill is not None): self.cv.itemconfigure(polyitem, fill=fill) if (outline is not None): self.cv.itemconfigure(polyitem, outline=outline) if (width is not None): self.cv.itemconfigure(polyitem, width=width) if top: self.cv.tag_raise(polyitem)
'Create an invisible line item on canvas self.cv)'
def _createline(self):
return self.cv.create_line(0, 0, 0, 0, fill='', width=2, capstyle=TK.ROUND)
'Configure lineitem according to provided arguments: coordlist is sequence of coordinates fill is drawing color width is width of drawn line. top is a boolean value, which specifies if polyitem will be put on top of the canvas\' displaylist so it will not be covered by other items.'
def _drawline(self, lineitem, coordlist=None, fill=None, width=None, top=False):
if (coordlist is not None): cl = [] for (x, y) in coordlist: cl.append((x * self.xscale)) cl.append(((- y) * self.yscale)) self.cv.coords(lineitem, *cl) if (fill is not None): self.cv.itemconfigure(lineitem, fill=fill) if (width is not None): self.cv.itemconfigure(lineitem, width=width) if top: self.cv.tag_raise(lineitem)
'Delete graphics item from canvas. If item is"all" delete all graphics items.'
def _delete(self, item):
self.cv.delete(item)
'Redraw graphics items on canvas'
def _update(self):
self.cv.update()
'Delay subsequent canvas actions for delay ms.'
def _delay(self, delay):
self.cv.after(delay)
'Check if the string color is a legal Tkinter color string.'
def _iscolorstring(self, color):
try: rgb = self.cv.winfo_rgb(color) ok = True except TK.TclError: ok = False return ok
'Set canvas\' backgroundcolor if color is not None, else return backgroundcolor.'
def _bgcolor(self, color=None):
if (color is not None): self.cv.config(bg=color) self._update() else: return self.cv.cget('bg')
'Write txt at pos in canvas with specified font and color. Return text item and x-coord of right bottom corner of text\'s bounding box.'
def _write(self, pos, txt, align, font, pencolor):
(x, y) = pos x = (x * self.xscale) y = (y * self.yscale) anchor = {'left': 'sw', 'center': 's', 'right': 'se'} item = self.cv.create_text((x - 1), (- y), text=txt, anchor=anchor[align], fill=pencolor, font=font) (x0, y0, x1, y1) = self.cv.bbox(item) self.cv.update() return (item, (x1 - 1))
'Bind fun to mouse-click event on turtle. fun must be a function with two arguments, the coordinates of the clicked point on the canvas. num, the number of the mouse-button defaults to 1'
def _onclick(self, item, fun, num=1, add=None):
if (fun is None): self.cv.tag_unbind(item, ('<Button-%s>' % num)) else: def eventfun(event): (x, y) = ((self.cv.canvasx(event.x) / self.xscale), ((- self.cv.canvasy(event.y)) / self.yscale)) fun(x, y) self.cv.tag_bind(item, ('<Button-%s>' % num), eventfun, add)
'Bind fun to mouse-button-release event on turtle. fun must be a function with two arguments, the coordinates of the point on the canvas where mouse button is released. num, the number of the mouse-button defaults to 1 If a turtle is clicked, first _onclick-event will be performed, then _onscreensclick-event.'
def _onrelease(self, item, fun, num=1, add=None):
if (fun is None): self.cv.tag_unbind(item, ('<Button%s-ButtonRelease>' % num)) else: def eventfun(event): (x, y) = ((self.cv.canvasx(event.x) / self.xscale), ((- self.cv.canvasy(event.y)) / self.yscale)) fun(x, y) self.cv.tag_bind(item, ('<Button%s-ButtonRelease>' % num), eventfun, add)
'Bind fun to mouse-move-event (with pressed mouse button) on turtle. fun must be a function with two arguments, the coordinates of the actual mouse position on the canvas. num, the number of the mouse-button defaults to 1 Every sequence of mouse-move-events on a turtle is preceded by a mouse-click event on that turtle.'
def _ondrag(self, item, fun, num=1, add=None):
if (fun is None): self.cv.tag_unbind(item, ('<Button%s-Motion>' % num)) else: def eventfun(event): try: (x, y) = ((self.cv.canvasx(event.x) / self.xscale), ((- self.cv.canvasy(event.y)) / self.yscale)) fun(x, y) except: pass self.cv.tag_bind(item, ('<Button%s-Motion>' % num), eventfun, add)
'Bind fun to mouse-click event on canvas. fun must be a function with two arguments, the coordinates of the clicked point on the canvas. num, the number of the mouse-button defaults to 1 If a turtle is clicked, first _onclick-event will be performed, then _onscreensclick-event.'
def _onscreenclick(self, fun, num=1, add=None):
if (fun is None): self.cv.unbind(('<Button-%s>' % num)) else: def eventfun(event): (x, y) = ((self.cv.canvasx(event.x) / self.xscale), ((- self.cv.canvasy(event.y)) / self.yscale)) fun(x, y) self.cv.bind(('<Button-%s>' % num), eventfun, add)
'Bind fun to key-release event of key. Canvas must have focus. See method listen'
def _onkey(self, fun, key):
if (fun is None): self.cv.unbind(('<KeyRelease-%s>' % key), None) else: def eventfun(event): fun() self.cv.bind(('<KeyRelease-%s>' % key), eventfun)
'Set focus on canvas (in order to collect key-events)'
def _listen(self):
self.cv.focus_force()
'Install a timer, which calls fun after t milliseconds.'
def _ontimer(self, fun, t):
if (t == 0): self.cv.after_idle(fun) else: self.cv.after(t, fun)
'Create and return image item on canvas.'
def _createimage(self, image):
return self.cv.create_image(0, 0, image=image)
'Configure image item as to draw image object at position (x,y) on canvas)'
def _drawimage(self, item, (x, y), image):
self.cv.coords(item, ((x * self.xscale), ((- y) * self.yscale))) self.cv.itemconfig(item, image=image)
'Configure image item as to draw image object at center of canvas. Set item to the first item in the displaylist, so it will be drawn below any other item .'
def _setbgpic(self, item, image):
self.cv.itemconfig(item, image=image) self.cv.tag_lower(item)
'Return \'line\' or \'polygon\' or \'image\' depending on type of item.'
def _type(self, item):
return self.cv.type(item)
'returns list of coordinate-pairs of points of item Example (for insiders): >>> from turtle import * >>> getscreen()._pointlist(getturtle().turtle._item) [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982), (9.9999999999999982, 0.0)]'
def _pointlist(self, item):
cl = self.cv.coords(item) pl = [(cl[i], (- cl[(i + 1)])) for i in range(0, len(cl), 2)] return pl
'Resize the canvas the turtles are drawing on. Does not alter the drawing window.'
def _resize(self, canvwidth=None, canvheight=None, bg=None):
if (not isinstance(self.cv, ScrolledCanvas)): return (self.canvwidth, self.canvheight) if (canvwidth is canvheight is bg is None): return (self.cv.canvwidth, self.cv.canvheight) if (canvwidth is not None): self.canvwidth = canvwidth if (canvheight is not None): self.canvheight = canvheight self.cv.reset(canvwidth, canvheight, bg)
'Return the width and height of the turtle window.'
def _window_size(self):
width = self.cv.winfo_width() if (width <= 1): width = self.cv['width'] height = self.cv.winfo_height() if (height <= 1): height = self.cv['height'] return (width, height)
'Add component to a shape of type compound. Arguments: poly is a polygon, i. e. a tuple of number pairs. fill is the fillcolor of the component, outline is the outline color of the component. call (for a Shapeobject namend s): -- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue") Example: >>> poly = ((0,0),(10,-5),(0,10),(-10,-5)) >>> s = Shape("compound") >>> s.addcomponent(poly, "red", "blue") ### .. add more components and then use register_shape()'
def addcomponent(self, poly, fill, outline=None):
if (self._type != 'compound'): raise TurtleGraphicsError(('Cannot add component to %s Shape' % self._type)) if (outline is None): outline = fill self._data.append([poly, fill, outline])
'Delete all drawings and all turtles from the TurtleScreen. Reset empty TurtleScreen to its initial state: white background, no backgroundimage, no eventbindings and tracing on. No argument. Example (for a TurtleScreen instance named screen): screen.clear() Note: this method is not available as function.'
def clear(self):
self._delayvalue = _CFG['delay'] self._colormode = _CFG['colormode'] self._delete('all') self._bgpic = self._createimage('') self._bgpicname = 'nopic' self._tracing = 1 self._updatecounter = 0 self._turtles = [] self.bgcolor('white') for btn in (1, 2, 3): self.onclick(None, btn) for key in self._keys[:]: self.onkey(None, key) Turtle._pen = None
'Set turtle-mode (\'standard\', \'logo\' or \'world\') and perform reset. Optional argument: mode -- on of the strings \'standard\', \'logo\' or \'world\' Mode \'standard\' is compatible with turtle.py. Mode \'logo\' is compatible with most Logo-Turtle-Graphics. Mode \'world\' uses userdefined \'worldcoordinates\'. *Attention*: in this mode angles appear distorted if x/y unit-ratio doesn\'t equal 1. If mode is not given, return the current mode. Mode Initial turtle heading positive angles \'standard\' to the right (east) counterclockwise \'logo\' upward (north) clockwise Examples: >>> mode(\'logo\') # resets turtle heading to north >>> mode() \'logo\''
def mode(self, mode=None):
if (mode is None): return self._mode mode = mode.lower() if (mode not in ['standard', 'logo', 'world']): raise TurtleGraphicsError(('No turtle-graphics-mode %s' % mode)) self._mode = mode if (mode in ['standard', 'logo']): self._setscrollregion(((- self.canvwidth) // 2), ((- self.canvheight) // 2), (self.canvwidth // 2), (self.canvheight // 2)) self.xscale = self.yscale = 1.0 self.reset()
'Set up a user defined coordinate-system. Arguments: llx -- a number, x-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 ury -- a number, y-coordinate of upper right corner of canvas Set up user coodinat-system and switch to mode \'world\' if necessary. This performs a screen.reset. If mode \'world\' is already active, all drawings are redrawn according to the new coordinates. But ATTENTION: in user-defined coordinatesystems angles may appear distorted. (see Screen.mode()) Example (for a TurtleScreen instance named screen): >>> screen.setworldcoordinates(-10,-0.5,50,1.5) >>> for _ in range(36): left(10) forward(0.5)'
def setworldcoordinates(self, llx, lly, urx, ury):
if (self.mode() != 'world'): self.mode('world') xspan = float((urx - llx)) yspan = float((ury - lly)) (wx, wy) = self._window_size() self.screensize((wx - 20), (wy - 20)) (oldxscale, oldyscale) = (self.xscale, self.yscale) self.xscale = (self.canvwidth / xspan) self.yscale = (self.canvheight / yspan) srx1 = (llx * self.xscale) sry1 = ((- ury) * self.yscale) srx2 = (self.canvwidth + srx1) sry2 = (self.canvheight + sry1) self._setscrollregion(srx1, sry1, srx2, sry2) self._rescale((self.xscale / oldxscale), (self.yscale / oldyscale)) self.update()
'Adds a turtle shape to TurtleScreen\'s shapelist. Arguments: (1) name is the name of a gif-file and shape is None. Installs the corresponding image shape. !! Image-shapes DO NOT rotate when turning the turtle, !! so they do not display the heading of the turtle! (2) name is an arbitrary string and shape is a tuple of pairs of coordinates. Installs the corresponding polygon shape (3) name is an arbitrary string and shape is a (compound) Shape object. Installs the corresponding compound shape. To use a shape, you have to issue the command shape(shapename). call: register_shape("turtle.gif") --or: register_shape("tri", ((0,0), (10,10), (-10,10))) Example (for a TurtleScreen instance named screen): >>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3)))'
def register_shape(self, name, shape=None):
if (shape is None): if name.lower().endswith('.gif'): shape = Shape('image', self._image(name)) else: raise TurtleGraphicsError(('Bad arguments for register_shape.\n' + 'Use help(register_shape)')) elif isinstance(shape, tuple): shape = Shape('polygon', shape) self._shapes[name] = shape
'Return color string corresponding to args. Argument may be a string or a tuple of three numbers corresponding to actual colormode, i.e. in the range 0<=n<=colormode. If the argument doesn\'t represent a color, an error is raised.'
def _colorstr(self, color):
if (len(color) == 1): color = color[0] if isinstance(color, str): if (self._iscolorstring(color) or (color == '')): return color else: raise TurtleGraphicsError(('bad color string: %s' % str(color))) try: (r, g, b) = color except: raise TurtleGraphicsError(('bad color arguments: %s' % str(color))) if (self._colormode == 1.0): (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))): raise TurtleGraphicsError(('bad color sequence: %s' % str(color))) return ('#%02x%02x%02x' % (r, g, b))
'Return the colormode or set it to 1.0 or 255. Optional argument: cmode -- one of the values 1.0 or 255 r, g, b values of colortriples have to be in range 0..cmode. Example (for a TurtleScreen instance named screen): >>> screen.colormode() 1.0 >>> screen.colormode(255) >>> turtle.pencolor(240,160,80)'
def colormode(self, cmode=None):
if (cmode is None): return self._colormode if (cmode == 1.0): self._colormode = float(cmode) elif (cmode == 255): self._colormode = int(cmode)
'Reset all Turtles on the Screen to their initial state. No argument. Example (for a TurtleScreen instance named screen): >>> screen.reset()'
def reset(self):
for turtle in self._turtles: turtle._setmode(self._mode) turtle.reset()
'Return the list of turtles on the screen. Example (for a TurtleScreen instance named screen): >>> screen.turtles() [<turtle.Turtle object at 0x00E11FB0>]'
def turtles(self):
return self._turtles
'Set or return backgroundcolor of the TurtleScreen. Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. Example (for a TurtleScreen instance named screen): >>> screen.bgcolor("orange") >>> screen.bgcolor() \'orange\' >>> screen.bgcolor(0.5,0,0.5) >>> screen.bgcolor() \'#800080\''
def bgcolor(self, *args):
if args: color = self._colorstr(args) else: color = None color = self._bgcolor(color) if (color is not None): color = self._color(color) return color
'Turns turtle animation on/off and set delay for update drawings. Optional arguments: n -- nonnegative integer delay -- nonnegative integer If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) Second arguments sets delay value (see RawTurtle.delay()) Example (for a TurtleScreen instance named screen): >>> screen.tracer(8, 25) >>> dist = 2 >>> for i in range(200): fd(dist) rt(90) dist += 2'
def tracer(self, n=None, delay=None):
if (n is None): return self._tracing self._tracing = int(n) self._updatecounter = 0 if (delay is not None): self._delayvalue = int(delay) if self._tracing: self.update()
'Return or set the drawing delay in milliseconds. Optional argument: delay -- positive integer Example (for a TurtleScreen instance named screen): >>> screen.delay(15) >>> screen.delay() 15'
def delay(self, delay=None):
if (delay is None): return self._delayvalue self._delayvalue = int(delay)
'Increment upadate counter.'
def _incrementudc(self):
if (not TurtleScreen._RUNNING): TurtleScreen._RUNNNING = True raise Terminator if (self._tracing > 0): self._updatecounter += 1 self._updatecounter %= self._tracing
'Perform a TurtleScreen update.'
def update(self):
tracing = self._tracing self._tracing = True for t in self.turtles(): t._update_data() t._drawturtle() self._tracing = tracing self._update()
'Return the width of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_width() 640'
def window_width(self):
return self._window_size()[0]
'Return the height of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_height() 480'
def window_height(self):
return self._window_size()[1]
'Return the Canvas of this TurtleScreen. No argument. Example (for a Screen instance named screen): >>> cv = screen.getcanvas() >>> cv <turtle.ScrolledCanvas instance at 0x010742D8>'
def getcanvas(self):
return self.cv
'Return a list of names of all currently available turtle shapes. No argument. Example (for a TurtleScreen instance named screen): >>> screen.getshapes() [\'arrow\', \'blank\', \'circle\', ... , \'turtle\']'
def getshapes(self):
return sorted(self._shapes.keys())
'Bind fun to mouse-click event on canvas. Arguments: fun -- a function with two arguments, the coordinates of the clicked point on the canvas. num -- the number of the mouse-button, defaults to 1 Example (for a TurtleScreen instance named screen and a Turtle instance named turtle): >>> screen.onclick(turtle.goto) ### Subsequently clicking into the TurtleScreen will ### make the turtle move to the clicked point. >>> screen.onclick(None) ### event-binding will be removed'
def onclick(self, fun, btn=1, add=None):
self._onscreenclick(fun, btn, add)
'Bind fun to key-release event of key. Arguments: fun -- a function with no arguments key -- a string: key (e.g. "a") or key-symbol (e.g. "space") In order to be able to register key-events, TurtleScreen must have focus. (See method listen.) Example (for a TurtleScreen instance named screen and a Turtle instance named turtle): >>> def f(): fd(50) lt(60) >>> screen.onkey(f, "Up") >>> screen.listen() ### Subsequently the turtle can be moved by ### repeatedly pressing the up-arrow key, ### consequently drawing a hexagon'
def onkey(self, fun, key):
if (fun is None): if (key in self._keys): self._keys.remove(key) elif (key not in self._keys): self._keys.append(key) self._onkey(fun, key)
'Set focus on TurtleScreen (in order to collect key-events) No arguments. Dummy arguments are provided in order to be able to pass listen to the onclick method. Example (for a TurtleScreen instance named screen): >>> screen.listen()'
def listen(self, xdummy=None, ydummy=None):
self._listen()
'Install a timer, which calls fun after t milliseconds. Arguments: fun -- a function with no arguments. t -- a number >= 0 Example (for a TurtleScreen instance named screen): >>> running = True >>> def f(): if running: fd(50) lt(60) screen.ontimer(f, 250) >>> f() ### makes the turtle marching around >>> running = False'
def ontimer(self, fun, t=0):
self._ontimer(fun, t)
'Set background image or return name of current backgroundimage. Optional argument: picname -- a string, name of a gif-file or "nopic". If picname is a filename, set the corresponding image as background. If picname is "nopic", delete backgroundimage, if present. If picname is None, return the filename of the current backgroundimage. Example (for a TurtleScreen instance named screen): >>> screen.bgpic() \'nopic\' >>> screen.bgpic("landscape.gif") >>> screen.bgpic() \'landscape.gif\''
def bgpic(self, picname=None):
if (picname is None): return self._bgpicname if (picname not in self._bgpics): self._bgpics[picname] = self._image(picname) self._setbgpic(self._bgpic, self._bgpics[picname]) self._bgpicname = picname
'Resize the canvas the turtles are drawing on. Optional arguments: canvwidth -- positive integer, new width of canvas in pixels canvheight -- positive integer, new height of canvas in pixels bg -- colorstring or color-tuple, new backgroundcolor If no arguments are given, return current (canvaswidth, canvasheight) Do not alter the drawing window. To observe hidden parts of the canvas use the scrollbars. (Can make visible those parts of a drawing, which were outside the canvas before!) Example (for a Turtle instance named turtle): >>> turtle.screensize(2000,1500) ### e. g. to search for an erroneously escaped turtle ;-)'
def screensize(self, canvwidth=None, canvheight=None, bg=None):
return self._resize(canvwidth, canvheight, bg)
'reset turtle to its initial values Will be overwritten by parent class'
def reset(self):
self._position = Vec2D(0.0, 0.0) self._orient = TNavigator.START_ORIENTATION[self._mode]
'Set turtle-mode to \'standard\', \'world\' or \'logo\'.'
def _setmode(self, mode=None):
if (mode is None): return self._mode if (mode not in ['standard', 'logo', 'world']): return self._mode = mode if (mode in ['standard', 'world']): self._angleOffset = 0 self._angleOrient = 1 else: self._angleOffset = (self._fullcircle / 4.0) self._angleOrient = (-1)
'Helper function for degrees() and radians()'
def _setDegreesPerAU(self, fullcircle):
self._fullcircle = fullcircle self._degreesPerAU = (360 / fullcircle) if (self._mode == 'standard'): self._angleOffset = 0 else: self._angleOffset = (fullcircle / 4.0)
'Set angle measurement units to degrees. Optional argument: fullcircle - a number Set angle measurement units, i. e. set number of \'degrees\' for a full circle. Dafault value is 360 degrees. Example (for a Turtle instance named turtle): >>> turtle.left(90) >>> turtle.heading() 90 Change angle measurement unit to grad (also known as gon, grade, or gradian and equals 1/100-th of the right angle.) >>> turtle.degrees(400.0) >>> turtle.heading() 100'
def degrees(self, fullcircle=360.0):
self._setDegreesPerAU(fullcircle)
'Set the angle measurement units to radians. No arguments. Example (for a Turtle instance named turtle): >>> turtle.heading() 90 >>> turtle.radians() >>> turtle.heading() 1.5707963267948966'
def radians(self):
self._setDegreesPerAU((2 * math.pi))
'move turtle forward by specified distance'
def _go(self, distance):
ende = (self._position + (self._orient * distance)) self._goto(ende)
'Turn turtle counterclockwise by specified angle if angle > 0.'
def _rotate(self, angle):
angle *= self._degreesPerAU self._orient = self._orient.rotate(angle)
'move turtle to position end.'
def _goto(self, end):
self._position = end
'Move the turtle forward by the specified distance. Aliases: forward | fd Argument: distance -- a number (integer or float) Move the turtle forward by the specified distance, in the direction the turtle is headed. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)'
def forward(self, distance):
self._go(distance)
'Move the turtle backward by distance. Aliases: back | backward | bk Argument: distance -- a number Move the turtle backward by distance ,opposite to the direction the turtle is headed. Do not change the turtle\'s heading. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00, 0.00)'
def back(self, distance):
self._go((- distance))
'Turn turtle right by angle units. Aliases: right | rt Argument: angle -- a number (integer or float) Turn turtle right by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on mode. (See this.) Example (for a Turtle instance named turtle): >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.0'
def right(self, angle):
self._rotate((- angle))
'Turn turtle left by angle units. Aliases: left | lt Argument: angle -- a number (integer or float) Turn turtle left by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on mode. (See this.) Example (for a Turtle instance named turtle): >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.0'
def left(self, angle):
self._rotate(angle)
'Return the turtle\'s current location (x,y), as a Vec2D-vector. Aliases: pos | position No arguments. Example (for a Turtle instance named turtle): >>> turtle.pos() (0.00, 240.00)'
def pos(self):
return self._position
'Return the turtle\'s x coordinate. No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.xcor() 50.0'
def xcor(self):
return self._position[0]
'Return the turtle\'s y coordinate No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.ycor() 86.6025403784'
def ycor(self):
return self._position[1]
'Move turtle to an absolute position. Aliases: setpos | setposition | goto: Arguments: x -- a number or a pair/vector of numbers y -- a number None call: goto(x, y) # two coordinates --or: goto((x, y)) # a pair (tuple) of coordinates --or: goto(vec) # e.g. as returned by pos() Move turtle to an absolute position. If the pen is down, a line will be drawn. The turtle\'s orientation does not change. Example (for a Turtle instance named turtle): >>> tp = turtle.pos() >>> tp (0.00, 0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)'
def goto(self, x, y=None):
if (y is None): self._goto(Vec2D(*x)) else: self._goto(Vec2D(x, y))
'Move turtle to the origin - coordinates (0,0). No arguments. Move turtle to the origin - coordinates (0,0) and set its heading to its start-orientation (which depends on mode). Example (for a Turtle instance named turtle): >>> turtle.home()'
def home(self):
self.goto(0, 0) self.setheading(0)
'Set the turtle\'s first coordinate to x Argument: x -- a number (integer or float) Set the turtle\'s first coordinate to x, leave second coordinate unchanged. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 240.00) >>> turtle.setx(10) >>> turtle.position() (10.00, 240.00)'
def setx(self, x):
self._goto(Vec2D(x, self._position[1]))
'Set the turtle\'s second coordinate to y Argument: y -- a number (integer or float) Set the turtle\'s first coordinate to x, second coordinate remains unchanged. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00, -10.00)'
def sety(self, y):
self._goto(Vec2D(self._position[0], y))
'Return the distance from the turtle to (x,y) in turtle step units. Arguments: x -- a number or a pair/vector of numbers or a turtle instance y -- a number None None call: distance(x, y) # two coordinates --or: distance((x, y)) # a pair (tuple) of coordinates --or: distance(vec) # e.g. as returned by pos() --or: distance(mypen) # where mypen is another turtle Example (for a Turtle instance named turtle): >>> turtle.pos() (0.00, 0.00) >>> turtle.distance(30,40) 50.0 >>> pen = Turtle() >>> pen.forward(77) >>> turtle.distance(pen) 77.0'
def distance(self, x, y=None):
if (y is not None): pos = Vec2D(x, y) if isinstance(x, Vec2D): pos = x elif isinstance(x, tuple): pos = Vec2D(*x) elif isinstance(x, TNavigator): pos = x._position return abs((pos - self._position))