Commit 8718459f authored by Martin v. Löwis's avatar Martin v. Löwis

Patch #1513695: New turtle module, with demos.

parent 4ed3ed13
========================================================
A new turtle module for Python
========================================================
Turtle graphics is a popular way for introducing programming to
kids. It was part of the original Logo programming language developed
by Wally Feurzig and Seymour Papert in 1966.
Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it
the 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 the
command turtle.left(25), and it rotates in-place 25 degrees clockwise.
By combining together these and similar commands, intricate shapes and
pictures can easily be drawn.
----- turtle.py
This module is an extended reimplementation of turtle.py from the
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%
compatible with it. This means in the first place to enable the
learning programmer to use all the commands, classes and methods
interactively when using the module from within IDLE run with
the -n switch.
Roughly it has the following features added:
- Better animation of the turtle movements, especially of turning the
turtle. So the turtles can more easily be used as a visual feedback
instrument by the (beginning) programmer.
- Different turtle shapes, gif-images as turtle shapes, user defined
and user controllable turtle shapes, among them compound
(multicolored) shapes. Turtle shapes can be stgretched and tilted, which
makes turtles zu very versatile geometrical objects.
- Fine control over turtle movement and screen updates via delay(),
and enhanced tracer() and speed() methods.
- Aliases for the most commonly used commands, like fd for forward etc.,
following the early Logo traditions. This reduces the boring work of
typing long sequences of commands, which often occur in a natural way
when kids try to program fancy pictures on their first encounter with
turtle graphcis.
- Turtles now have an undo()-method with configurable undo-buffer.
- Some simple commands/methods for creating event driven programs
(mouse-, key-, timer-events). Especially useful for programming games.
- A scrollable Canvas class. The default scrollable Canvas can be
extended interactively as needed while playing around with the turtle(s).
- A TurtleScreen class with methods controlling background color or
background image, window and canvas size and other properties of the
TurtleScreen.
- There is a method, setworldcoordinates(), to install a user defined
coordinate-system for the TurtleScreen.
- 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,
which makes certain types of computations very natural and compact.
- Appearance of the TurtleScreen and the Turtles at startup/import can be
configured by means of a turtle.cfg configuration file.
The default configuration mimics the appearance of the old turtle module.
- If configured appropriately the module reads in docstrings from a docstring
dictionary in some different language, supplied separately and replaces
the english ones by those read in. There is a utility function
write_docstringdict() to write a dictionary with the original (english)
docstrings to disc, so it can serve as a template for translations.
--------------------------------------
About xturtleDemo.py
--------------------------------------
Tiny demo Viewer to view turtle graphics example scripts.
Quickly and dirtyly assembled by Gregor Lingl.
June, 2006
For more information see: xturtleDemo - Help
Have fun!
----------------------------------------------
xturtleDemo - Help
----------------------------------------------
This document has two sections:
(1) How to use the demo viewer
(2) How to add your own demos to the demo repository
(1) How to use the demo viewer.
Select a demoscript from the example menu.
The (syntax coloured) source code appears in the left
source code window. IT CANNOT BE EDITED, but ONLY VIEWED!
- Press START button to start the demo.
- Stop execution by pressing the STOP button.
- Clear screen by pressing the CLEAR button.
- Restart by pressing the START button again.
SPECIAL demos are those which run EVENTDRIVEN.
(For example clock.py - or oldTurtleDemo.py which
in the end expects a mouse click.):
Press START button to start the demo.
- Until the EVENTLOOP is entered everything works
as in an ordinary demo script.
- When the EVENTLOOP is entered, you control the
application by using the mouse and/or keys (or it's
controlled by some timer events)
To stop it you can and must press the STOP button.
While the EVENTLOOP is running, the examples menu is disabled.
- Only after having pressed the STOP button, you may
restart it or choose another example script.
* * * * * * * *
In some rare situations there may occur interferences/conflicts
between events concerning the demo script and those concerning the
demo-viewer. (They run in the same process.) Strange behaviour may be
the consequence and in the worst case you must close and restart the
viewer.
* * * * * * * *
(2) How to add your own demos to the demo repository
- scriptname: must begin with tdemo_ ,
so it must have the form tdemo_<your-script-name>.py
- place: same directory as xturtleDemo.py or some
subdirectory, the name of which must also begin with
tdemo_.....
- requirements on source code:
code must contain a main() function which will
be executed by the viewer (see provided example scripts)
main() may return a string which will be displayed
in the Label below the source code window (when execution
has finished.)
!! For programs, which are EVENT DRIVEN, main must return
!! the string "EVENTLOOP". This informs the viewer, that the
!! script is still running and must be stopped by the user!
#!/usr/bin/python
""" turtle-example-suite:
tdemo-I_dont_like_tiltdemo.py
Demostrates
(a) use of a tilted ellipse as
turtle shape
(b) stamping that shape
We can remove it, if you don't like it.
Without using reset() ;-)
---------------------------------------
"""
from turtle import *
import time
def main():
reset()
shape("circle")
resizemode("user")
pu(); bk(24*18/6.283); rt(90); pd()
tilt(45)
pu()
turtlesize(16,10,5)
color("red", "violet")
for i in range(18):
fd(24)
lt(20)
stamp()
color("red", "")
for i in range(18):
fd(24)
lt(20)
stamp()
tilt(-15)
turtlesize(3, 1, 4)
color("blue", "yellow")
for i in range(17):
fd(24)
lt(20)
if i%2 == 0:
stamp()
time.sleep(1)
while undobufferentries():
undo()
ht()
write("OK, OVER!", align="center", font=("Courier", 18, "bold"))
return "Done!"
if __name__=="__main__":
msg = main()
print msg
mainloop()
#!/usr/bin/python
""" turtle-example-suite:
tdemo_bytedesign.py
An example adapted from the example-suite
of PythonCard's turtle graphcis.
It's based on an article in BYTE magazine
Problem Solving with Logo: Using Turtle
Graphics to Redraw a Design
November 1982, p. 118 - 134
-------------------------------------------
Due to the statement
t.delay(0)
in line 152, which sets the animation delay
to 0, this animation runs in "line per line"
mode as fast as possible.
"""
import math
from turtle import Turtle, mainloop
from time import clock
# wrapper for any additional drawing routines
# that need to know about each other
class Designer(Turtle):
def design(self, homePos, scale):
self.up()
for i in range(5):
self.forward(64.65 * scale)
self.down()
self.wheel(self.position(), scale)
self.up()
self.backward(64.65 * scale)
self.right(72)
self.up()
self.goto(homePos)
self.right(36)
self.forward(24.5 * scale)
self.right(198)
self.down()
self.centerpiece(46 * scale, 143.4, scale)
self.tracer(True)
def wheel(self, initpos, scale):
self.right(54)
for i in range(4):
self.pentpiece(initpos, scale)
self.down()
self.left(36)
for i in range(5):
self.tripiece(initpos, scale)
self.left(36)
for i in range(5):
self.down()
self.right(72)
self.forward(28 * scale)
self.up()
self.backward(28 * scale)
self.left(54)
self.getscreen().update()
def tripiece(self, initpos, scale):
oldh = self.heading()
self.down()
self.backward(2.5 * scale)
self.tripolyr(31.5 * scale, scale)
self.up()
self.goto(initpos)
self.setheading(oldh)
self.down()
self.backward(2.5 * scale)
self.tripolyl(31.5 * scale, scale)
self.up()
self.goto(initpos)
self.setheading(oldh)
self.left(72)
self.getscreen().update()
def pentpiece(self, initpos, scale):
oldh = self.heading()
self.up()
self.forward(29 * scale)
self.down()
for i in range(5):
self.forward(18 * scale)
self.right(72)
self.pentr(18 * scale, 75, scale)
self.up()
self.goto(initpos)
self.setheading(oldh)
self.forward(29 * scale)
self.down()
for i in range(5):
self.forward(18 * scale)
self.right(72)
self.pentl(18 * scale, 75, scale)
self.up()
self.goto(initpos)
self.setheading(oldh)
self.left(72)
self.getscreen().update()
def pentl(self, side, ang, scale):
if side < (2 * scale): return
self.forward(side)
self.left(ang)
self.pentl(side - (.38 * scale), ang, scale)
def pentr(self, side, ang, scale):
if side < (2 * scale): return
self.forward(side)
self.right(ang)
self.pentr(side - (.38 * scale), ang, scale)
def tripolyr(self, side, scale):
if side < (4 * scale): return
self.forward(side)
self.right(111)
self.forward(side / 1.78)
self.right(111)
self.forward(side / 1.3)
self.right(146)
self.tripolyr(side * .75, scale)
def tripolyl(self, side, scale):
if side < (4 * scale): return
self.forward(side)
self.left(111)
self.forward(side / 1.78)
self.left(111)
self.forward(side / 1.3)
self.left(146)
self.tripolyl(side * .75, scale)
def centerpiece(self, s, a, scale):
self.forward(s); self.left(a)
if s < (7.5 * scale):
return
self.centerpiece(s - (1.2 * scale), a, scale)
def main():
t = Designer()
t.speed(0)
t.hideturtle()
t.getscreen().delay(0)
t.tracer(0)
at = clock()
t.design(t.position(), 2)
et = clock()
return "runtime: %.2f sec." % (et-at)
if __name__ == '__main__':
msg = main()
print msg
mainloop()
# Datei: chaosplotter.py
# Autor: Gregor Lingl
# Datum: 31. 5. 2008
# Ein einfaches Programm zur Demonstration von "chaotischem Verhalten".
from turtle import *
def f(x):
return 3.9*x*(1-x)
def g(x):
return 3.9*(x-x**2)
def h(x):
return 3.9*x-3.9*x*x
def coosys():
penup()
goto(-1,0)
pendown()
goto(n+1,0)
penup()
goto(0, -0.1)
pendown()
goto(-0.1, 1.1)
def plot(fun, start, farbe):
x = start
pencolor(farbe)
penup()
goto(0, x)
pendown()
dot(5)
for i in range(n):
x=fun(x)
goto(i+1,x)
dot(5)
def main():
global n
n = 80
ox=-250.0
oy=-150.0
ex= -2.0*ox / n
ey=300.0
reset()
setworldcoordinates(-1.0,-0.1, n+1, 1.1)
speed(0)
hideturtle()
coosys()
plot(f, 0.35, "blue")
plot(g, 0.35, "green")
plot(h, 0.35, "red")
for s in range(100):
setworldcoordinates(0.5*s,-0.1, n+1, 1.1)
return "Done!"
if __name__ == "__main__":
main()
mainloop()
#!/usr/bin/python
# -*- coding: cp1252 -*-
""" turtle-example-suite:
tdemo_clock.py
Enhanced clock-program, showing date
and time
------------------------------------
Press STOP to exit the program!
------------------------------------
"""
from turtle import *
from datetime import datetime
mode("logo")
def jump(distanz, winkel=0):
penup()
right(winkel)
forward(distanz)
left(winkel)
pendown()
def hand(laenge, spitze):
fd(laenge*1.15)
rt(90)
fd(spitze/2.0)
lt(120)
fd(spitze)
lt(120)
fd(spitze)
lt(120)
fd(spitze/2.0)
def make_hand_shape(name, laenge, spitze):
reset()
jump(-laenge*0.15)
begin_poly()
hand(laenge, spitze)
end_poly()
hand_form = get_poly()
register_shape(name, hand_form)
def clockface(radius):
reset()
pensize(7)
for i in range(60):
jump(radius)
if i % 5 == 0:
fd(25)
jump(-radius-25)
else:
dot(3)
jump(-radius)
rt(6)
def setup():
global second_hand, minute_hand, hour_hand, writer
mode("logo")
make_hand_shape("second_hand", 125, 25)
make_hand_shape("minute_hand", 130, 25)
make_hand_shape("hour_hand", 90, 25)
clockface(160)
second_hand = Turtle()
second_hand.shape("second_hand")
second_hand.color("gray20", "gray80")
minute_hand = Turtle()
minute_hand.shape("minute_hand")
minute_hand.color("blue1", "red1")
hour_hand = Turtle()
hour_hand.shape("hour_hand")
hour_hand.color("blue3", "red3")
for hand in second_hand, minute_hand, hour_hand:
hand.resizemode("user")
hand.shapesize(1, 1, 3)
hand.speed(0)
ht()
writer = Turtle()
#writer.mode("logo")
writer.ht()
writer.pu()
writer.bk(85)
def wochentag(t):
wochentag = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"]
return wochentag[t.weekday()]
def datum(z):
monat = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "June",
"July", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."]
j = z.year
m = monat[z.month - 1]
t = z.day
return "%s %d %d" % (m, t, j)
def tick():
t = datetime.today()
sekunde = t.second + t.microsecond*0.000001
minute = t.minute + sekunde/60.0
stunde = t.hour + minute/60.0
tracer(False)
writer.clear()
writer.home()
writer.forward(65)
writer.write(wochentag(t),
align="center", font=("Courier", 14, "bold"))
writer.back(150)
writer.write(datum(t),
align="center", font=("Courier", 14, "bold"))
writer.forward(85)
tracer(True)
second_hand.setheading(6*sekunde)
minute_hand.setheading(6*minute)
hour_hand.setheading(30*stunde)
tracer(True)
ontimer(tick, 100)
def main():
tracer(False)
setup()
tracer(True)
tick()
return "EVENTLOOP"
if __name__ == "__main__":
msg = main()
print msg
mainloop()
# colormixer
from turtle import Screen, Turtle, mainloop
class ColorTurtle(Turtle):
def __init__(self, x, y):
Turtle.__init__(self)
self.shape("turtle")
self.resizemode("user")
self.shapesize(3,3,5)
self.pensize(10)
self._color = [0,0,0]
self.x = x
self._color[x] = y
self.color(self._color)
self.speed(0)
self.left(90)
self.pu()
self.goto(x,0)
self.pd()
self.sety(1)
self.pu()
self.sety(y)
self.pencolor("gray25")
self.ondrag(self.shift)
def shift(self, x, y):
self.sety(max(0,min(y,1)))
self._color[self.x] = self.ycor()
self.fillcolor(self._color)
setbgcolor()
def setbgcolor():
screen.bgcolor(red.ycor(), green.ycor(), blue.ycor())
def main():
global screen, red, green, blue
screen = Screen()
screen.delay(0)
screen.setworldcoordinates(-1, -0.3, 3, 1.3)
red = ColorTurtle(0, .5)
green = ColorTurtle(1, .5)
blue = ColorTurtle(2, .5)
setbgcolor()
writer = Turtle()
writer.ht()
writer.pu()
writer.goto(1,1.15)
writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic")))
return "EVENTLOOP"
if __name__ == "__main__":
msg = main()
print msg
mainloop()
#!/usr/bin/python
""" turtle-example-suite:
tdemo_fractalCurves.py
This program draws two fractal-curve-designs:
(1) A hilbert curve (in a box)
(2) A combination of Koch-curves.
The CurvesTurtle class and the fractal-curve-
methods are taken from the PythonCard example
scripts for turtle-graphics.
"""
from turtle import *
from time import sleep, clock
class CurvesTurtle(Pen):
# example derived from
# Turtle Geometry: The Computer as a Medium for Exploring Mathematics
# by Harold Abelson and Andrea diSessa
# p. 96-98
def hilbert(self, size, level, parity):
if level == 0:
return
# rotate and draw first subcurve with opposite parity to big curve
self.left(parity * 90)
self.hilbert(size, level - 1, -parity)
# interface to and draw second subcurve with same parity as big curve
self.forward(size)
self.right(parity * 90)
self.hilbert(size, level - 1, parity)
# third subcurve
self.forward(size)
self.hilbert(size, level - 1, parity)
# fourth subcurve
self.right(parity * 90)
self.forward(size)
self.hilbert(size, level - 1, -parity)
# a final turn is needed to make the turtle
# end up facing outward from the large square
self.left(parity * 90)
# Visual Modeling with Logo: A Structural Approach to Seeing
# by James Clayson
# Koch curve, after Helge von Koch who introduced this geometric figure in 1904
# p. 146
def fractalgon(self, n, rad, lev, dir):
import math
# if dir = 1 turn outward
# if dir = -1 turn inward
edge = 2 * rad * math.sin(math.pi / n)
self.pu()
self.fd(rad)
self.pd()
self.rt(180 - (90 * (n - 2) / n))
for i in range(n):
self.fractal(edge, lev, dir)
self.rt(360 / n)
self.lt(180 - (90 * (n - 2) / n))
self.pu()
self.bk(rad)
self.pd()
# p. 146
def fractal(self, dist, depth, dir):
if depth < 1:
self.fd(dist)
return
self.fractal(dist / 3, depth - 1, dir)
self.lt(60 * dir)
self.fractal(dist / 3, depth - 1, dir)
self.rt(120 * dir)
self.fractal(dist / 3, depth - 1, dir)
self.lt(60 * dir)
self.fractal(dist / 3, depth - 1, dir)
def main():
ft = CurvesTurtle()
ft.reset()
ft.speed(0)
ft.ht()
ft.tracer(1,0)
ft.pu()
size = 6
ft.setpos(-33*size, -32*size)
ft.pd()
ta=clock()
ft.fillcolor("red")
ft.fill(True)
ft.fd(size)
ft.hilbert(size, 6, 1)
# frame
ft.fd(size)
for i in range(3):
ft.lt(90)
ft.fd(size*(64+i%2))
ft.pu()
for i in range(2):
ft.fd(size)
ft.rt(90)
ft.pd()
for i in range(4):
ft.fd(size*(66+i%2))
ft.rt(90)
ft.fill(False)
tb=clock()
res = "Hilbert: %.2fsec. " % (tb-ta)
sleep(3)
ft.reset()
ft.speed(0)
ft.ht()
ft.tracer(1,0)
ta=clock()
ft.color("black", "blue")
ft.fill(True)
ft.fractalgon(3, 250, 4, 1)
ft.fill(True)
ft.color("red")
ft.fractalgon(3, 200, 4, -1)
ft.fill(False)
tb=clock()
res += "Koch: %.2fsec." % (tb-ta)
return res
if __name__ == '__main__':
msg = main()
print msg
mainloop()
#!/usr/bin/python
""" turtle-example-suite:
xtx_lindenmayer_indian.py
Each morning women in Tamil Nadu, in southern
India, place designs, created by using rice
flour and known as kolam on the thresholds of
their homes.
These can be described by Lindenmayer systems,
which can easily be implemented with turtle
graphics and Python.
Two examples are shown here:
(1) the snake kolam
(2) anklets of Krishna
Taken from Marcia Ascher: Mathematics
Elsewhere, An Exploration of Ideas Across
Cultures
"""
################################
# Mini Lindenmayer tool
###############################
from turtle import *
def replace( seq, replacementRules, n ):
for i in range(n):
newseq = ""
for element in seq:
newseq = newseq + replacementRules.get(element,element)
seq = newseq
return seq
def draw( commands, rules ):
for b in commands:
try:
rules[b]()
except TypeError:
try:
draw(rules[b], rules)
except:
pass
def main():
################################
# Example 1: Snake kolam
################################
def r():
right(45)
def l():
left(45)
def f():
forward(7.5)
snake_rules = {"-":r, "+":l, "f":f, "b":"f+f+f--f--f+f+f"}
snake_replacementRules = {"b": "b+f+b--f--b+f+b"}
snake_start = "b--f--b--f"
drawing = replace(snake_start, snake_replacementRules, 3)
reset()
speed(3)
tracer(1,0)
ht()
up()
backward(195)
down()
draw(drawing, snake_rules)
from time import sleep
sleep(3)
################################
# Example 2: Anklets of Krishna
################################
def A():
color("red")
circle(10,90)
def B():
from math import sqrt
color("black")
l = 5/sqrt(2)
forward(l)
circle(l, 270)
forward(l)
def F():
color("green")
forward(10)
krishna_rules = {"a":A, "b":B, "f":F}
krishna_replacementRules = {"a" : "afbfa", "b" : "afbfbfbfa" }
krishna_start = "fbfbfbfb"
reset()
speed(0)
tracer(3,0)
ht()
left(45)
drawing = replace(krishna_start, krishna_replacementRules, 3)
draw(drawing, krishna_rules)
tracer(1)
return "Done!"
if __name__=='__main__':
msg = main()
print msg
mainloop()
#!/usr/bin/python
""" turtle-example-suite:
tdemo_minimal_hanoi.py
A minimal 'Towers of Hanoi' animation:
A tower of 6 discs is transferred from the
left to the right peg.
An imho quite elegant and concise
implementation using a tower class, which
is derived from the built-in type list.
Discs are turtles with shape "square", but
stretched to rectangles by shapesize()
---------------------------------------
To exit press STOP button
---------------------------------------
"""
from turtle import *
class Disc(Turtle):
def __init__(self, n):
Turtle.__init__(self, shape="square", visible=False)
self.pu()
self.shapesize(1.5, n*1.5, 2) # square-->rectangle
self.fillcolor(n/6., 0, 1-n/6.)
self.st()
class Tower(list):
"Hanoi tower, a subclass of built-in type list"
def __init__(self, x):
"create an empty tower. x is x-position of peg"
self.x = x
def push(self, d):
d.setx(self.x)
d.sety(-150+34*len(self))
self.append(d)
def pop(self):
d = list.pop(self)
d.sety(150)
return d
def hanoi(n, from_, with_, to_):
if n > 0:
hanoi(n-1, from_, to_, with_)
to_.push(from_.pop())
hanoi(n-1, with_, from_, to_)
def play():
onkey(None,"space")
clear()
hanoi(6, t1, t2, t3)
write("press STOP button to exit",
align="center", font=("Courier", 16, "bold"))
def main():
global t1, t2, t3
ht(); penup(); goto(0, -225) # writer turtle
t1 = Tower(-250)
t2 = Tower(0)
t3 = Tower(250)
# make tower of 6 discs
for i in range(6,0,-1):
t1.push(Disc(i))
# prepare spartanic user interface ;-)
write("press spacebar to start game",
align="center", font=("Courier", 16, "bold"))
onkey(play, "space")
listen()
return "EVENTLOOP"
if __name__=="__main__":
msg = main()
print msg
mainloop()
#!/usr/bin/python
""" turtle-example-suite:
tdemo_paint.py
A simple eventdriven paint program
- use left mouse button to move turtle
- middle mouse button to change color
- right mouse button do turn filling on/off
-------------------------------------------
Play around by clicking into the canvas
using all three mouse buttons.
-------------------------------------------
To exit press STOP button
-------------------------------------------
"""
from turtle import *
def switchupdown(x=0, y=0):
if pen()["pendown"]:
end_fill()
up()
else:
down()
begin_fill()
def changecolor(x=0, y=0):
global colors
colors = colors[1:]+colors[:1]
color(colors[0])
def main():
global colors
shape("circle")
resizemode("user")
shapesize(.5)
width(3)
colors=["red", "green", "blue", "yellow"]
color(colors[0])
switchupdown()
onscreenclick(goto,1)
onscreenclick(changecolor,2)
onscreenclick(switchupdown,3)
return "EVENTLOOP"
if __name__ == "__main__":
msg = main()
print msg
mainloop()
#!/usr/bin/python
""" turtle-example-suite:
tdemo_peace.py
A very simple drawing suitable as a beginner's
programming example.
Uses only commands, which are also available in
old turtle.py.
Intentionally no variables are used except for the
colorloop:
"""
from turtle import *
def main():
peacecolors = ("red3", "orange", "yellow",
"seagreen4", "orchid4",
"royalblue1", "dodgerblue4")
reset()
s = Screen()
up()
goto(-320,-195)
width(70)
for pcolor in peacecolors:
color(pcolor)
down()
forward(640)
up()
backward(640)
left(90)
forward(66)
right(90)
width(25)
color("white")
goto(0,-170)
down()
circle(170)
left(90)
forward(340)
up()
left(180)
forward(170)
right(45)
down()
forward(170)
up()
backward(170)
left(90)
down()
forward(170)
up()
goto(0,300) # vanish if hideturtle() is not available ;-)
return "Done!!"
if __name__ == "__main__":
main()
mainloop()
#!/usr/bin/python
""" xturtle-example-suite:
xtx_kites_and_darts.py
Constructs two aperiodic penrose-tilings,
consisting of kites and darts, by the method
of inflation in six steps.
Starting points are the patterns "sun"
consisting of five kites and "star"
consisting of five darts.
For more information see:
http://en.wikipedia.org/wiki/Penrose_tiling
-------------------------------------------
"""
from turtle import *
from math import cos, pi
from time import clock, sleep
f = (5**0.5-1)/2.0 # (sqrt(5)-1)/2 -- golden ratio
d = 2 * cos(3*pi/10)
def kite(l):
fl = f * l
lt(36)
fd(l)
rt(108)
fd(fl)
rt(36)
fd(fl)
rt(108)
fd(l)
rt(144)
def dart(l):
fl = f * l
lt(36)
fd(l)
rt(144)
fd(fl)
lt(36)
fd(fl)
rt(144)
fd(l)
rt(144)
def inflatekite(l, n):
if n == 0:
px, py = pos()
h, x, y = int(heading()), round(px,3), round(py,3)
tiledict[(h,x,y)] = True
return
fl = f * l
lt(36)
inflatedart(fl, n-1)
fd(l)
rt(144)
inflatekite(fl, n-1)
lt(18)
fd(l*d)
rt(162)
inflatekite(fl, n-1)
lt(36)
fd(l)
rt(180)
inflatedart(fl, n-1)
lt(36)
def inflatedart(l, n):
if n == 0:
px, py = pos()
h, x, y = int(heading()), round(px,3), round(py,3)
tiledict[(h,x,y)] = False
return
fl = f * l
inflatekite(fl, n-1)
lt(36)
fd(l)
rt(180)
inflatedart(fl, n-1)
lt(54)
fd(l*d)
rt(126)
inflatedart(fl, n-1)
fd(l)
rt(144)
def draw(l, n, th=2):
clear()
l = l * f**n
shapesize(l/100.0, l/100.0, th)
for k in tiledict:
h, x, y = k
setpos(x, y)
setheading(h)
if tiledict[k]:
shape("kite")
color("black", (0, 0.75, 0))
else:
shape("dart")
color("black", (0.75, 0, 0))
stamp()
def sun(l, n):
for i in range(5):
inflatekite(l, n)
lt(72)
def star(l,n):
for i in range(5):
inflatedart(l, n)
lt(72)
def makeshapes():
tracer(0)
begin_poly()
kite(100)
end_poly()
register_shape("kite", get_poly())
begin_poly()
dart(100)
end_poly()
register_shape("dart", get_poly())
tracer(1)
def start():
reset()
ht()
pu()
makeshapes()
resizemode("user")
def test(l=200, n=4, fun=sun, startpos=(0,0), th=2):
global tiledict
goto(startpos)
setheading(0)
tiledict = {}
a = clock()
tracer(0)
fun(l, n)
b = clock()
draw(l, n, th)
tracer(1)
c = clock()
print "Calculation: %7.4f s" % (b - a)
print "Drawing: %7.4f s" % (c - b)
print "Together: %7.4f s" % (c - a)
nk = len([x for x in tiledict if tiledict[x]])
nd = len([x for x in tiledict if not tiledict[x]])
print "%d kites and %d darts = %d pieces." % (nk, nd, nk+nd)
def demo(fun=sun):
start()
for i in range(8):
a = clock()
test(300, i, fun)
b = clock()
t = b - a
if t < 2:
sleep(2 - t)
def main():
#title("Penrose-tiling with kites and darts.")
mode("logo")
bgcolor(0.3, 0.3, 0)
demo(sun)
sleep(2)
demo(star)
pencolor("black")
goto(0,-200)
pencolor(0.7,0.7,1)
write("Please wait...",
align="center", font=('Arial Black', 36, 'bold'))
test(600, 8, startpos=(70, 117))
return "Done"
if __name__ == "__main__":
msg = main()
mainloop()
#!/usr/bin/python
""" turtle-example-suite:
tdemo_planets_and_moon.py
Gravitational system simulation using the
approximation method from Feynman-lectures,
p.9-8, using turtlegraphics.
Example: heavy central body, light planet,
very light moon!
Planet has a circular orbit, moon a stable
orbit around the planet.
You can hold the movement temporarily by pressing
the left mouse button with mouse over the
scrollbar of the canvas.
"""
from turtle import Shape, Turtle, mainloop, Vec2D as Vec
from time import sleep
G = 8
class GravSys(object):
def __init__(self):
self.planets = []
self.t = 0
self.dt = 0.01
def init(self):
for p in self.planets:
p.init()
def start(self):
for i in range(10000):
self.t += self.dt
for p in self.planets:
p.step()
class Star(Turtle):
def __init__(self, m, x, v, gravSys, shape):
Turtle.__init__(self, shape=shape)
self.penup()
self.m = m
self.setpos(x)
self.v = v
gravSys.planets.append(self)
self.gravSys = gravSys
self.resizemode("user")
self.pendown()
def init(self):
dt = self.gravSys.dt
self.a = self.acc()
self.v = self.v + 0.5*dt*self.a
def acc(self):
a = Vec(0,0)
for planet in self.gravSys.planets:
if planet != self:
v = planet.pos()-self.pos()
a += (G*planet.m/abs(v)**3)*v
return a
def step(self):
dt = self.gravSys.dt
self.setpos(self.pos() + dt*self.v)
if self.gravSys.planets.index(self) != 0:
self.setheading(self.towards(self.gravSys.planets[0]))
self.a = self.acc()
self.v = self.v + dt*self.a
## create compound yellow/blue turtleshape for planets
def main():
s = Turtle()
s.reset()
s.tracer(0,0)
s.ht()
s.pu()
s.fd(6)
s.lt(90)
s.begin_poly()
s.circle(6, 180)
s.end_poly()
m1 = s.get_poly()
s.begin_poly()
s.circle(6,180)
s.end_poly()
m2 = s.get_poly()
planetshape = Shape("compound")
planetshape.addcomponent(m1,"orange")
planetshape.addcomponent(m2,"blue")
s.getscreen().register_shape("planet", planetshape)
s.tracer(1,0)
## setup gravitational system
gs = GravSys()
sun = Star(1000000, Vec(0,0), Vec(0,-2.5), gs, "circle")
sun.color("yellow")
sun.shapesize(1.8)
sun.pu()
earth = Star(12500, Vec(210,0), Vec(0,195), gs, "planet")
earth.pencolor("green")
earth.shapesize(0.8)
moon = Star(1, Vec(220,0), Vec(0,295), gs, "planet")
moon.pencolor("blue")
moon.shapesize(0.5)
gs.init()
gs.start()
return "Done!"
if __name__ == '__main__':
msg = main()
print msg
mainloop()
#!/usr/bin/python
""" turtle-example-suite:
tdemo_tree.py
Displays a 'breadth-first-tree' - in contrast
to the classical Logo tree drawing programs,
which use a depth-first-algorithm.
Uses:
(1) a tree-generator, where the drawing is
quasi the side-effect, whereas the generator
always yields None.
(2) Turtle-cloning: At each branching point the
current pen is cloned. So in the end there
are 1024 turtles.
"""
from turtle import Turtle, mainloop
from time import clock
def tree(plist, l, a, f):
""" plist is list of pens
l is length of branch
a is half of the angle between 2 branches
f is factor by which branch is shortened
from level to level."""
if l > 3:
lst = []
for p in plist:
p.forward(l)
q = p.clone()
p.left(a)
q.right(a)
lst.append(p)
lst.append(q)
for x in tree(lst, l*f, a, f):
yield None
def maketree():
p = Turtle()
p.setundobuffer(None)
p.hideturtle()
p.speed(0)
p.tracer(30,0)
p.left(90)
p.penup()
p.forward(-210)
p.pendown()
t = tree([p], 200, 65, 0.6375)
for x in t:
pass
print len(p.getscreen().turtles())
def main():
a=clock()
maketree()
b=clock()
return "done: %.2f sec." % (b-a)
if __name__ == "__main__":
msg = main()
print msg
mainloop()
""" turtle-example-suite:
tdemo_wikipedia3.py
This example is
inspired by the Wikipedia article on turtle
graphics. (See example wikipedia1 for URLs)
First we create (ne-1) (i.e. 35 in this
example) copies of our first turtle p.
Then we let them perform their steps in
parallel.
Followed by a complete undo().
"""
from turtle import Screen, Turtle, mainloop
from time import clock, sleep
def mn_eck(p, ne,sz):
turtlelist = [p]
#create ne-1 additional turtles
for i in range(1,ne):
q = p.clone()
q.rt(360.0/ne)
turtlelist.append(q)
p = q
for i in range(ne):
c = abs(ne/2.0-i)/(ne*.7)
# let those ne turtles make a step
# in parallel:
for t in turtlelist:
t.rt(360./ne)
t.pencolor(1-c,0,c)
t.fd(sz)
def main():
s = Screen()
s.bgcolor("black")
p=Turtle()
p.speed(0)
p.hideturtle()
p.pencolor("red")
p.pensize(3)
s.tracer(36,0)
at = clock()
mn_eck(p, 36, 19)
et = clock()
z1 = et-at
sleep(1)
at = clock()
while any([t.undobufferentries() for t in s.turtles()]):
for t in s.turtles():
t.undo()
et = clock()
return "Laufzeit: %.3f sec" % (z1+et-at)
if __name__ == '__main__':
msg = main()
print msg
mainloop()
#!/usr/bin/python
""" turtle-example-suite:
tdemo_yinyang.py
Another drawing suitable as a beginner's
programming example.
The small circles are drawn by the circle
command.
"""
from turtle import *
def yin(radius, color1, color2):
width(3)
color("black")
fill(True)
circle(radius/2., 180)
circle(radius, 180)
left(180)
circle(-radius/2., 180)
color(color1)
fill(True)
color(color2)
left(90)
up()
forward(radius*0.375)
right(90)
down()
circle(radius*0.125)
left(90)
fill(False)
up()
backward(radius*0.375)
down()
left(90)
def main():
reset()
yin(200, "white", "black")
yin(200, "black", "white")
ht()
return "Done!"
if __name__ == '__main__':
main()
mainloop()
width = 800
height = 600
canvwidth = 1200
canvheight = 900
shape = arrow
mode = standard
resizemode = auto
fillcolor = ""
title = Python turtle graphics demo.
#!/usr/bin/python
import sys
import os
from Tkinter import *
from idlelib.Percolator import Percolator
from idlelib.ColorDelegator import ColorDelegator
from idlelib.textView import TextViewer
import turtle
import time
STARTUP = 1
READY = 2
RUNNING = 3
DONE = 4
EVENTDRIVEN = 5
menufont = ("Arial", 12, NORMAL)
btnfont = ("Arial", 12, 'bold')
txtfont = ('Lucida Console', 8, 'normal')
def getExampleEntries():
cwd = os.getcwd()
if "turtleDemo.py" not in os.listdir(cwd):
print "Directory of turtleDemo must be current working directory!"
print "But in your case this is", cwd
sys.exit()
entries1 = [entry for entry in os.listdir(cwd) if
entry.startswith("tdemo_") and
not entry.endswith(".pyc")]
entries2 = []
for entry in entries1:
if entry.endswith(".py"):
entries2.append(entry)
else:
path = os.path.join(cwd,entry)
sys.path.append(path)
subdir = [entry]
scripts = [script for script in os.listdir(path) if
script.startswith("tdemo_") and
script.endswith(".py")]
entries2.append(subdir+scripts)
return entries2
def showDemoHelp():
TextViewer(demo.root, "Help on turtleDemo", "demohelp.txt")
def showAboutDemo():
TextViewer(demo.root, "About turtleDemo", "about_turtledemo.txt")
def showAboutTurtle():
TextViewer(demo.root, "About the new turtle module", "about_turtle.txt")
class DemoWindow(object):
def __init__(self, filename=None): #, root=None):
self.root = root = turtle._root = Tk()
root.wm_protocol("WM_DELETE_WINDOW", self._destroy)
#################
self.mBar = Frame(root, relief=RAISED, borderwidth=2)
self.mBar.pack(fill=X)
self.ExamplesBtn = self.makeLoadDemoMenu()
self.OptionsBtn = self.makeHelpMenu()
self.mBar.tk_menuBar(self.ExamplesBtn, self.OptionsBtn) #, QuitBtn)
root.title('Python turtle-graphics examples')
#################
self.left_frame = left_frame = Frame(root)
self.text_frame = text_frame = Frame(left_frame)
self.vbar = vbar =Scrollbar(text_frame, name='vbar')
self.text = text = Text(text_frame,
name='text', padx=5, wrap='none',
width=45)
vbar['command'] = text.yview
vbar.pack(side=LEFT, fill=Y)
#####################
self.hbar = hbar =Scrollbar(text_frame, name='hbar', orient=HORIZONTAL)
hbar['command'] = text.xview
hbar.pack(side=BOTTOM, fill=X)
#####################
text['yscrollcommand'] = vbar.set
text.config(font=txtfont)
text.config(xscrollcommand=hbar.set)
text.pack(side=LEFT, fill=Y, expand=1)
#####################
self.output_lbl = Label(left_frame, height= 1,text=" --- ", bg = "#ddf",
font = ("Arial", 16, 'normal'))
self.output_lbl.pack(side=BOTTOM, expand=0, fill=X)
#####################
text_frame.pack(side=LEFT, fill=BOTH, expand=0)
left_frame.pack(side=LEFT, fill=BOTH, expand=0)
self.graph_frame = g_frame = Frame(root)
turtle.Screen._root = g_frame
turtle.Screen._canvas = turtle.ScrolledCanvas(g_frame, 800, 600, 1000, 800)
#xturtle.Screen._canvas.pack(expand=1, fill="both")
self.screen = _s_ = turtle.Screen()
self.scanvas = _s_._canvas
#xturtle.RawTurtle.canvases = [self.scanvas]
turtle.RawTurtle.screens = [_s_]
self.scanvas.pack(side=TOP, fill=BOTH, expand=1)
self.btn_frame = btn_frame = Frame(g_frame, height=100)
self.start_btn = Button(btn_frame, text=" START ", font=btnfont, fg = "white",
disabledforeground = "#fed", command=self.startDemo)
self.start_btn.pack(side=LEFT, fill=X, expand=1)
self.stop_btn = Button(btn_frame, text=" STOP ", font=btnfont, fg = "white",
disabledforeground = "#fed", command = self.stopIt)
self.stop_btn.pack(side=LEFT, fill=X, expand=1)
self.clear_btn = Button(btn_frame, text=" CLEAR ", font=btnfont, fg = "white",
disabledforeground = "#fed", command = self.clearCanvas)
self.clear_btn.pack(side=LEFT, fill=X, expand=1)
self.btn_frame.pack(side=TOP, fill=BOTH, expand=0)
self.graph_frame.pack(side=TOP, fill=BOTH, expand=1)
Percolator(text).insertfilter(ColorDelegator())
self.dirty = False
self.exitflag = False
if filename:
self.loadfile(filename)
self.configGUI(NORMAL, DISABLED, DISABLED, DISABLED,
"Choose example from menu", "black")
self.state = STARTUP
def _destroy(self):
self.root.destroy()
sys.exit()
def configGUI(self, menu, start, stop, clear, txt="", color="blue"):
self.ExamplesBtn.config(state=menu)
self.start_btn.config(state=start)
if start==NORMAL:
self.start_btn.config(bg="#d00")
else:
self.start_btn.config(bg="#fca")
self.stop_btn.config(state=stop)
if stop==NORMAL:
self.stop_btn.config(bg="#d00")
else:
self.stop_btn.config(bg="#fca")
self.clear_btn.config(state=clear)
self.clear_btn.config(state=clear)
if clear==NORMAL:
self.clear_btn.config(bg="#d00")
else:
self.clear_btn.config(bg="#fca")
self.output_lbl.config(text=txt, fg=color)
def makeLoadDemoMenu(self):
CmdBtn = Menubutton(self.mBar, text='Examples', underline=0, font=menufont)
CmdBtn.pack(side=LEFT, padx="2m")
CmdBtn.menu = Menu(CmdBtn)
for entry in getExampleEntries():
def loadexample(x):
def emit():
self.loadfile(x)
return emit
if isinstance(entry,str):
CmdBtn.menu.add_command(label=entry[6:-3], underline=0, font=menufont,
command=loadexample(entry))
else:
_dir, entries = entry[0], entry[1:]
CmdBtn.menu.choices = Menu(CmdBtn.menu)
for e in entries:
CmdBtn.menu.choices.add_command(label=e[6:-3], underline=0, font=menufont,
command = loadexample(os.path.join(_dir,e)))
CmdBtn.menu.add_cascade(label=_dir[6:],
menu = CmdBtn.menu.choices, font=menufont )
CmdBtn['menu'] = CmdBtn.menu
return CmdBtn
def makeHelpMenu(self):
CmdBtn = Menubutton(self.mBar, text='Help', underline=0, font = menufont)
CmdBtn.pack(side=LEFT, padx='2m')
CmdBtn.menu = Menu(CmdBtn)
CmdBtn.menu.add_command(label='About turtle.py', font=menufont, command=showAboutTurtle)
CmdBtn.menu.add_command(label='turtleDemo - Help', font=menufont, command=showDemoHelp)
CmdBtn.menu.add_command(label='About turtleDemo', font=menufont, command=showAboutDemo)
CmdBtn['menu'] = CmdBtn.menu
return CmdBtn
def refreshCanvas(self):
if not self.dirty: return
self.screen.clear()
#self.screen.mode("standard")
self.dirty=False
def loadfile(self,filename):
self.refreshCanvas()
if os.path.exists(filename) and not os.path.isdir(filename):
# load and display file text
f = open(filename,'r')
chars = f.read()
f.close()
self.text.delete("1.0", "end")
self.text.insert("1.0",chars)
direc, fname = os.path.split(filename)
self.root.title(fname[6:-3]+" - an xturtle example")
self.module = __import__(fname[:-3])
reload(self.module)
self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED,
"Press start button", "red")
self.state = READY
def startDemo(self):
self.refreshCanvas()
self.dirty = True
turtle.TurtleScreen._RUNNING = True
self.configGUI(DISABLED, DISABLED, NORMAL, DISABLED,
"demo running...", "black")
self.screen.clear()
self.screen.mode("standard")
self.state = RUNNING
try:
result = self.module.main()
if result == "EVENTLOOP":
self.state = EVENTDRIVEN
else:
self.state = DONE
except turtle.Terminator:
self.state = DONE
result = "stopped!"
if self.state == DONE:
self.configGUI(NORMAL, NORMAL, DISABLED, NORMAL,
result)
elif self.state == EVENTDRIVEN:
self.exitflag = True
self.configGUI(DISABLED, DISABLED, NORMAL, DISABLED,
"use mouse/keys or STOP", "red")
def clearCanvas(self):
self.refreshCanvas()
self.scanvas.config(cursor="")
self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED)
def stopIt(self):
if self.exitflag:
self.clearCanvas()
self.exitflag = False
self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED,
"STOPPED!", "red")
turtle.TurtleScreen._RUNNING = False
#print "stopIT: exitflag = True"
else:
turtle.TurtleScreen._RUNNING = False
#print "stopIt: exitflag = False"
if __name__ == '__main__':
demo = DemoWindow()
RUN = True
while RUN:
try:
print "ENTERING mainloop"
demo.root.mainloop()
except AttributeError:
print "CRASH!!!- WAIT A MOMENT!"
time.sleep(0.3)
print "GOING ON .."
demo.refreshCanvas()
## time.sleep(1)
except:
RUN = FALSE
#!/usr/bin/python
## DEMONSTRATES USE OF 2 CANVASES, SO CANNOT BE RUN IN DEMOVIEWER!
"""turtle example: Using TurtleScreen and RawTurtle
for drawing on two distinct canvases.
"""
from turtle import TurtleScreen, RawTurtle, TK
root = TK.Tk()
cv1 = TK.Canvas(root, width=300, height=200, bg="#ddffff")
cv2 = TK.Canvas(root, width=300, height=200, bg="#ffeeee")
cv1.pack()
cv2.pack()
s1 = TurtleScreen(cv1)
s1.bgcolor(0.85, 0.85, 1)
s2 = TurtleScreen(cv2)
s2.bgcolor(1, 0.85, 0.85)
p = RawTurtle(s1)
q = RawTurtle(s2)
p.color("red", "white")
p.width(3)
q.color("blue", "black")
q.width(3)
for t in p,q:
t.shape("turtle")
t.lt(36)
q.lt(180)
for i in range(5):
for t in p, q:
t.fd(50)
t.lt(72)
for t in p,q:
t.lt(54)
t.pu()
t.bk(50)
## Want to get some info?
print s1, s2
print p, q
print s1.turtles()
print s2.turtles()
TK.mainloop()
========================================
:mod:`turtle` --- Turtle graphics for Tk :mod:`turtle` --- Turtle graphics for Tk
======================================== ========================================
.. module:: turtle ------------
:platform: Tk Introduction
:synopsis: An environment for turtle graphics. ------------
.. moduleauthor:: Guido van Rossum <guido@python.org>
Turtle graphics is a popular way for introducing programming to
kids. It was part of the original Logo programming language developed
by Wally Feurzig and Seymour Papert in 1966.
Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it
the 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 the
command turtle.left(25), and it rotates in-place 25 degrees clockwise.
By combining together these and similar commands, intricate shapes and
pictures can easily be drawn.
The module turtle.py is an extended reimplementation of turtle.py from
the Python standard distribution up to version Python 2.5.
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 the
learning programmer to use all the commands, classes and methods
interactively when using the module from within IDLE run with
the -n switch.
The turtle module provides turtle graphics primitives, in both
object-oriented and procedure-oriented ways. Because it uses Tkinter
for the underlying graphics, it needs a version of python installed
with Tk support.
The objectoriented interface uses essentially two+two classes:
1. The TurtleScreen class defines graphics windows as a playground for the
drawing turtles. It's constructor needs a Tk-Canvas or a ScrolledCanvas
as argument. It should be used when turtle.py is used as part of some
application.
Derived from TurtleScreen is the subclass Screen. Screen is implemented
as sort of singleton, so there can exist only one instance of Screen at a
time. It should be used when turtle.py is used as a standalone tool for
doing graphics.
All methods of TurtleScreen/Screen also exist as functions, i. e.
as part of the procedure-oriented interface.
2. RawTurtle (alias: RawPen) defines Turtle-objects which draw on a
TurtleScreen. It's constructor needs a Canvas/ScrolledCanvas/Turtlescreen
as argument, so the RawTurtle objects know where to draw.
Derived from RawTurtle is the subclass Turtle (alias: Pen), which
draws on "the" Screen - instance which is automatically created,
if not already present.
All methods of RawTurtle/Turtle also exist as functions, i. e.
part of the procedure-oriented interface.
The procedural interface uses functions which are derived from the methods
of the classes Screen and Turtle. They have the same names as the
corresponding methods. A screen-object is automativally created
whenever a function derived form a Screen-method is called. An (unnamed)
turtle object is automatically created whenever any of the functions
derived from a Turtle method is called.
To use multiple turtles an a screen one has to use the objectoriented
interface.
IMPORTANT NOTE!
In the following documentation the argumentlist for functions is given.
--->> Methods, of course, have the additional first argument self <<---
--->> which is omitted here. <<---
--------------------------------------------------
OVERVIEW over available Turtle and Screen methods:
--------------------------------------------------
(A) TURTLE METHODS:
===================
I. TURTLE MOTION
-----------------
MOVE AND DRAW
forward | fd
back | bk | back
right | rt
left | lt
goto | setpos | setposition
setx
sety
setheading | seth
home
circle
dot
stamp
clearstamp
clearstamps
undo
speed
TELL TURTLE'S STATE
position | pos
towards
xcor
ycor
heading
distance
SETTING AND MEASUREMENT
degrees
radians
II. PEN CONTROL
---------------
DRAWING STATE
pendown | pd | down
penup | pu | up
pensize | width
pen
isdown
COLOR CONTROL
color
pencolor
fillcolor
FILLING
fill
begin_fill
end_fill
MORE DRAWING CONTROL
reset
clear
write
III. TURTLE STATE
-----------------
VISIBILITY
showturtle | st
hideturtle | ht
isvisible
APPEARANCE
shape
resizemode
shapesize | turtlesize
settiltangle
tiltangle
tilt
IV. USING EVENTS
----------------
onclick
onrelease
ondrag
V. SPECIAL TURTLE METHODS
-------------------------
begin_poly
end_poly
get_poly
clone
getturtle | getpen
getscreen
setundobuffer
undobufferentries
tracer
window_width
window_height
..EXCURSUS ABOUT THE USE OF COMPOUND SHAPES
..-----------------------------------------
(B) METHODS OF TurtleScreen/Screen
==================================
I. WINDOW CONTROL
-----------------
bgcolor
bgpic
clear | clearscreen
reset | resetscreen
screensize
setworldcoordinates
II. ANIMATION CONTROL
---------------------
delay
tracer
update
III. USING SCREEN EVENTS
------------------------
listen
onkey
onclick | onscreenclick
ontimer
IV. SETTINGS AND SPECIAL METHODS
--------------------------------
mode
colormode
getcanvas
getshapes
register_shape | addshape
turtles
window_height
window_width
V. METHODS SPECIFIC TO Screen
=============================
bye()
exitonclick()
setup()
title()
---------------end of OVERVIEW ---------------------------
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
The :mod:`turtle` module provides turtle graphics primitives, in both an 2. METHODS OF RawTurtle/Turtle AND CORRESPONDING FUNCTIONS
object-oriented and procedure-oriented ways. Because it uses :mod:`Tkinter` for ==========================================================
the underlying graphics, it needs a version of python installed with Tk support.
The procedural interface uses a pen and a canvas which are automagically created (I) TURTLE MOTION:
when any of the functions are called. ------------------
The :mod:`turtle` module defines the following functions: (a) --- MOVE (AND DRAW)
.. function:: degrees() .. method:: forward(distance)
.. method:: fd(distance)
distance -- a number (integer or float)
Set angle measurement units to degrees. 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)
.. function:: radians()
Set angle measurement units to radians. .. method:: back(distance)
.. method:: bk(distance)
.. method:: backward(distance)
distance -- a number
call: back(distance)
--or: bk(distance)
--or: backward(distance)
.. function:: setup(**kwargs) Move the turtle backward by distance ,opposite to the direction the
turtle is headed. Do not change the turtle's heading.
Sets the size and position of the main window. Keywords are: Example (for a Turtle instance named turtle)::
* ``width``: either a size in pixels or a fraction of the screen. The default is >>> turtle.position()
50% of the screen. (0.00, 0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00, 0.00)
* ``height``: either a size in pixels or a fraction of the screen. The default
is 50% of the screen.
* ``startx``: starting position in pixels from the left edge of the screen. .. method:: right(angle)
``None`` is the default value and centers the window horizontally on screen. .. method:: rt(angle)
angle -- a number (integer or float)
* ``starty``: starting position in pixels from the top edge of the screen. Turn turtle right by angle units. (Units are by default degrees,
``None`` is the default value and centers the window vertically on screen. but can be set via the degrees() and radians() functions.)
Angle orientation depends on mode. (See this.)
Examples:: Example (for a Turtle instance named turtle)::
>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0
# Uses default geometry: 50% x 50% of screen, centered.
setup()
# Sets window to 200x200 pixels, in upper left of screen .. method:: left(angle)
setup (width=200, height=200, startx=0, starty=0) .. method:: lt(angle)
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
.. method:: goto(x, y=None)
.. method:: setpos(x, y=None)
.. method:: setposition(x, y=None)
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,
draw line. Do not change the turtle's orientation.
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)
.. method:: setx(x)
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)
.. method:: sety(y)
y -- 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, 40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00, -10.00)
.. method:: setheading(to_angle)
.. method:: seth(to_angle)
to_angle -- a number (integer or float)
Set the orientation of the turtle to to_angle.
Here are some common directions in degrees:
=================== ====================
standard - mode logo-mode
=================== ====================
0 - east 0 - north
90 - north 90 - east
180 - west 180 - south
270 - south 270 - west
=================== ====================
Example (for a Turtle instance named turtle)::
>>> turtle.setheading(90)
>>> turtle.heading()
90
.. method:: home():
Move turtle to the origin - coordinates (0,0) and set it's
heading to it's start-orientation (which depends on mode).
Example (for a Turtle instance named turtle)::
>>> turtle.home()
.. method:: circle(radius, extent=None, steps=None)
radius -- a number
extent (optional) -- a number
steps (optional) -- an integer
Draw a circle with given radius. The center is radius units left
of the turtle; extent - an angle - determines which part of the
circle is drawn. If extent is not given, draw the entire circle.
If extent is not a full circle, one endpoint of the arc is the
current pen position. Draw the arc in counterclockwise direction
if radius is positive, otherwise in clockwise direction. Finally
the direction of the turtle is changed by the amount of extent.
As the circle is approximated by an inscribed regular polygon,
steps determines the number of steps to use. If not given,
it will be calculated automatically. Maybe used to draw regular
polygons.
call: circle(radius) # full circle
--or: circle(radius, extent) # arc
--or: circle(radius, extent, steps)
--or: circle(radius, steps=6) # 6-sided polygon
Example (for a Turtle instance named turtle)::
>>> turtle.circle(50)
>>> turtle.circle(120, 180) # semicircle
.. method:: dot(size=None, *color)
size -- an integer >= 1 (if given)
color -- a colorstring or a numeric color tuple
Draw a circular dot with diameter size, using color. If size
is not given, the maximum of pensize+4 and 2*pensize is used.
Example (for a Turtle instance named turtle)::
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
.. method:: stamp():
Stamp a copy of the turtle shape onto the canvas at the current
turtle position. Return a stamp_id for that stamp, which can be
used to delete it by calling clearstamp(stamp_id).
Example (for a Turtle instance named turtle)::
>>> turtle.color("blue")
>>> turtle.stamp()
13
>>> turtle.fd(50)
.. method:: clearstamp(stampid):
stampid - an integer, must be return value of previous stamp() call.
Delete stamp with given stampid
Example (for a Turtle instance named turtle)::
>>> turtle.color("blue")
>>> astamp = turtle.stamp()
>>> turtle.fd(50)
>>> turtle.clearstamp(astamp)
.. method:: clearstamps(n=None):
n -- an integer
Delete all or first/last n of turtle's stamps.
If n is None, delete all of pen's stamps,
else if n > 0 delete first n stamps
else if n < 0 delete last n stamps.
Example (for a Turtle instance named turtle)::
>>> for i in range(8):
... turtle.stamp(); turtle.fd(30)
>>> turtle.clearstamps(2)
>>> turtle.clearstamps(-2)
>>> turtle.clearstamps()
.. method:: undo():
undo (repeatedly) the last turtle action(s). Number of available
undo actions is determined by the size of the undobuffer.
Example (for a Turtle instance named turtle)::
>>> for i in range(4):
turtle.fd(50); turtle.lt(80)
>>> for i in range(8):
turtle.undo()
.. method:: speed(speed=None):
speed -- an integer in the range 0..10 or a speedstring (see below)
Set the turtle's speed to an integer value in the range 0 .. 10.
If no argument is given: return current speed.
If input is a number greater than 10 or smaller than 0.5,
speed is set to 0.
Speedstrings are mapped to speedvalues as follows:
* 'fastest' : 0
* 'fast' : 10
* 'normal' : 6
* 'slow' : 3
* 'slowest' : 1
speeds from 1 to 10 enforce increasingly faster animation of
line drawing and turtle turning.
Attention:
speed = 0 : *no* animation takes place. forward/back makes turtle jump
and likewise left/right make the turtle turn instantly.
Example (for a Turtle instance named turtle)::
>>> turtle.speed(3)
TELL TURTLE'S STATE
-------------------
.. method:: position()
.. method:: pos()
Return the turtle's current location (x,y) (as a Vec2D-vector)
Example (for a Turtle instance named turtle)::
>>> turtle.pos()
(0.00, 240.00)
.. method:: towards(x, y=None)
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
Return the angle, between the line from turtle-position to position
specified by x, y and the turtle's start orientation. (Depends on
modes - "standard"/"world" or "logo")
Example (for a Turtle instance named turtle)::
>>> turtle.pos()
(10.00, 10.00)
>>> turtle.towards(0,0)
225.0
.. method:: xcor()
Return the turtle's x coordinate
Example (for a Turtle instance named turtle)::
>>> reset()
>>> turtle.left(60)
>>> turtle.forward(100)
>>> print turtle.xcor()
50.0
.. method:: ycor()
Return the turtle's y coordinate
Example (for a Turtle instance named turtle)::
>>> reset()
>>> turtle.left(60)
>>> turtle.forward(100)
>>> print turtle.ycor()
86.6025403784
.. method:: heading()
Return the turtle's current heading (value depends on mode).
Example (for a Turtle instance named turtle)::
>>> turtle.left(67)
>>> turtle.heading()
67.0
.. method:: distance(x, y=None)
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
Return the distance from the turtle to (x,y) in turtle step units.
Example (for a Turtle instance named turtle)::
>>> turtle.pos()
(0.00, 0.00)
>>> turtle.distance(30,40)
50.0
>>> joe = Turtle()
>>> joe.forward(77)
>>> turtle.distance(joe)
77.0
SETTINGS FOR MEASUREMENT
.. method:: degrees(fullcircle=360.0)
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
>>> turtle.degrees(400.0) # angle measurement in gon
>>> turtle.heading()
100
.. method:: radians()
Set the angle measurement units to radians.
Example (for a Turtle instance named turtle)::
>>> turtle.heading()
90
>>> turtle.radians()
>>> turtle.heading()
1.5707963267948966
(II) PEN CONTROL:
-----------------
DRAWING STATE
.. method:: pendown()
.. method:: pd()
.. method:: down()
Pull the pen down -- drawing when moving.
Example (for a Turtle instance named turtle)::
>>> turtle.pendown()
.. method:: penup()
.. method:: pu()
.. method:: up()
Pull the pen up -- no drawing when moving.
Example (for a Turtle instance named turtle)::
>>> turtle.penup()
.. method:: pensize(width=None)
.. method:: width(width=None)
width -- positive number
Set the line thickness to width or return it. If resizemode is set
to "auto" and turtleshape is a polygon, that polygon is drawn with
the same line thickness. If no argument is given, the current pensize
is returned.
Example (for a Turtle instance named turtle)::
>>> turtle.pensize()
1
turtle.pensize(10) # from here on lines of width 10 are drawn
.. method:: pen(pen=None, **pendict)
pen -- a dictionary with some or all of the below listed keys.
**pendict -- one or more keyword-arguments with the below
listed keys as keywords.
Return or set the pen's attributes in a 'pen-dictionary'
with the following key/value pairs:
* "shown" : True/False
* "pendown" : True/False
* "pencolor" : color-string or color-tuple
* "fillcolor" : color-string or color-tuple
* "pensize" : positive number
* "speed" : number in range 0..10
* "resizemode" : "auto" or "user" or "noresize"
* "stretchfactor": (positive number, positive number)
* "outline" : positive number
* "tilt" : number
This dicionary can be used as argument for a subsequent
pen()-call to restore the former pen-state. Moreover one
or more of these attributes can be provided as keyword-arguments.
This can be used to set several pen attributes in one statement.
Examples (for a Turtle instance named turtle)::
>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
>>> turtle.pen()
{'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
'pencolor': 'red', 'pendown': True, 'fillcolor': 'black',
'stretchfactor': (1,1), 'speed': 3}
>>> penstate=turtle.pen()
>>> turtle.color("yellow","")
>>> turtle.penup()
>>> turtle.pen()
{'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
'pencolor': 'yellow', 'pendown': False, 'fillcolor': '',
'stretchfactor': (1,1), 'speed': 3}
>>> p.pen(penstate, fillcolor="green")
>>> p.pen()
{'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
'pencolor': 'red', 'pendown': True, 'fillcolor': 'green',
'stretchfactor': (1,1), 'speed': 3}
.. method:: isdown(self):
Return True if pen is down, False if it's up.
Example (for a Turtle instance named turtle)::
>>> turtle.penup()
>>> turtle.isdown()
False
>>> turtle.pendown()
>>> turtle.isdown()
True
COLOR CONTROL
.. method:: color(*args)
Return or set pencolor and fillcolor.
Several input formats are allowed. They use 0, 1, 2, or 3 arguments
as follows:
- color()
Return the current pencolor and the current fillcolor
as a pair of color specification strings as are returned
by pencolor and fillcolor.
- color(colorstring), color((r,g,b)), color(r,g,b)
inputs as in pencolor, set both, fillcolor and pencolor,
to the given value.
- color(colorstring1, colorstring2),
- color((r1,g1,b1), (r2,g2,b2))
equivalent to pencolor(colorstring1) and fillcolor(colorstring2)
and analogously, if the other input format is used.
If turtleshape is a polygon, outline and interior of that polygon
is drawn with the newly set colors.
For more info see: pencolor, fillcolor
Example (for a Turtle instance named turtle)::
>>> turtle.color('red', 'green')
>>> turtle.color()
('red', 'green')
>>> colormode(255)
>>> color((40, 80, 120), (160, 200, 240))
>>> color()
('#285078', '#a0c8f0')
.. method:: pencolor(*args)
Return or set the pencolor.
Four input formats are allowed:
- pencolor()
Return the current pencolor as color specification string,
possibly in hex-number format (see example).
May be used as input to another color/pencolor/fillcolor call.
- pencolor(colorstring)
s is a Tk color specification string, such as "red" or "yellow"
- pencolor((r, g, b))
*a tuple* of r, g, and b, which represent, an RGB color,
and each of r, g, and b are in the range 0..colormode,
where colormode is either 1.0 or 255
- pencolor(r, g, b)
r, g, and b represent an RGB color, and each of r, g, and b
are in the range 0..colormode
If turtleshape is a polygon, the outline of that polygon is drawn
with the newly set pencolor.
Example (for a Turtle instance named turtle)::
>>> turtle.pencolor('brown')
>>> tup = (0.2, 0.8, 0.55)
>>> turtle.pencolor(tup)
>>> turtle.pencolor()
'#33cc8c'
.. method:: fillcolor(*args)
""" Return or set the fillcolor.
Four input formats are allowed:
- fillcolor()
Return the current fillcolor as color specification string,
possibly in hex-number format (see example).
May be used as input to another color/pencolor/fillcolor call.
- fillcolor(colorstring)
s is a Tk color specification string, such as "red" or "yellow"
- fillcolor((r, g, b))
*a tuple* of r, g, and b, which represent, an RGB color,
and each of r, g, and b are in the range 0..colormode,
where colormode is either 1.0 or 255
- fillcolor(r, g, b)
r, g, and b represent an RGB color, and each of r, g, and b
are in the range 0..colormode
If turtleshape is a polygon, the interior of that polygon is drawn
with the newly set fillcolor.
Example (for a Turtle instance named turtle)::
>>> turtle.fillcolor('violet')
>>> col = turtle.pencolor()
>>> turtle.fillcolor(col)
>>> turtle.fillcolor(0, .5, 0)
See also: Screen method colormode()
FILLING
.. method:: fill(flag)
flag -- True/False (or 1/0 respectively)
Call fill(True) before drawing the shape you want to fill,
and fill(False) when done. When used without argument: return
fillstate (True if filling, False else).
Example (for a Turtle instance named turtle)::
>>> turtle.fill(True)
>>> for _ in range(3):
... turtle.forward(100)
... turtle.left(120)
...
>>> turtle.fill(False)
.. method:: begin_fill()
Called just before drawing a shape to be filled.
Example (for a Turtle instance named turtle)::
>>> turtle.color("black", "red")
>>> turtle.begin_fill()
>>> turtle.circle(60)
>>> turtle.end_fill()
.. method:: end_fill()
Fill the shape drawn after the call begin_fill().
Example: See begin_fill()
MORE DRAWING CONTROL
.. method:: reset()
Delete the turtle's drawings from the screen, re-center the turtle
and set variables to the default values.
Example (for a Turtle instance named turtle)::
>>> turtle.position()
(0.00,-22.00)
>>> turtle.heading()
100.0
>>> turtle.reset()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
.. method:: clear()
Delete the turtle's drawings from the screen. Do not move turtle.
State and position of the turtle as well as drawings of other
turtles are not affected.
Examples (for a Turtle instance named turtle):
>>> turtle.clear()
.. method:: write(arg, move=False, align='left', font=('Arial', 8, 'normal'))
arg -- info, which is to be written to the TurtleScreen
move (optional) -- True/False
align (optional) -- one of the strings "left", "center" or right"
font (optional) -- a triple (fontname, fontsize, fonttype)
Write text - the string representation of arg - at the current
turtle position according to align ("left", "center" or right")
and with the given font.
If move is True, the pen is moved to the bottom-right corner
of the text. By default, move is False.
Example (for a Turtle instance named turtle)::
>>> turtle.write('Home = ', True, align="center")
>>> turtle.write((0,0), True)
TURTLE STATE:
-------------
VISIBILITY
.. method:: showturtle()
.. method:: st()
Makes the turtle visible.
Example (for a Turtle instance named turtle)::
>>> turtle.hideturtle()
>>> turtle.showturtle()
.. method:: hideturtle()
.. method:: ht()
Makes the turtle invisible.
It's a good idea to do this while you're in the middle of
doing some complex drawing, because hiding the turtle speeds
up the drawing observably.
Example (for a Turtle instance named turtle)::
>>> turtle.hideturtle()
# Sets window to 75% of screen by 50% of screen, and centers it. .. method:: isvisible(self):
setup(width=.75, height=0.5, startx=None, starty=None) Return True if the Turtle is shown, False if it's hidden.
Example (for a Turtle instance named turtle)::
>>> turtle.hideturtle()
>>> print turtle.isvisible():
False
.. function:: title(title_str)
Set the window's title to *title*. APPEARANCE
.. function:: done() .. method:: shape(name=None)
name -- a string, which is a valid shapename
Enters the Tk main loop. The window will continue to be displayed until the Set turtle shape to shape with given name or, if name is not given,
user closes it or the process is killed. return name of current shape.
Shape with name must exist in the TurtleScreen's shape dictionary.
Initially there are the following polygon shapes:
'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'.
To learn about how to deal with shapes see Screen-method register_shape.
Example (for a Turtle instance named turtle)::
>>> turtle.shape()
'arrow'
>>> turtle.shape("turtle")
>>> turtle.shape()
'turtle'
.. function:: reset()
Clear the screen, re-center the pen, and set variables to the default values. .. method:: resizemode(rmode=None)
rmode -- one of the strings "auto", "user", "noresize"
Set resizemode to one of the values: "auto", "user", "noresize".
If rmode is not given, return current resizemode.
Different resizemodes have the following effects:
.. function:: clear() - "auto" adapts the appearance of the turtle
corresponding to the value of pensize.
- "user" adapts the appearance of the turtle according to the
values of stretchfactor and outlinewidth (outline),
which are set by shapesize()
- "noresize" no adaption of the turtle's appearance takes place.
Clear the screen. resizemode("user") is called by a shapesize when used with arguments.
Examples (for a Turtle instance named turtle)::
>>> turtle.resizemode("noresize")
>>> turtle.resizemode()
'noresize'
.. function:: tracer(flag)
Set tracing on/off (according to whether flag is true or not). Tracing means .. method:: shapesize(stretch_wid=None, stretch_len=None, outline=None):
line are drawn more slowly, with an animation of an arrow along the line. stretch_wid -- positive number
stretch_len -- positive number
outline -- positive number
Return or set the pen's attributes x/y-stretchfactors and/or outline.
Set resizemode to "user".
If and only if resizemode is set to "user", the turtle will be
displayed stretched according to its stretchfactors:
stretch_wid is stretchfactor perpendicular to it's orientation,
stretch_len is stretchfactor in direction of it's orientation,
outline determines the width of the shapes's outline.
.. function:: speed(speed) Examples (for a Turtle instance named turtle)::
>>> turtle.resizemode("user")
>>> turtle.shapesize(5, 5, 12)
>>> turtle.shapesize(outline=8)
Set the speed of the turtle. Valid values for the parameter *speed* are
``'fastest'`` (no delay), ``'fast'``, (delay 5ms), ``'normal'`` (delay 10ms),
``'slow'`` (delay 15ms), and ``'slowest'`` (delay 20ms).
.. versionadded:: 2.5 .. method:: tilt(angle)
angle - a number
Rotate the turtleshape by angle from its current tilt-angle,
but do NOT change the turtle's heading (direction of movement).
.. function:: delay(delay) Examples (for a Turtle instance named turtle)::
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(30)
>>> turtle.fd(50)
>>> turtle.tilt(30)
>>> turtle.fd(50)
Set the speed of the turtle to *delay*, which is given in ms.
.. versionadded:: 2.5 .. method:: settiltangle(angle)
angle -- number
Rotate the turtleshape to point in the direction specified by angle,
regardless of its current tilt-angle. DO NOT change the turtle's
heading (direction of movement).
.. function:: forward(distance) Examples (for a Turtle instance named turtle)::
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.settiltangle(45)
>>> stamp()
>>> turtle.fd(50)
>>> turtle.settiltangle(-45)
>>> stamp()
>>> turtle.fd(50)
Go forward *distance* steps.
.. method:: tiltangle()
Return the current tilt-angle, i. e. the angle between the
orientation of the turtleshape and the heading of the turtle
(it's direction of movement).
.. function:: backward(distance) Examples (for a Turtle instance named turtle)::
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(45)
>>> turtle.tiltangle()
45
Go backward *distance* steps.
IV. USING EVENTS
----------------
.. function:: left(angle)
Turn left *angle* units. Units are by default degrees, but can be set via the .. method:: onclick(fun, btn=1, add=None)
:func:`degrees` and :func:`radians` functions. fun -- a function with two arguments, to which will be assigned
the coordinates of the clicked point on the canvas.
num -- number of the mouse-button defaults to 1 (left mouse button).
add -- True or False. If True, new binding will be added, otherwise
it will replace a former binding.
Bind fun to mouse-click event on this turtle on canvas.
If fun is None, existing bindings are removed.
Example for the anonymous turtle, i. e. the procedural way::
.. function:: right(angle) >>> def turn(x, y):
left(360)
Turn right *angle* units. Units are by default degrees, but can be set via the >>> onclick(turn) # Now clicking into the turtle will turn it.
:func:`degrees` and :func:`radians` functions. >>> onclick(None) # event-binding will be removed
.. function:: up() .. method:: onrelease(fun, btn=1, add=None):
"""
Arguments:
fun -- a function with two arguments, to which will be assigned
the coordinates of the clicked point on the canvas.
num -- number of the mouse-button defaults to 1 (left mouse button).
add -- True or False. If True, new binding will be added, otherwise
it will replace a former binding.
Move the pen up --- stop drawing. Bind fun to mouse-button-release event on this turtle on canvas.
If fun is None, existing bindings are removed.
Example (for a MyTurtle instance named turtle):
>>> class MyTurtle(Turtle):
... def glow(self,x,y):
... self.fillcolor("red")
... def unglow(self,x,y):
... self.fillcolor("")
...
>>> turtle = MyTurtle()
>>> turtle.onclick(turtle.glow)
>>> turtle.onrelease(turtle.unglow)
### clicking on turtle turns fillcolor red,
### unclicking turns it to transparent.
.. function:: down()
Move the pen down --- draw when moving. .. method:: ondrag(fun, btn=1, add=None):
fun -- a function with two arguments, to which will be assigned
the coordinates of the clicked point on the canvas.
num -- number of the mouse-button defaults to 1 (left mouse button).
add -- True or False. If True, new binding will be added, otherwise
it will replace a former binding.
Bind fun to mouse-move event on this turtle on canvas.
If fun is None, existing bindings are removed.
.. function:: width(width) Remark: Every sequence of mouse-move-events on a turtle is preceded
by a mouse-click event on that turtle.
If fun is None, existing bindings are removed.
Set the line width to *width*. Example (for a Turtle instance named turtle):
>>> turtle.ondrag(turtle.goto)
### Subsequently clicking and dragging a Turtle will move it across
### the screen thereby producing handdrawings (if pen is down).
.. function:: color(s) V. SPECIAL TURTLE METHODS
color((r, g, b)) --------------------------
color(r, g, b)
Set the pen color. In the first form, the color is specified as a Tk color
specification as a string. The second form specifies the color as a tuple of
the RGB values, each in the range [0..1]. For the third form, the color is
specified giving the RGB values as three separate parameters (each in the range
[0..1]).
.. method:: begin_poly():
Start recording the vertices of a polygon. Current turtle position
is first vertex of polygon.
.. function:: write(text[, move]) Example (for a Turtle instance named turtle):
>>> turtle.begin_poly()
Write *text* at the current pen position. If *move* is true, the pen is moved to
the bottom-right corner of the text. By default, *move* is false.
.. method:: end_poly():
Stop recording the vertices of a polygon. Current turtle position is
last vertex of polygon. This will be connected with the first vertex.
.. function:: fill(flag) Example (for a Turtle instance named turtle):
>>> turtle.end_poly()
The complete specifications are rather complex, but the recommended usage is:
call ``fill(1)`` before drawing a path you want to fill, and call ``fill(0)``
when you finish to draw the path.
.. method:: get_poly():
Return the lastly recorded polygon.
.. function:: begin_fill() Example (for a Turtle instance named turtle):
>>> p = turtle.get_poly()
>>> turtle.register_shape("myFavouriteShape", p)
Switch turtle into filling mode; Must eventually be followed by a corresponding
end_fill() call. Otherwise it will be ignored.
.. versionadded:: 2.5 .. method:: clone():
Create and return a clone of the turtle with same position, heading
and turtle properties.
Example (for a Turtle instance named mick):
mick = Turtle()
joe = mick.clone()
.. function:: end_fill()
End filling mode, and fill the shape; equivalent to ``fill(0)``. .. method:: getturtle():
Return the Turtleobject itself.
Only reasonable use: as a function to return the 'anonymous turtle':
.. versionadded:: 2.5 Example:
>>> pet = getturtle()
>>> pet.fd(50)
>>> pet
<turtle.Turtle object at 0x01417350>
>>> turtles()
[<turtle.Turtle object at 0x01417350>]
.. function:: circle(radius[, extent]) .. method:: getscreen():
Return the TurtleScreen object, the turtle is drawing on.
So TurtleScreen-methods can be called for that object.
Draw a circle with radius *radius* whose center-point is *radius* units left of Example (for a Turtle instance named turtle):
the turtle. *extent* determines which part of a circle is drawn: if not given it >>> ts = turtle.getscreen()
defaults to a full circle. >>> ts
<turtle.Screen object at 0x01417710>
>>> ts.bgcolor("pink")
If *extent* is not a full circle, one endpoint of the arc is the current pen
position. The arc is drawn in a counter clockwise direction if *radius* is
positive, otherwise in a clockwise direction. In the process, the direction of
the turtle is changed by the amount of the *extent*.
.. method:: def setundobuffer(size):
size -- an integer or None
.. function:: goto(x, y) Set or disable undobuffer.
goto((x, y)) If size is an integer an empty undobuffer of given size is installed.
Size gives the maximum number of turtle-actions that can be undone
by the undo() method/function.
If size is None, no undobuffer is present.
Go to co-ordinates *x*, *y*. The co-ordinates may be specified either as two Example (for a Turtle instance named turtle):
separate arguments or as a 2-tuple. >>> turtle.setundobuffer(42)
.. function:: towards(x, y) .. method:: undobufferentries():
"""Return count of entries in the undobuffer.
Return the angle of the line from the turtle's position to the point *x*, *y*. Example (for a Turtle instance named turtle):
The co-ordinates may be specified either as two separate arguments, as a >>> while undobufferentries():
2-tuple, or as another pen object. ... undo()
.. versionadded:: 2.5
.. method:: tracer(flag=None, delay=None)
A replica of the corresponding TurtleScreen-method
*Deprecated since Python 2.6* (as RawTurtle method)
.. function:: heading()
Return the current orientation of the turtle. .. method:: window_width()
.. method:: window_height()
Both are replicas of the corresponding TurtleScreen-methods
*Deprecated since Python 2.6* (as RawTurtle methods)
.. versionadded:: 2.3
EXCURSUS ABOUT THE USE OF COMPOUND SHAPES
-----------------------------------------
.. function:: setheading(angle) To use compound turtle shapes, which consist of several polygons
of different color, you must use the helper class Shape
explicitely as described below:
Set the orientation of the turtle to *angle*. 1. Create an empty Shape object of type compound
2. Add as many components to this object as desired,
using the addcomponent() method:
.. versionadded:: 2.3 .. method:: addcomponent(self, poly, fill, outline=None)
poly -- a polygon
fill -- a color, the poly will be filled with
outline -- a color for the poly's outline (if given)
So it goes like this::
.. function:: position() >>> s = Shape("compound")
>>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))
>>> s.addcomponent(poly1, "red", "blue")
>>> poly2 = ((0,0),(10,-5),(-10,-5))
>>> s.addcomponent(poly2, "blue", "red")
Return the current location of the turtle as an ``(x,y)`` pair. Now add Shape s to the Screen's shapelist ...
.. and use it::
.. versionadded:: 2.3 >>> register_shape("myshape", s)
>>> shape("myshape")
.. function:: setx(x) NOTE 1: addcomponent() is a method of class Shape (not of
Turtle nor Screen) and thus there is NO FUNCTION of the same name.
Set the x coordinate of the turtle to *x*. NOTE 2: class Shape is used internally by the register_shape method
in different ways.
.. versionadded:: 2.3 The application programmer has to deal with the Shape class
ONLY when using compound shapes like shown above!
NOTE 3: A short description of the class Shape is in section 4.
.. function:: sety(y)
Set the y coordinate of the turtle to *y*.
.. versionadded:: 2.3 3. METHODS OF TurtleScreen/Screen AND CORRESPONDING FUNCTIONS
=============================================================
.. function:: window_width() WINDOW CONTROL
--------------
Return the width of the canvas window.
.. versionadded:: 2.3 .. method:: bgcolor(*args)
args -- a color string or three numbers in the range 0..colormode
or a 3-tuple of such numbers.
Set or return backgroundcolor of the TurtleScreen.
.. function:: window_height() Example (for a TurtleScreen instance named screen):
>>> screen.bgcolor("orange")
>>> screen.bgcolor()
'orange'
>>> screen.bgcolor(0.5,0,0.5)
>>> screen.bgcolor()
'#800080'
Return the height of the canvas window.
.. versionadded:: 2.3 .. method:: bgpic(picname=None)
picname -- a string, name of a gif-file or "nopic".
Set background image or return name of current backgroundimage.
If picname is a filename, set the corresponing 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'
.. method:: clear()
.. method:: clearscreen()
Delete all drawings and all turtles from the TurtleScreen.
Reset empty TurtleScreen to it's initial state: white background,
no backgroundimage, no eventbindings and tracing on.
Example (for a TurtleScreen instance named screen):
screen.clear()
*Note*: this method is only available as the function named
clearscreen(). (The function clear() is another one derived from
the Turtle-method clear()!).
.. method:: reset()
.. method:: resetscreen()
Reset all Turtles on the Screen to their initial state.
Example (for a TurtleScreen instance named screen):
>>> screen.reset()
*Note*: this method is pnly available as the function named
resetscreen(). (The function reset() is another one derived from
the Turtle-method reset()!).
.. method:: screensize(canvwidth=None, canvheight=None, bg=None):
canvwidth -- positive integer, new width of canvas in pixels
canvheight -- positive integer, new height of canvas in pixels
bg -- colorstring or color-tupel, new backgroundcolor
If no arguments are given, return current (canvaswidth, canvasheight)
Resize the canvas, the turtles are drawing on.
Do not alter the drawing window. To observe hidden parts of
the canvas use the scrollbars. (So one 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 ;-)
.. method:: setworldcoordinates(llx, lly, urx, ury):
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 coodinate-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.reset()
>>> screen.setworldcoordinates(-50,-7.5,50,7.5)
>>> for _ in range(72):
... left(10)
...
>>> for _ in range(8):
... left(45); fd(2) # a regular octogon
ANIMATION CONTROL
-----------------
.. method:: delay(delay=None):
delay -- positive integer
Set or return the drawing delay in milliseconds. (This is sort of
time interval between two consecutived canvas updates.) The longer
the drawing delay, the slower the animation.
Optional argument:
Example (for a TurtleScreen instance named screen)::
>>> screen.delay(15)
>>> screen.delay()
15
.. method:: tracer(n=None, delay=None):
n -- nonnegative integer
delay -- nonnegative integer
Turn turtle animation on/off and set delay for update drawings.
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 argument sets delay value (see 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
.. method:: update():
Perform a TurtleScreen update. To be used, when tracer is turned
off.
See also RawTurtle/Turtle - method speed()
USING SCREEN EVENTS
-------------------
.. method:: listen(xdummy=None, ydummy=None):
"""Set focus on TurtleScreen (in order to collect key-events)
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()
.. method:: onkey(fun, key):
fun -- a function with no arguments or None
key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
Bind fun to key-release event of key. If fun is None, event-bindings
are removed.
Remark: 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()
.. method:: onclick(fun, btn=1, add=None):
.. method:: onscreenclick(fun, btn=1, add=None):
fun -- a function with two arguments, to which will be assigned
the coordinates of the clicked point on the canvas - or None.
num -- number of the mouse-button defaults to 1 (left mouse button).
add -- True or False. If True, new binding will be added, otherwise
it will replace a former binding.
Example (for 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
*Note*: this method is only available as the function named
onscreenclick(). (The function onclick() is a different one derived
from the Turtle-method onclick()!).
.. method:: ontimer(fun, t=0):
fun -- a function with no arguments.
t -- a number >= 0
Install a timer, which calls fun after t milliseconds.
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
SETTINGS AND SPECIAL METHODS
.. method:: mode(mode=None):
mode -- on of the strings 'standard', 'logo' or 'world'
Set turtle-mode ('standard', 'logo' or 'world') and perform reset.
If mode is not given, current mode is returned.
Mode 'standard' is compatible with old 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.
============ ========================= ===================
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'
.. method:: colormode(cmode=None):
cmode -- one of the values 1.0 or 255
"""Return the colormode or set it to 1.0 or 255.
Subsequently 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)
.. method:: getcanvas():
Return the Canvas of this TurtleScreen. Useful for insiders, who
know what to do with a Tkinter-Canvas ;-)
Example (for a Screen instance named screen):
>>> cv = screen.getcanvas()
>>> cv
<turtle.ScrolledCanvas instance at 0x010742D8>
.. method:: getshapes():
"""Return a list of names of all currently available turtle shapes.
Example (for a TurtleScreen instance named screen):
>>> screen.getshapes()
['arrow', 'blank', 'circle', ... , 'turtle']
.. method:: register_shape(name, shape=None)
.. method:: addshape(name, shape=None)
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. (See class Shape.)
Adds a turtle shape to TurtleScreen's shapelist. Only thusly
registered shapes can be used by issueing 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)))
.. method:: turtles():
Return the list of turtles on the screen.
Example (for a TurtleScreen instance named screen):
>>> for turtle in screen.turtles()
... turtle.color("red")
.. method:: window_height():
Return the height of the turtle window.
Example (for a TurtleScreen instance named screen):
>>> screen.window_height()
480
.. method:: window_width():
Return the width of the turtle window.
Example (for a TurtleScreen instance named screen):
>>> screen.window_width()
640
METHODS SPECIFIC TO Screen, not inherited from TurtleScreen
-----------------------------------------------------------
.. method:: bye():
"""Shut the turtlegraphics window.
This is a method of the Screen-class and not available for
TurtleScreen instances.
Example (for a TurtleScreen instance named screen):
>>> screen.bye()
.. method:: exitonclick():
Bind bye() method to mouseclick on TurtleScreen.
If "using_IDLE" - value in configuration dictionary is False
(default value), enter mainloop.
Remark: If IDLE with -n switch (no subprocess) is used, this value
should be set to True in turtle.cfg. In this case IDLE's own mainloop
is active also for the client script.
This is a method of the Screen-class and not available for
TurtleScreen instances.
Example (for a Screen instance named screen):
>>> screen.exitonclick()
.. method:: setup(width=_CFG["width"], height=_CFG["height"],
startx=_CFG["leftright"], starty=_CFG["topbottom"]):
Set the size and position of the main window.
Default values of arguments are stored in the configuration dicionary
and can be changed via a turtle.cfg file.
width -- as integer a size in pixels, as float a fraction of the screen.
Default is 50% of screen.
height -- as integer the height in pixels, as float a fraction of the
screen. Default is 75% of screen.
startx -- if positive, starting position in pixels from the left
edge of the screen, if negative from the right edge
Default, startx=None is to center window horizontally.
starty -- if positive, starting position in pixels from the top
edge of the screen, if negative from the bottom edge
Default, starty=None is to center window vertically.
Examples (for a Screen instance named screen)::
>>> screen.setup (width=200, height=200, startx=0, starty=0)
# sets window to 200x200 pixels, in upper left of screen
>>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
# sets window to 75% of screen by 50% of screen and centers
.. method:: title(titlestring):
titlestring -- a string, to appear in the titlebar of the
turtle graphics window.
Set title of turtle-window to titlestring
This is a method of the Screen-class and not available for
TurtleScreen instances.
Example (for a Screen instance named screen):
>>> screen.title("Welcome to the turtle-zoo!")
4. THE PUBLIC CLASSES of the module turtle.py
=============================================
class RawTurtle(canvas):
canvas -- a Tkinter-Canvas, a ScrolledCanvas or a TurtleScreen
Alias: RawPen
Define a turtle.
A description of the methods follows below. All methods are also
available as functions (to control some anonymous turtle) thus
providing a procedural interface to turtlegraphics
class Turtle()
Subclass of RawTurtle, has the same interface with the additional
property, that Turtle instances draw on a default Screen object,
which is created automatically, when needed for the first time.
class TurtleScreen(cv)
cv -- a Tkinter-Canvas
Provides screen oriented methods like setbg etc.
A description of the methods follows below.
class Screen()
Subclass of TurtleScreen, with four methods added.
All methods are also available as functions to conrtol a unique
Screen instance thus belonging to the procedural interface
to turtlegraphics. This Screen instance is automatically created
when needed for the first time.
class ScrolledCavas(master)
master -- some Tkinter widget to contain the ScrolledCanvas, i.e.
a Tkinter-canvas with scrollbars added.
Used by class Screen, which thus provides automatically a
ScrolledCanvas as playground for the turtles.
class Shape(type\_, data)
type --- one of the strings "polygon", "image", "compound"
Data structure modeling shapes.
The pair type\_, data must be as follows:
type\_ data
"polygon" a polygon-tuple, i. e.
a tuple of pairs of coordinates
"image" an image (in this form only used internally!)
"compound" None
A compund shape has to be constructed using
the addcomponent method
addcomponent(self, poly, fill, outline=None)
poly -- polygon, i. e. a tuple of pairs of numbers.
fill -- the fillcolor of the component,
outline -- the outline color of the component.
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()
See EXCURSUS ABOUT THE USE OF COMPOUND SHAPES
class Vec2D(x, y):
A two-dimensional vector class, used as a helper class
for implementing turtle graphics.
May be useful for turtle graphics programs also.
Derived from tuple, so a vector is a tuple!
Provides (for a, b vectors, k number):
* a+b vector addition
* a-b vector subtraction
* a*b inner product
* k*a and a*k multiplication with scalar
* \|a\| absolute value of a
* a.rotate(angle) rotation
V. HELP AND CONFIGURATION
=========================
This section contains subsections on:
- how to use help
- how to prepare and use translations of the online-help
into other languages
- how to configure the appearance of the graphics window and
the turtles at startup
HOW TO USE HELP:
----------------
The public methods of the Screen and Turtle classes are documented
extensively via docstrings. So these can be used as online-help
via the Python help facilities:
- When using IDLE, tooltips show the signatures and first lines of
the docstrings of typed in function-/method calls.
- calling help on methods or functions display the docstrings.
Examples::
This module also does ``from math import *``, so see the documentation for the >>> help(Screen.bgcolor)
:mod:`math` module for additional constants and functions useful for turtle Help on method bgcolor in module turtle:
graphics.
bgcolor(self, *args) unbound turtle.Screen method
Set or return backgroundcolor of the TurtleScreen.
.. function:: demo() Arguments (if given): a color string or three numbers
in the range 0..colormode or a 3-tuple of such numbers.
Exercise the module a bit. Example (for a TurtleScreen instance named screen)::
>>> screen.bgcolor("orange")
>>> screen.bgcolor()
'orange'
>>> screen.bgcolor(0.5,0,0.5)
>>> screen.bgcolor()
'#800080'
.. exception:: Error >>> help(Turtle.penup)
Help on method penup in module turtle:
Exception raised on any error caught by this module. penup(self) unbound turtle.Turtle method
Pull the pen up -- no drawing when moving.
For examples, see the code of the :func:`demo` function. Aliases: penup | pu | up
This module defines the following classes: No argument
Example (for a Turtle instance named turtle):
>>> turtle.penup()
.. class:: Pen() The docstrings of the functions which are derived from methods have
a modified form::
Define a pen. All above functions can be called as a methods on the given pen. >>> help(bgcolor)
The constructor automatically creates a canvas do be drawn on. Help on function bgcolor in module turtle:
bgcolor(*args)
Set or return backgroundcolor of the TurtleScreen.
.. class:: Turtle() Arguments (if given): a color string or three numbers
in the range 0..colormode or a 3-tuple of such numbers.
Define a pen. This is essentially a synonym for ``Pen()``; :class:`Turtle` is an Example::
empty subclass of :class:`Pen`.
>>> bgcolor("orange")
>>> bgcolor()
'orange'
>>> bgcolor(0.5,0,0.5)
>>> bgcolor()
'#800080'
.. class:: RawPen(canvas) >>> help(penup)
Help on function penup in module turtle:
Define a pen which draws on a canvas *canvas*. This is useful if you want to penup()
use the module to create graphics in a "real" program. Pull the pen up -- no drawing when moving.
Aliases: penup | pu | up
No argument
Example:
>>> penup()
These modified docstrings are created automatically together with the
function definitions that are derived from the methods at import time.
TRANSLATION OF DOCSTRINGS INTO DIFFERENT LANGUAGES
--------------------------------------------------
.. _pen-rawpen-objects: There is a utility to create a dictionary the keys of which are the
method names and the values of which are the docstrings of the public
methods of the classes Screen and Turtle.
Turtle, Pen and RawPen Objects write_docstringdict(filename="turtle_docstringdict"):
------------------------------ filename -- a string, used as filename
Most of the global functions available in the module are also available as Create and write docstring-dictionary to a Python script
methods of the :class:`Turtle`, :class:`Pen` and :class:`RawPen` classes, with the given filename.
affecting only the state of the given pen. This function has to be called explicitely, (it is not used by the
turtle-graphics classes). The docstring dictionary will be written
to the Python script <filname>.py It is intended to serve as a
template for translation of the docstrings into different languages.
The only method which is more powerful as a method is :func:`degrees`, which If you (or your students) want to use turtle.py with online help in
takes an optional argument letting you specify the number of units your native language. You have to translate the docstrings and save
corresponding to a full circle: the resulting file as e.g. turtle_docstringdict_german.py
If you have an appropriate entry in your turtle.cfg file this dictionary
will be read in at import time and will replace the original English
docstrings.
.. method:: Turtle.degrees([fullcircle]) At the time of this writing there exist docstring_dicts in German
and in Italian. (Requests please to glingl@aon.at)
*fullcircle* is by default 360. This can cause the pen to have any angular units
whatever: give *fullcircle* ``2*pi`` for radians, or 400 for gradians.
HOW TO CONFIGURE SCREEN AND TURTLES
-----------------------------------
The built-in default configuration mimics the appearance and
behaviour of the old turtle module in order to retain best possible
compatibility with it.
If you want to use a different configuration which reflects
better the features of this module or which fits better to
your needs, e. g. for use in a classroom, you can prepare
a configuration file turtle.cfg which will be read at import
time and modify the configuration according to it's settings.
The built in configuration would correspond to the following
turtle.cfg:
width = 0.5
height = 0.75
leftright = None
topbottom = None
canvwidth = 400
canvheight = 300
mode = standard
colormode = 1.0
delay = 10
undobuffersize = 1000
shape = classic
pencolor = black
fillcolor = black
resizemode = noresize
visible = True
language = english
exampleturtle = turtle
examplescreen = screen
title = Python Turtle Graphics
using_IDLE = False
Short explanation of selected entries:
- The first four lines correspond to the arguments of the
Screen.setup method
- Line 5 and 6 correspond to the arguments of the Method
Screen.screensize
- shape can be any of the built-in shapes, e.g: arrow, turtle,
etc. For more info try help(shape)
- if you want to use no fillcolor (i. e. turtle transparent),
you have to write:
fillcolor = ""
(All not empty strings must not have quotes in the cfg-file!)
- if you want to reflect the turtle its state, you have to use
resizemode = auto
- if you set, e. g.: language = italian
the docstringdict turtle_docstringdict_italian.py will be
loaded at import time (if present on the import path, e.g. in
the same directory as turtle.py
- the entries exampleturtle and examplescreen define the names
of these objects as they occur in the docstrings. The
transformation of method-docstrings to function-docstrings
will delete these names from the docstrings. (See examples in
section on HELP)
- using_IDLE Set this to True if you regularly work with IDLE
and it's -n - switch. ("No subprocess") This will prevent
exitonclick to enter the mainloop.
There can be a turtle.cfg file in the directory where turtle.py
is stored and an additional one in the currentworkingdirectory.
The latter will override the settings of the first one.
The turtledemo directory contains a turtle.cfg file. If you
study it as an example and see its effects when running the
demos (preferably not from within the demo-viewer).
VI. Demo scripts
================
There is a set of demo scripts in the turtledemo directory
located here ...
##### please complete info about path ########################
It contains:
- a set of 15 demo scripts demonstrating differet features
of the new module turtle.py
- a Demo-Viewer turtleDemo.py which can be used to view
the sourcecode of the scripts and run them at the same time
14 of the examples can be accessed via the Examples Menu.
All of them can also be run standalone.
- The example turtledemo_two_canvases.py demonstrates the
simultaneous use of two canvases with the turtle module.
Therefor it only can be run standalone.
- There is a turtle.cfg file in this directory, which also
serves as an example for how to write and use such files.
The demoscripts are:
+----------------+------------------------------+-----------------------+
|Name | description | features |
+----------------+------------------------------+-----------------------+
|bytedesign | complex classical | tracer, delay |
| | turtlegraphics pattern | update |
+----------------+------------------------------+-----------------------+
|chaos | graphs verhust dynamics, | worldcoordinates |
| | proofs that you must not | |
| | trust computers computations| |
+----------------+------------------------------+-----------------------+
|clock | analog clock showing time | turtles as clock's |
| | of your computer | hands, ontimer |
+----------------+------------------------------+-----------------------+
|colormixer | experiment with r, g, b | ondrag |
+----------------+------------------------------+-----------------------+
|fractalcurves | Hilbert & Koch | recursion |
+----------------+------------------------------+-----------------------+
|lindenmayer | ethnomathematics | L-System |
| | (indian kolams) | |
+----------------+------------------------------+-----------------------+
|minimal_hanoi | Towers of Hanoi | Rectangular Turtles |
| | | as Hanoi-Discs |
| | | (shape, shapesize) |
+----------------+------------------------------+-----------------------+
|paint | super minimalistic | onclick |
| | drawing program | |
+----------------+------------------------------+-----------------------+
|peace | elementary | turtle: appearance |
| | | and animation |
+----------------+------------------------------+-----------------------+
|penrose | aperiodic tiling with | stamp |
| | kites and darts | |
+----------------+------------------------------+-----------------------+
|planet_and_moon | simulation of | compound shape |
| | gravitational system | Vec2D |
+----------------+------------------------------+-----------------------+
|tree | a (graphical) breadth | clone |
| | first tree (using generators)| |
+----------------+------------------------------+-----------------------+
|wikipedia | a pattern from the wikipedia | clone, undo |
| | article on turtle-graphics | |
+----------------+------------------------------+-----------------------+
|yingyang | another elementary example | circle |
+----------------+------------------------------+-----------------------+
turtledemo_two-canvases: two distinct Tkinter-Canvases
are populated with turtles. Uses class RawTurtle.
Have fun!
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -412,6 +412,7 @@ Christopher Lindblad ...@@ -412,6 +412,7 @@ Christopher Lindblad
Bjorn Lindqvist Bjorn Lindqvist
Per Lindqvist Per Lindqvist
Eric Lindvall Eric Lindvall
Gregor Lingl
Nick Lockwood Nick Lockwood
Stephanie Lockwood Stephanie Lockwood
Anne Lord Anne Lord
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment