desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Verifies that subclassed cursor classes are correctly registered with the connection object, too. (fetch-across-rollback problem)'
def CheckCursorRegistration(self):
class Connection(sqlite.Connection, ): def cursor(self): return Cursor(self) class Cursor(sqlite.Cursor, ): def __init__(self, con): sqlite.Cursor.__init__(self, con) con = Connection(':memory:') cur = con.cursor() cur.execute('create table foo(x)') ...
'Verifies that creating a connection in autocommit mode works. 2.5.3 introduced a regression so that these could no longer be created.'
def CheckAutoCommit(self):
con = sqlite.connect(':memory:', isolation_level=None)
'Verifies that running a PRAGMA statement that does an autocommit does work. This did not work in 2.5.3/2.5.4.'
def CheckPragmaAutocommit(self):
cur = self.con.cursor() cur.execute('create table foo(bar)') cur.execute('insert into foo(bar) values (5)') cur.execute('pragma page_size') row = cur.fetchone()
'See http://bugs.python.org/issue7478 It was possible to successfully register callbacks that could not be hashed. Return codes of PyDict_SetItem were not checked properly.'
def CheckSetDict(self):
class NotHashable: def __call__(self, *args, **kw): pass def __hash__(self): raise TypeError() var = NotHashable() self.assertRaises(TypeError, self.con.create_function, var) self.assertRaises(TypeError, self.con.create_aggregate, var) self.assertRaises(TypeEr...
'Call a connection with a non-string SQL request: check error handling of the statement constructor.'
def CheckConnectionCall(self):
self.assertRaises(sqlite.Warning, self.con, 1)
'http://bugs.python.org/issue10811 Recursively using a cursor, such as when reusing it from a generator led to segfaults. Now we catch recursive cursor usage and raise a ProgrammingError.'
def CheckRecursiveCursorUse(self):
con = sqlite.connect(':memory:') cur = con.cursor() cur.execute('create table a (bar)') cur.execute('create table b (baz)') def foo(): cur.execute('insert into a (bar) values (?)', (1,)) (yield 1) with self.assertRaises(sqlite.ProgrammingError): ...
'http://bugs.python.org/issue14720 The microsecond parsing of convert_timestamp() should pad with zeros, since the microsecond string "456" actually represents "456000".'
def CheckConvertTimestampMicrosecondPadding(self):
con = sqlite.connect(':memory:', detect_types=sqlite.PARSE_DECLTYPES) cur = con.cursor() cur.execute('CREATE TABLE t (x TIMESTAMP)') cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 15:06:00.456')") cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 ...
'Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard...
def add_type(self, type, ext, strict=True):
self.types_map[strict][ext] = type exts = self.types_map_inv[strict].setdefault(type, []) if (ext not in exts): exts.append(ext)
'Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can\'t be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. c...
def guess_type(self, url, strict=True):
(scheme, url) = urllib.parse.splittype(url) if (scheme == 'data'): comma = url.find(',') if (comma < 0): return (None, None) semi = url.find(';', 0, comma) if (semi >= 0): type = url[:semi] else: type = url[:comma] if (('=' in t...
'Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot (\'.\'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type\' by guess_type(). O...
def guess_all_extensions(self, type, strict=True):
type = type.lower() extensions = self.types_map_inv[True].get(type, []) if (not strict): for ext in self.types_map_inv[False].get(type, []): if (ext not in extensions): extensions.append(ext) return extensions
'Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot (\'.\'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type\' by guess_type(). If no extension can be...
def guess_extension(self, type, strict=True):
extensions = self.guess_all_extensions(type, strict) if (not extensions): return None return extensions[0]
'Read a single mime.types-format file, specified by pathname. If strict is true, information will be added to list of standard types, else to the list of non-standard types.'
def read(self, filename, strict=True):
with open(filename, encoding='utf-8') as fp: self.readfp(fp, strict)
'Read a single mime.types-format file. If strict is true, information will be added to list of standard types, else to the list of non-standard types.'
def readfp(self, fp, strict=True):
while 1: line = fp.readline() if (not line): break words = line.split() for i in range(len(words)): if (words[i][0] == '#'): del words[i:] break if (not words): continue (type, suffixes) = (words[0], ...
'Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types.'
def read_windows_registry(self, strict=True):
if (not _winreg): return def enum_types(mimedb): i = 0 while True: try: ctype = _winreg.EnumKey(mimedb, i) except EnvironmentError: break else: (yield ctype) i += 1 with _winreg.OpenKey(_w...
'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((...
'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-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) ...
'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): s...
'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>'...
'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...
'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 _onkeyrelease(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)
'If key is given, bind fun to key-press event of key. Otherwise bind fun to any key-press. Canvas must have focus. See method listen.'
def _onkeypress(self, fun, key=None):
if (fun is None): if (key is None): self.cv.unbind('<KeyPress>', None) else: self.cv.unbind(('<KeyPress-%s>' % key), None) else: def eventfun(event): fun() if (key is None): self.cv.bind('<KeyPress>', eventfun) else: ...
'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, pos, image):
(x, y) = pos 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.canvh...
'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)
'Starts event loop - calling Tkinter\'s mainloop function. No argument. Must be last statement in a turtle graphics program. Must NOT be used if a script is run from within IDLE in -n mode (No subprocess) - for interactive use of turtle graphics. Example (for a TurtleScreen instance named screen): >>> screen.mainloop()...
def mainloop(self):
TK.mainloop()
'Pop up a dialog window for input of a string. Arguments: title is the title of the dialog window, prompt is a text mostly describing what information to input. Return the string input If the dialog is canceled, return None. Example (for a TurtleScreen instance named screen): >>> screen.textinput("NIM", "Name of first ...
def textinput(self, title, prompt):
return simpledialog.askstring(title, prompt)
'Pop up a dialog window for input of a number. Arguments: title is the title of the dialog window, prompt is a text mostly describing what numerical information to input. default: default value minval: minimum value for imput maxval: maximum value for input The number input must be in the range minval .. maxval if thes...
def numinput(self, title, prompt, default=None, minval=None, maxval=None):
return simpledialog.askfloat(title, prompt, initialvalue=default, minvalue=minval, maxvalue=maxval)
'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...
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. No argument. Reset empty TurtleScreen to its initial state: white background, no backgroundimage, no eventbindings and tracing on. 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(Non...
'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\'. *At...
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)...
'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-...
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 = (sel...
'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 ...
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('poly...
'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: ...
'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) >>> 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.bgco...
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 RawTu...
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 update 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) >>> screen.onclick(goto) >>> # Subsequently clicking into the TurtleScree...
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): >>> def f(): ... fd(50...
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._onkeyrelease(fun, key)
'Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given. 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 Tur...
def onkeypress(self, fun, key=None):
if (fun is None): if (key in self._keys): self._keys.remove(key) elif ((key is not None) and (key not in self._keys)): self._keys.append(key) self._onkeypress(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() ...
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 b...
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 n...
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._angle...
'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...
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) >>...
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.backw...
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): >...
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): >>> ...
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(...
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: ...
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))
'Return the angle of the line from the turtle\'s position to (x, y). 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:...
def towards(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 (x, y) = (pos - self._position) result = (round(((math.atan2(y, x) * 180.0) / math.pi), 10) % 360.0)...