Commit 97cf99fc authored by Martin v. Löwis's avatar Martin v. Löwis

Patch #3064: Port new turtle module and demos to 3.0.

parent b38fea34
========================================================
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 turtleDemo.py
--------------------------------------
Tiny demo Viewer to view turtle graphics example scripts.
Quickly and dirtyly assembled by Gregor Lingl.
June, 2006
For more information see: turtleDemo - Help
Have fun!
----------------------------------------------
turtleDemo - 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 turtleDemo.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 tkinter.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 tkinter.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.getscreen().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.getscreen().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 tkinter.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 tkinter.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 tkinter.turtle import Screen, Turtle, mainloop
import sys
sys.setrecursionlimit(20000) # overcomes, for now, an instability of Python 3.0
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
""" turtlegraphics-example-suite:
tdemo_forest.py
Displays a 'forest' of 3 'breadth-first-trees'
similar to the one from example tree.
For further remarks see xtx_tree.py
This example is a 'breadth-first'-rewrite of
a Logo program written by Erich Neuwirth. See:
http://homepage.univie.ac.at/erich.neuwirth/
"""
from tkinter.turtle import Turtle, colormode, tracer, mainloop
from random import randrange
from time import clock
def symRandom(n):
return randrange(-n,n+1)
def randomize( branchlist, angledist, sizedist ):
return [ (angle+symRandom(angledist),
sizefactor*1.01**symRandom(sizedist))
for angle, sizefactor in branchlist ]
def randomfd( t, distance, parts, angledist ):
for i in range(parts):
t.left(symRandom(angledist))
t.forward( (1.0 * distance)/parts )
def tree(tlist, size, level, widthfactor, branchlists, angledist=10, sizedist=5):
# benutzt Liste von turtles und Liste von Zweiglisten,
# fuer jede turtle eine!
if level > 0:
lst = []
brs = []
for t, branchlist in list(zip(tlist,branchlists)):
t.pensize( size * widthfactor )
t.pencolor( 255 - (180 - 11 * level + symRandom(15)),
180 - 11 * level + symRandom(15),
0 )
t.pendown()
randomfd(t, size, level, angledist )
yield 1
for angle, sizefactor in branchlist:
t.left(angle)
lst.append(t.clone())
brs.append(randomize(branchlist, angledist, sizedist))
t.right(angle)
for x in tree(lst, size*sizefactor, level-1, widthfactor, brs,
angledist, sizedist):
yield None
def start(t,x,y):
colormode(255)
t.reset()
t.speed(0)
t.hideturtle()
t.left(90)
t.penup()
t.setpos(x,y)
t.pendown()
def doit1(level, pen):
pen.hideturtle()
start(pen, 20, -208)
t = tree( [pen], 80, level, 0.1, [[ (45,0.69), (0,0.65), (-45,0.71) ]] )
return t
def doit2(level, pen):
pen.hideturtle()
start(pen, -135, -130)
t = tree( [pen], 120, level, 0.1, [[ (45,0.69), (-45,0.71) ]] )
return t
def doit3(level, pen):
pen.hideturtle()
start(pen, 190, -90)
t = tree( [pen], 100, level, 0.1, [[ (45,0.7), (0,0.72), (-45,0.65) ]] )
return t
# Hier 3 Baumgeneratoren:
def main():
p = Turtle()
p.ht()
tracer(75,0)
u = doit1(6, Turtle(undobuffersize=1))
s = doit2(7, Turtle(undobuffersize=1))
t = doit3(5, Turtle(undobuffersize=1))
a = clock()
while True:
done = 0
for b in u,s,t:
try:
b.__next__()
except:
done += 1
if done == 3:
break
tracer(1,10)
b = clock()
return "runtime: %.2f sec." % (b-a)
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 tkinter.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.getscreen().tracer(1,0)
ft.pu()
size = 6
ft.setpos(-33*size, -32*size)
ft.pd()
ta=clock()
ft.fillcolor("red")
ft.begin_fill()
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.end_fill()
tb=clock()
res = "Hilbert: %.2fsec. " % (tb-ta)
sleep(3)
ft.reset()
ft.speed(0)
ft.ht()
ft.getscreen().tracer(1,0)
ta=clock()
ft.color("black", "blue")
ft.begin_fill()
ft.fractalgon(3, 250, 4, 1)
ft.end_fill()
ft.begin_fill()
ft.color("red")
ft.fractalgon(3, 200, 4, -1)
ft.end_fill()
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 tkinter.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 tkinter.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 tkinter.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 tkinter.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 tkinter.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 tkinter.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.getscreen().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.getscreen().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 tkinter.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.getscreen().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 tkinter.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 tkinter.turtle import *
def yin(radius, color1, color2):
width(3)
color("black", color1)
begin_fill()
circle(radius/2., 180)
circle(radius, 180)
left(180)
circle(-radius/2., 180)
end_fill()
left(90)
up()
forward(radius*0.35)
right(90)
down()
color(color1, color2)
begin_fill()
circle(radius*0.15)
end_fill()
left(90)
up()
backward(radius*0.35)
down()
left(90)
def main():
reset()
yin(200, "black", "white")
yin(200, "white", "black")
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 view_file # TextViewer
from imp import reload
from tkinter 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()
#print(cwd, os.listdir(cwd))
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():
view_file(demo.root, "Help on turtleDemo", "demohelp.txt")
def showAboutDemo():
view_file(demo.root, "About turtleDemo", "about_turtledemo.txt")
def showAboutTurtle():
view_file(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()
#####
turtle.TurtleScreen.__init__(_s_, _s_._canvas)
#####
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]+" - a Python turtle graphics 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.screen._delete("all")
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("AttributeError!- WAIT A MOMENT!")
time.sleep(0.3)
print("GOING ON ..")
demo.ckearCanvas()
except TypeError:
demo.screen._delete("all")
#print("CRASH!!!- WAIT A MOMENT!")
time.sleep(0.3)
#print("GOING ON ..")
demo.clearCanvas()
except:
print("BYE!")
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 tkinter.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", (1, 0.85, 0.85))
p.width(3)
q.color("blue", (0.85, 0.85, 1))
q.width(3)
for t in p,q:
t.shape("turtle")
t.lt(36)
q.lt(180)
for t in p, q:
t.begin_fill()
for i in range(5):
for t in p, q:
t.fd(50)
t.lt(72)
for t in p,q:
t.end_fill()
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:`tkinter.turtle` --- Turtle graphics for Tk
================================================
========================================
:mod:`turtle` --- Turtle graphics for Tk
========================================
Introduction
============
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 :mod:`turtle` module is an extended reimplementation of the same-named
module from the Python standard distribution up to version Python 2.5.
It tries to keep the merits of the old turtle module 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 :mod:`Tkinter` for the underlying
graphics, it needs a version of python installed with Tk support.
The object-oriented interface uses essentially two+two classes:
1. The :class:`TurtleScreen` class defines graphics windows as a playground for
the drawing turtles. Its constructor needs a :class:`Tkinter.Canvas` or a
:class:`ScrolledCanvas` as argument. It should be used when :mod:`turtle` is
used as part of some application.
Derived from :class:`TurtleScreen` is the subclass :class:`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 :mod:`turtle` 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. :class:`RawTurtle` (alias: :class:`RawPen`) defines Turtle objects which draw
on a :class:`TurtleScreen`. Its constructor needs a Canvas, ScrolledCanvas
or TurtleScreen as argument, so the RawTurtle objects know where to draw.
Derived from RawTurtle is the subclass :class:`Turtle` (alias: :class:`Pen`),
which draws on "the" :class:`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 provides functions which are derived from the methods
of the classes :class:`Screen` and :class:`Turtle`. They have the same names as
the corresponding methods. A screen object is automativally created whenever a
function derived from 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 object-oriented interface.
.. note::
In the following documentation the argument list for functions is given.
Methods, of course, have the additional first argument *self* which is
omitted here.
Overview over available Turtle and Screen methods
=================================================
Turtle methods
--------------
Turtle motion
Move and draw
| :func:`forward` | :func:`fd`
| :func:`backward` | :func:`bk` | :func:`back`
| :func:`right` | :func:`rt`
| :func:`left` | :func:`lt`
| :func:`goto` | :func:`setpos` | :func:`setposition`
| :func:`setx`
| :func:`sety`
| :func:`setheading` | :func:`seth`
| :func:`home`
| :func:`circle`
| :func:`dot`
| :func:`stamp`
| :func:`clearstamp`
| :func:`clearstamps`
| :func:`undo`
| :func:`speed`
Tell Turtle's state
| :func:`position` | :func:`pos`
| :func:`towards`
| :func:`xcor`
| :func:`ycor`
| :func:`heading`
| :func:`distance`
Setting and measurement
| :func:`degrees`
| :func:`radians`
Pen control
Drawing state
| :func:`pendown` | :func:`pd` | :func:`down`
| :func:`penup` | :func:`pu` | :func:`up`
| :func:`pensize` | :func:`width`
| :func:`pen`
| :func:`isdown`
Color control
| :func:`color`
| :func:`pencolor`
| :func:`fillcolor`
Filling
| :func:`filling`
| :func:`begin_fill`
| :func:`end_fill`
More drawing control
| :func:`reset`
| :func:`clear`
| :func:`write`
Turtle state
Visibility
| :func:`showturtle` | :func:`st`
| :func:`hideturtle` | :func:`ht`
| :func:`isvisible`
Appearance
| :func:`shape`
| :func:`resizemode`
| :func:`shapesize` | :func:`turtlesize`
| :func:`settiltangle`
| :func:`tiltangle`
| :func:`tilt`
Using events
| :func:`onclick`
| :func:`onrelease`
| :func:`ondrag`
Special Turtle methods
| :func:`begin_poly`
| :func:`end_poly`
| :func:`get_poly`
| :func:`clone`
| :func:`getturtle` | :func:`getpen`
| :func:`getscreen`
| :func:`setundobuffer`
| :func:`undobufferentries`
Methods of TurtleScreen/Screen
------------------------------
Window control
| :func:`bgcolor`
| :func:`bgpic`
| :func:`clear` | :func:`clearscreen`
| :func:`reset` | :func:`resetscreen`
| :func:`screensize`
| :func:`setworldcoordinates`
Animation control
| :func:`delay`
| :func:`tracer`
| :func:`update`
Using screen events
| :func:`listen`
| :func:`onkey`
| :func:`onclick` | :func:`onscreenclick`
| :func:`ontimer`
Settings and special methods
| :func:`mode`
| :func:`colormode`
| :func:`getcanvas`
| :func:`getshapes`
| :func:`register_shape` | :func:`addshape`
| :func:`turtles`
| :func:`window_height`
| :func:`window_width`
Methods specific to Screen
| :func:`bye`
| :func:`exitonclick`
| :func:`setup`
| :func:`title`
Methods of RawTurtle/Turtle and corresponding functions
=======================================================
Most of the examples in this section refer to a Turtle instance called
``turtle``.
Turtle motion
-------------
.. function:: forward(distance)
fd(distance)
:param distance: a number (integer or float)
Move the turtle forward by the specified *distance*, in the direction the
turtle is headed.
>>> 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:: back(distance)
bk(distance)
backward(distance)
:param distance: a number
Move the turtle backward by *distance*, opposite to the direction the
turtle is headed. Do not change the turtle's heading.
>>> turtle.position()
(0.00, 0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00, 0.00)
.. function:: right(angle)
rt(angle)
:param angle: a number (integer or float)
Turn turtle right by *angle* units. (Units are by default degrees, but
can be set via the :func:`degrees` and :func:`radians` functions.) Angle
orientation depends on the turtle mode, see :func:`mode`.
>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0
.. function:: left(angle)
lt(angle)
:param angle: a number (integer or float)
Turn turtle left by *angle* units. (Units are by default degrees, but
can be set via the :func:`degrees` and :func:`radians` functions.) Angle
orientation depends on the turtle mode, see :func:`mode`.
>>> turtle.heading()
22.0
>>> turtle.left(45)
>>> turtle.heading()
67.0
.. function:: goto(x, y=None)
setpos(x, y=None)
setposition(x, y=None)
:param x: a number or a pair/vector of numbers
:param y: a number or ``None``
If *y* is ``None``, *x* must be a pair of coordinates or a :class:`Vec2D`
(e.g. as returned by :func:`pos`).
Move turtle to an absolute position. If the pen is down, draw line. Do
not change the turtle's orientation.
>>> 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)
.. function:: setx(x)
:param x: a number (integer or float)
Set the turtle's first coordinate to *x*, leave second coordinate
unchanged.
>>> turtle.position()
(0.00, 240.00)
>>> turtle.setx(10)
>>> turtle.position()
(10.00, 240.00)
.. function:: sety(y)
:param y: a number (integer or float)
Set the turtle's first coordinate to *y*, leave second coordinate
unchanged.
>>> turtle.position()
(0.00, 40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00, -10.00)
.. function:: setheading(to_angle)
seth(to_angle)
:param to_angle: a number (integer or float)
.. module:: tkinter.turtle
:platform: Tk
:synopsis: An environment for turtle graphics.
.. moduleauthor:: Guido van Rossum <guido@python.org>
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
=================== ====================
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
>>> turtle.setheading(90)
>>> turtle.heading()
90
The :mod:`tkinter.turtle` module provides turtle graphics primitives, in both an
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.
.. function:: home()
Move turtle to the origin -- coordinates (0,0) -- and set its heading to
its start-orientation (which depends on the mode, see :func:`mode`).
.. function:: circle(radius, extent=None, steps=None)
:param radius: a number
:param extent: a number (or ``None``)
:param steps: an integer (or ``None``)
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. May be used to draw regular polygons.
>>> turtle.circle(50)
>>> turtle.circle(120, 180) # draw a semicircle
.. function:: dot(size=None, *color)
:param size: an integer >= 1 (if given)
:param 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.
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
.. function:: 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)``.
>>> turtle.color("blue")
>>> turtle.stamp()
13
>>> turtle.fd(50)
.. function:: clearstamp(stampid)
:param stampid: an integer, must be return value of previous
:func:`stamp` call
Delete stamp with given *stampid*.
>>> turtle.color("blue")
>>> astamp = turtle.stamp()
>>> turtle.fd(50)
>>> turtle.clearstamp(astamp)
.. function:: clearstamps(n=None)
:param n: an integer (or ``None``)
Delete all or first/last *n* of turtle's stamps. If *n* is None, delete
all stamps, if *n* > 0 delete first *n* stamps, else if *n* < 0 delete
last *n* stamps.
>>> for i in range(8):
... turtle.stamp(); turtle.fd(30)
>>> turtle.clearstamps(2)
>>> turtle.clearstamps(-2)
>>> turtle.clearstamps()
.. function:: undo()
Undo (repeatedly) the last turtle action(s). Number of available
undo actions is determined by the size of the undobuffer.
>>> for i in range(4):
... turtle.fd(50); turtle.lt(80)
...
>>> for i in range(8):
... turtle.undo()
.. function:: speed(speed=None)
:param 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 means that *no* animation takes
place. forward/back makes turtle jump and likewise left/right make the
turtle turn instantly.
>>> turtle.speed(3)
Tell Turtle's state
-------------------
.. function:: position()
pos()
The procedural interface uses a pen and a canvas which are automagically created
when any of the functions are called.
Return the turtle's current location (x,y) (as a :class:`Vec2D` vector).
The :mod:`tkinter.turtle` module defines the following functions:
>>> turtle.pos()
(0.00, 240.00)
.. function:: degrees()
.. function:: towards(x, y=None)
Set angle measurement units to degrees.
:param x: a number or a pair/vector of numbers or a turtle instance
:param y: a number if *x* is a number, else ``None``
Return the angle between the line from turtle position to position specified
by (x,y), the vector or the other turtle. This depends on the turtle's start
orientation which depends on the mode - "standard"/"world" or "logo").
>>> turtle.pos()
(10.00, 10.00)
>>> turtle.towards(0,0)
225.0
.. function:: xcor()
Return the turtle's x coordinate.
>>> reset()
>>> turtle.left(60)
>>> turtle.forward(100)
>>> print turtle.xcor()
50.0
.. function:: ycor()
Return the turtle's y coordinate.
>>> reset()
>>> turtle.left(60)
>>> turtle.forward(100)
>>> print turtle.ycor()
86.6025403784
.. function:: heading()
Return the turtle's current heading (value depends on the turtle mode, see
:func:`mode`).
>>> turtle.left(67)
>>> turtle.heading()
67.0
.. function:: distance(x, y=None)
:param x: a number or a pair/vector of numbers or a turtle instance
:param y: a number if *x* is a number, else ``None``
Return the distance from the turtle to (x,y), the given vector, or the given
other turtle, in turtle step units.
>>> 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
------------------------
.. function:: degrees(fullcircle=360.0)
:param fullcircle: a number
Set angle measurement units, i.e. set number of "degrees" for a full circle.
Default value is 360 degrees.
>>> turtle.left(90)
>>> turtle.heading()
90
>>> turtle.degrees(400.0) # angle measurement in gon
>>> turtle.heading()
100
.. function:: radians()
Set angle measurement units to radians.
Set the angle measurement units to radians. Equivalent to
``degrees(2*math.pi)``.
>>> turtle.heading()
90
>>> turtle.radians()
>>> turtle.heading()
1.5707963267948966
.. function:: setup(**kwargs)
Sets the size and position of the main window. Keywords are:
Pen control
-----------
* ``width``: either a size in pixels or a fraction of the screen. The default is
50% of the screen.
Drawing state
~~~~~~~~~~~~~
* ``height``: either a size in pixels or a fraction of the screen. The default
is 50% of the screen.
.. function:: pendown()
pd()
down()
* ``startx``: starting position in pixels from the left edge of the screen.
``None`` is the default value and centers the window horizontally on screen.
Pull the pen down -- drawing when moving.
* ``starty``: starting position in pixels from the top edge of the screen.
``None`` is the default value and centers the window vertically on screen.
Examples::
.. function:: penup()
pu()
up()
# Uses default geometry: 50% x 50% of screen, centered.
setup()
Pull the pen up -- no drawing when moving.
# Sets window to 200x200 pixels, in upper left of screen
setup (width=200, height=200, startx=0, starty=0)
# Sets window to 75% of screen by 50% of screen, and centers it.
setup(width=.75, height=0.5, startx=None, starty=None)
.. function:: pensize(width=None)
width(width=None)
:param width: a positive number
.. function:: title(title_str)
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.
Set the window's title to *title*.
>>> turtle.pensize()
1
>>> turtle.pensize(10) # from here on lines of width 10 are drawn
.. function:: done()
.. function:: pen(pen=None, **pendict)
Enters the Tk main loop. The window will continue to be displayed until the
user closes it or the process is killed.
:param pen: a dictionary with some or all of the below listed keys
:param 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:
.. function:: reset()
* "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
Clear the screen, re-center the pen, and set variables to the default values.
This dicionary can be used as argument for a subsequent call to :func:`pen`
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.
>>> 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}
.. function:: clear()
Clear the screen.
.. function:: isdown()
Return ``True`` if pen is down, ``False`` if it's up.
.. function:: tracer(flag)
>>> turtle.penup()
>>> turtle.isdown()
False
>>> turtle.pendown()
>>> turtle.isdown()
True
Set tracing on/off (according to whether flag is true or not). Tracing means
line are drawn more slowly, with an animation of an arrow along the line.
Color control
~~~~~~~~~~~~~
.. function:: speed(speed)
.. function:: pencolor(*args)
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).
Return or set the pencolor.
Four input formats are allowed:
.. function:: delay(delay)
``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.
Set the speed of the turtle to *delay*, which is given in ms.
``pencolor(colorstring)``
Set pencolor to *colorstring*, which is a Tk color specification string,
such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.
``pencolor((r, g, b))``
Set pencolor to the RGB color represented by the tuple of *r*, *g*, and
*b*. Each of *r*, *g*, and *b* must be in the range 0..colormode, where
colormode is either 1.0 or 255 (see :func:`colormode`).
.. function:: forward(distance)
``pencolor(r, g, b)``
Set pencolor to the RGB color represented by *r*, *g*, and *b*. Each of
*r*, *g*, and *b* must be in the range 0..colormode.
Go forward *distance* steps.
If turtleshape is a polygon, the outline of that polygon is drawn with the
newly set pencolor.
>>> turtle.pencolor("brown")
>>> tup = (0.2, 0.8, 0.55)
>>> turtle.pencolor(tup)
>>> turtle.pencolor()
"#33cc8c"
.. function:: backward(distance)
Go backward *distance* steps.
.. function:: fillcolor(*args)
Return or set the fillcolor.
.. function:: left(angle)
Four input formats are allowed:
Turn left *angle* units. Units are by default degrees, but can be set via the
:func:`degrees` and :func:`radians` functions.
``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)``
Set fillcolor to *colorstring*, which is a Tk color specification string,
such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.
.. function:: right(angle)
``fillcolor((r, g, b))``
Set fillcolor to the RGB color represented by the tuple of *r*, *g*, and
*b*. Each of *r*, *g*, and *b* must be in the range 0..colormode, where
colormode is either 1.0 or 255 (see :func:`colormode`).
Turn right *angle* units. Units are by default degrees, but can be set via the
:func:`degrees` and :func:`radians` functions.
``fillcolor(r, g, b)``
Set fillcolor to the RGB color represented by *r*, *g*, and *b*. Each of
*r*, *g*, and *b* must be in the range 0..colormode.
If turtleshape is a polygon, the interior of that polygon is drawn
with the newly set fillcolor.
.. function:: up()
>>> turtle.fillcolor("violet")
>>> col = turtle.pencolor()
>>> turtle.fillcolor(col)
>>> turtle.fillcolor(0, .5, 0)
Move the pen up --- stop drawing.
.. function:: color(*args)
.. function:: down()
Return or set pencolor and fillcolor.
Move the pen down --- draw when moving.
Several input formats are allowed. They use 0 to 3 arguments as
follows:
``color()``
Return the current pencolor and the current fillcolor as a pair of color
specification strings as returned by :func:`pencolor` and
:func:`fillcolor`.
.. function:: width(width)
``color(colorstring)``, ``color((r,g,b))``, ``color(r,g,b)``
Inputs as in :func:`pencolor`, set both, fillcolor and pencolor, to the
given value.
Set the line width to *width*.
``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.
.. function:: color(s)
color((r, g, b))
color(r, g, b)
>>> turtle.color("red", "green")
>>> turtle.color()
("red", "green")
>>> colormode(255)
>>> color((40, 80, 120), (160, 200, 240))
>>> color()
("#285078", "#a0c8f0")
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]).
See also: Screen method :func:`colormode`.
.. function:: write(text[, move])
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.
Filling
~~~~~~~
.. function:: filling()
.. function:: fill(flag)
Return fillstate (``True`` if filling, ``False`` else).
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.
>>> turtle.begin_fill()
>>> if turtle.filling():
... turtle.pensize(5)
else:
... turtle.pensize(3)
.. function:: begin_fill()
Switch turtle into filling mode; Must eventually be followed by a corresponding
end_fill() call. Otherwise it will be ignored.
To be called just before drawing a shape to be filled.
>>> turtle.color("black", "red")
>>> turtle.begin_fill()
>>> turtle.circle(60)
>>> turtle.end_fill()
.. function:: end_fill()
End filling mode, and fill the shape; equivalent to ``fill(0)``.
Fill the shape drawn after the last call to :func:`begin_fill`.
.. function:: circle(radius[, extent])
More drawing control
~~~~~~~~~~~~~~~~~~~~
Draw a circle with radius *radius* whose center-point is *radius* units left of
the turtle. *extent* determines which part of a circle is drawn: if not given it
defaults to a full circle.
.. function:: reset()
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*.
Delete the turtle's drawings from the screen, re-center the turtle and set
variables to the default values.
>>> turtle.position()
(0.00,-22.00)
>>> turtle.heading()
100.0
>>> turtle.reset()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
.. function:: goto(x, y)
goto((x, y))
Go to co-ordinates *x*, *y*. The co-ordinates may be specified either as two
separate arguments or as a 2-tuple.
.. function:: 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.
.. function:: towards(x, y)
Return the angle of the line from the turtle's position to the point *x*, *y*.
The co-ordinates may be specified either as two separate arguments, as a
2-tuple, or as another pen object.
.. function:: write(arg, move=False, align="left", font=("Arial", 8, "normal"))
:param arg: object to be written to the TurtleScreen
:param move: True/False
:param align: one of the strings "left", "center" or right"
:param font: a triple (fontname, fontsize, fonttype)
.. function:: heading()
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.
Return the current orientation of the turtle.
>>> turtle.write("Home = ", True, align="center")
>>> turtle.write((0,0), True)
.. function:: setheading(angle)
Turtle state
------------
Set the orientation of the turtle to *angle*.
Visibility
~~~~~~~~~~
.. function:: showturtle()
st()
.. function:: position()
Make the turtle visible.
Return the current location of the turtle as an ``(x,y)`` pair.
>>> turtle.hideturtle()
>>> turtle.showturtle()
.. function:: setx(x)
.. function:: hideturtle()
ht()
Set the x coordinate of the turtle to *x*.
Make 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.
>>> turtle.hideturtle()
.. function:: sety(y)
Set the y coordinate of the turtle to *y*.
.. function:: isvisible()
Return True if the Turtle is shown, False if it's hidden.
.. function:: window_width()
>>> turtle.hideturtle()
>>> print turtle.isvisible():
False
Appearance
~~~~~~~~~~
.. function:: shape(name=None)
:param name: a string which is a valid shapename
Set turtle shape to shape with given *name* or, if name is not given, 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 :func:`register_shape`.
>>> turtle.shape()
"arrow"
>>> turtle.shape("turtle")
>>> turtle.shape()
"turtle"
.. function:: resizemode(rmode=None)
:param 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:
- "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
:func:`shapesize`.
- "noresize": no adaption of the turtle's appearance takes place.
resizemode("user") is called by :func:`shapesize` when used with arguments.
>>> turtle.resizemode("noresize")
>>> turtle.resizemode()
"noresize"
.. function:: shapesize(stretch_wid=None, stretch_len=None, outline=None)
:param stretch_wid: positive number
:param stretch_len: positive number
:param 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 its orientation, *stretch_len* is
stretchfactor in direction of its orientation, *outline* determines the width
of the shapes's outline.
>>> turtle.resizemode("user")
>>> turtle.shapesize(5, 5, 12)
>>> turtle.shapesize(outline=8)
.. function:: tilt(angle)
:param angle: a number
Rotate the turtleshape by *angle* from its current tilt-angle, but do *not*
change the turtle's heading (direction of movement).
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(30)
>>> turtle.fd(50)
>>> turtle.tilt(30)
>>> turtle.fd(50)
.. function:: settiltangle(angle)
:param angle: a 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).
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.settiltangle(45)
>>> stamp()
>>> turtle.fd(50)
>>> turtle.settiltangle(-45)
>>> stamp()
>>> turtle.fd(50)
.. function:: tiltangle()
Return the current tilt-angle, i.e. the angle between the orientation of the
turtleshape and the heading of the turtle (its direction of movement).
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(45)
>>> turtle.tiltangle()
45
Using events
------------
.. function:: onclick(fun, btn=1, add=None)
:param fun: a function with two arguments which will be called with the
coordinates of the clicked point on the canvas
:param num: number of the mouse-button, defaults to 1 (left mouse button)
:param add: ``True`` or ``False`` -- if ``True``, a new binding will be
added, otherwise it will replace a former binding
Bind *fun* to mouse-click events on this turtle. If *fun* is ``None``,
existing bindings are removed. Example for the anonymous turtle, i.e. the
procedural way:
>>> def turn(x, y):
... left(180)
...
>>> onclick(turn) # Now clicking into the turtle will turn it.
>>> onclick(None) # event-binding will be removed
.. function:: onrelease(fun, btn=1, add=None)
:param fun: a function with two arguments which will be called with the
coordinates of the clicked point on the canvas
:param num: number of the mouse-button, defaults to 1 (left mouse button)
:param add: ``True`` or ``False`` -- if ``True``, a new binding will be
added, otherwise it will replace a former binding
Bind *fun* to mouse-button-release events on this turtle. If *fun* is
``None``, existing bindings are removed.
>>> class MyTurtle(Turtle):
... def glow(self,x,y):
... self.fillcolor("red")
... def unglow(self,x,y):
... self.fillcolor("")
...
>>> turtle = MyTurtle()
>>> turtle.onclick(turtle.glow) # clicking on turtle turns fillcolor red,
>>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
.. function:: ondrag(fun, btn=1, add=None)
:param fun: a function with two arguments which will be called with the
coordinates of the clicked point on the canvas
:param num: number of the mouse-button, defaults to 1 (left mouse button)
:param add: ``True`` or ``False`` -- if ``True``, a new binding will be
added, otherwise it will replace a former binding
Bind *fun* to mouse-move events on this turtle. If *fun* is ``None``,
existing bindings are removed.
Return the width of the canvas window.
Remark: Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that turtle.
>>> turtle.ondrag(turtle.goto)
# Subsequently, clicking and dragging the Turtle will move it across
# the screen thereby producing handdrawings (if pen is down).
Special Turtle methods
----------------------
.. function:: begin_poly()
Start recording the vertices of a polygon. Current turtle position is first
vertex of polygon.
.. function:: 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:: get_poly()
Return the last recorded polygon.
>>> p = turtle.get_poly()
>>> turtle.register_shape("myFavouriteShape", p)
.. function:: clone()
Create and return a clone of the turtle with same position, heading and
turtle properties.
>>> mick = Turtle()
>>> joe = mick.clone()
.. function:: getturtle()
Return the Turtle object itself. Only reasonable use: as a function to
return the "anonymous turtle":
>>> pet = getturtle()
>>> pet.fd(50)
>>> pet
<turtle.Turtle object at 0x01417350>
>>> turtles()
[<turtle.Turtle object at 0x01417350>]
.. function:: getscreen()
Return the :class:`TurtleScreen` object the turtle is drawing on.
TurtleScreen methods can then be called for that object.
>>> ts = turtle.getscreen()
>>> ts
<turtle.Screen object at 0x01417710>
>>> ts.bgcolor("pink")
.. function:: setundobuffer(size)
:param size: an integer or ``None``
Set or disable undobuffer. 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 :func:`undo` method/function. If *size* is
``None``, the undobuffer is disabled.
>>> turtle.setundobuffer(42)
.. function:: undobufferentries()
Return number of entries in the undobuffer.
>>> while undobufferentries():
... undo()
.. _compoundshapes:
Excursus about the use of compound shapes
-----------------------------------------
To use compound turtle shapes, which consist of several polygons of different
color, you must use the helper class :class:`Shape` explicitly as described
below:
1. Create an empty Shape object of type "compound".
2. Add as many components to this object as desired, using the
:meth:`addcomponent` method.
For example:
>>> 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")
3. Now add the Shape to the Screen's shapelist and use it:
>>> register_shape("myshape", s)
>>> shape("myshape")
.. note::
The :class:`Shape` class is used internally by the :func:`register_shape`
method in different ways. The application programmer has to deal with the
Shape class *only* when using compound shapes like shown above!
Methods of TurtleScreen/Screen and corresponding functions
==========================================================
Most of the examples in this section refer to a TurtleScreen instance called
``screen``.
Window control
--------------
.. function:: bgcolor(*args)
:param args: a color string or three numbers in the range 0..colormode or a
3-tuple of such numbers
Set or return background color of the TurtleScreen.
>>> screen.bgcolor("orange")
>>> screen.bgcolor()
"orange"
>>> screen.bgcolor(0.5,0,0.5)
>>> screen.bgcolor()
"#800080"
.. function:: bgpic(picname=None)
:param picname: a string, name of a gif-file or ``"nopic"``, or ``None``
Set background image or return name of current backgroundimage. If *picname*
is a filename, set the corresponding image as background. If *picname* is
``"nopic"``, delete background image, if present. If *picname* is ``None``,
return the filename of the current backgroundimage.
>>> screen.bgpic()
"nopic"
>>> screen.bgpic("landscape.gif")
>>> screen.bgpic()
"landscape.gif"
.. function:: clear()
clearscreen()
Delete all drawings and all turtles from the TurtleScreen. Reset the now
empty TurtleScreen to its initial state: white background, no background
image, no event bindings and tracing on.
.. note::
This TurtleScreen method is available as a global function only under the
name ``clearscreen``. The global function ``clear`` is another one
derived from the Turtle method ``clear``.
.. function:: reset()
resetscreen()
Reset all Turtles on the Screen to their initial state.
.. note::
This TurtleScreen method is available as a global function only under the
name ``resetscreen``. The global function ``reset`` is another one
derived from the Turtle method ``reset``.
.. function:: screensize(canvwidth=None, canvheight=None, bg=None)
:param canvwidth: positive integer, new width of canvas in pixels
:param canvheight: positive integer, new height of canvas in pixels
:param bg: colorstring or color-tupel, new background color
If no arguments are given, return current (canvaswidth, canvasheight). Else
resize the canvas the turtles are drawing on. Do not alter the drawing
window. To observe hidden parts of the canvas, use the scrollbars. With this
method, one can make visible those parts of a drawing which were outside the
canvas before.
>>> turtle.screensize(2000,1500)
# e.g. to search for an erroneously escaped turtle ;-)
.. function:: setworldcoordinates(llx, lly, urx, ury)
:param llx: a number, x-coordinate of lower left corner of canvas
:param lly: a number, y-coordinate of lower left corner of canvas
:param urx: a number, x-coordinate of upper right corner of canvas
:param ury: a number, y-coordinate of upper right corner of canvas
Set up user-defined coordinate 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.
**ATTENTION**: in user-defined coordinate systems angles may appear
distorted.
>>> 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
-----------------
.. function:: delay(delay=None)
:param delay: positive integer
Set or return the drawing *delay* in milliseconds. (This is approximately
the time interval between two consecutived canvas updates.) The longer the
drawing delay, the slower the animation.
Optional argument:
>>> screen.delay(15)
>>> screen.delay()
15
.. function:: tracer(n=None, delay=None)
:param n: nonnegative integer
:param 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 :func:`delay`).
>>> screen.tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
... fd(dist)
... rt(90)
... dist += 2
.. function:: update()
Perform a TurtleScreen update. To be used when tracer is turned off.
See also the RawTurtle/Turtle method :func:`speed`.
Using screen events
-------------------
.. function:: 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 :func:`listen` to the onclick method.
.. function:: onkey(fun, key)
:param fun: a function with no arguments or ``None``
:param 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 the focus. (See method :func:`listen`.)
>>> def f():
... fd(50)
... lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
.. function:: onclick(fun, btn=1, add=None)
onscreenclick(fun, btn=1, add=None)
:param fun: a function with two arguments which will be called with the
coordinates of the clicked point on the canvas
:param num: number of the mouse-button, defaults to 1 (left mouse button)
:param add: ``True`` or ``False`` -- if ``True``, a new binding will be
added, otherwise it will replace a former binding
Bind *fun* to mouse-click events on this screen. If *fun* is ``None``,
existing bindings are removed.
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) # remove event binding again
.. note::
This TurtleScreen method is available as a global function only under the
name ``onscreenclick``. The global function ``onclick`` is another one
derived from the Turtle method ``onclick``.
.. function:: ontimer(fun, t=0)
:param fun: a function with no arguments
:param t: a number >= 0
Install a timer that calls *fun* after *t* milliseconds.
>>> 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
----------------------------
.. function:: mode(mode=None)
:param mode: one 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 :mod:`turtle`. Mode "logo" is
compatible with most Logo turtle graphics. Mode "world" uses user-defined
"world coordinates". **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
============ ========================= ===================
>>> mode("logo") # resets turtle heading to north
>>> mode()
"logo"
.. function:: colormode(cmode=None)
:param 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 color triples have to be in the range 0..\ *cmode*.
>>> screen.colormode()
1.0
>>> screen.colormode(255)
>>> turtle.pencolor(240,160,80)
.. function:: getcanvas()
Return the Canvas of this TurtleScreen. Useful for insiders who know what to
do with a Tkinter Canvas.
>>> cv = screen.getcanvas()
>>> cv
<turtle.ScrolledCanvas instance at 0x010742D8>
.. function:: getshapes()
Return a list of names of all currently available turtle shapes.
>>> screen.getshapes()
["arrow", "blank", "circle", ..., "turtle"]
.. function:: register_shape(name, shape=None)
addshape(name, shape=None)
There are three different ways to call this function:
(1) *name* is the name of a gif-file and *shape* is ``None``: Install the
corresponding image shape.
.. note::
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: Install the corresponding polygon shape.
(3) *name* is an arbitrary string and shape is a (compound) :class:`Shape`
object: Install the corresponding compound shape.
Add a turtle shape to TurtleScreen's shapelist. Only thusly registered
shapes can be used by issuing the command ``shape(shapename)``.
>>> screen.register_shape("turtle.gif")
>>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
.. function:: turtles()
Return the list of turtles on the screen.
>>> for turtle in screen.turtles()
... turtle.color("red")
.. function:: window_height()
Return the height of the canvas window.
Return the height of the turtle window.
>>> screen.window_height()
480
This module also does ``from math import *``, so see the documentation for the
:mod:`math` module for additional constants and functions useful for turtle
graphics.
.. function:: window_width()
Return the width of the turtle window.
>>> screen.window_width()
640
.. _screenspecific:
Methods specific to Screen, not inherited from TurtleScreen
-----------------------------------------------------------
.. function:: bye()
Shut the turtlegraphics window.
.. function:: exitonclick()
Bind bye() method to mouse clicks on the Screen.
.. function:: demo()
Exercise the module a bit.
If the value "using_IDLE" in the configuration dictionary is ``False``
(default value), also enter mainloop. Remark: If IDLE with the ``-n`` switch
(no subprocess) is used, this value should be set to ``True`` in
:file:`turtle.cfg`. In this case IDLE's own mainloop is active also for the
client script.
.. exception:: Error
.. function:: setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])
Exception raised on any error caught by this module.
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
:file:`turtle.cfg` file.
For examples, see the code of the :func:`demo` function.
:param width: if an integer, a size in pixels, if a float, a fraction of the
screen; default is 50% of screen
:param height: if an integer, the height in pixels, if a float, a fraction of
the screen; default is 75% of screen
:param startx: if positive, starting position in pixels from the left
edge of the screen, if negative from the right edge, if None,
center window horizontally
:param startx: if positive, starting position in pixels from the top
edge of the screen, if negative from the bottom edge, if None,
center window vertically
This module defines the following classes:
>>> 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
.. class:: Pen()
.. function:: title(titlestring)
Define a pen. All above functions can be called as a methods on the given pen.
The constructor automatically creates a canvas do be drawn on.
:param titlestring: a string that is shown in the titlebar of the turtle
graphics window
Set title of turtle window to *titlestring*.
>>> screen.title("Welcome to the turtle zoo!")
The public classes of the module :mod:`turtle`
==============================================
.. class:: RawTurtle(canvas)
RawPen(canvas)
:param canvas: a :class:`Tkinter.Canvas`, a :class:`ScrolledCanvas` or a
:class:`TurtleScreen`
Create a turtle. The turtle has all methods described above as "methods of
Turtle/RawTurtle".
.. class:: Turtle()
Define a pen. This is essentially a synonym for ``Pen()``; :class:`Turtle` is an
empty subclass of :class:`Pen`.
Subclass of RawTurtle, has the same interface but draws on a default
:class:`Screen` object created automatically when needed for the first time.
.. class:: RawPen(canvas)
.. class:: TurtleScreen(cv)
Define a pen which draws on a canvas *canvas*. This is useful if you want to
use the module to create graphics in a "real" program.
:param cv: a :class:`Tkinter.Canvas`
Provides screen oriented methods like :func:`setbg` etc. that are described
above.
.. _pen-rawpen-objects:
.. class:: Screen()
Turtle, Pen and RawPen Objects
------------------------------
Subclass of TurtleScreen, with :ref:`four methods added <screenspecific>`.
.. class:: ScrolledCavas(master)
Most of the global functions available in the module are also available as
methods of the :class:`Turtle`, :class:`Pen` and :class:`RawPen` classes,
affecting only the state of the given pen.
:param master: some Tkinter widget to contain the ScrolledCanvas, i.e.
a Tkinter-canvas with scrollbars added
The only method which is more powerful as a method is :func:`degrees`, which
takes an optional argument letting you specify the number of units
corresponding to a full circle:
Used by class Screen, which thus automatically provides a ScrolledCanvas as
playground for the turtles.
.. class:: Shape(type_, data)
.. method:: Turtle.degrees([fullcircle])
:param type\_: one of the strings "polygon", "image", "compound"
*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.
Data structure modeling shapes. The pair ``(type_, data)`` must follow this
specification:
=========== ===========
*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
:meth:`addcomponent` method)
=========== ===========
.. method:: addcomponent(poly, fill, outline=None)
:param poly: a polygon, i.e. a tuple of pairs of numbers
:param fill: a color the *poly* will be filled with
:param outline: a color for the poly's outline (if given)
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 :ref:`compoundshapes`.
.. 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 too. 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
* ``abs(a)`` absolute value of a
* ``a.rotate(angle)`` rotation
Help and configuration
======================
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 :func:`help` on methods or functions displays the docstrings::
>>> help(Screen.bgcolor)
Help on method bgcolor in module turtle:
bgcolor(self, *args) unbound turtle.Screen method
Set or return backgroundcolor of the TurtleScreen.
Arguments (if given): a color string or three numbers
in the range 0..colormode or a 3-tuple of such numbers.
>>> screen.bgcolor("orange")
>>> screen.bgcolor()
"orange"
>>> screen.bgcolor(0.5,0,0.5)
>>> screen.bgcolor()
"#800080"
>>> help(Turtle.penup)
Help on method penup in module turtle:
penup(self) unbound turtle.Turtle method
Pull the pen up -- no drawing when moving.
Aliases: penup | pu | up
No argument
>>> turtle.penup()
- The docstrings of the functions which are derived from methods have a modified
form::
>>> help(bgcolor)
Help on function bgcolor in module turtle:
bgcolor(*args)
Set or return backgroundcolor of the TurtleScreen.
Arguments (if given): a color string or three numbers
in the range 0..colormode or a 3-tuple of such numbers.
Example::
>>> bgcolor("orange")
>>> bgcolor()
"orange"
>>> bgcolor(0.5,0,0.5)
>>> bgcolor()
"#800080"
>>> help(penup)
Help on function penup in module turtle:
penup()
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
--------------------------------------------------
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.
.. function:: write_docstringdict(filename="turtle_docstringdict")
:param filename: a string, used as filename
Create and write docstring-dictionary to a Python script with the given
filename. This function has to be called explicitly (it is not used by the
turtle graphics classes). The docstring dictionary will be written to the
Python script :file:`{filename}.py`. It is intended to serve as a template
for translation of the docstrings into different languages.
If you (or your students) want to use :mod:`turtle` with online help in your
native language, you have to translate the docstrings and save the resulting
file as e.g. :file:`turtle_docstringdict_german.py`.
If you have an appropriate entry in your :file:`turtle.cfg` file this dictionary
will be read in at import time and will replace the original English docstrings.
At the time of this writing there are docstring dictionaries in German and in
Italian. (Requests please to glingl@aon.at.)
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 better reflects the features
of this module or which better fits 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 its 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 :meth:`Screen.setup`
method.
- Line 5 and 6 correspond to the arguments of the method
:meth:`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. make the turtle transparent), you have
to write ``fillcolor = ""`` (but all nonempty 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
:file:`turtle_docstringdict_italian.py` will be loaded at import time (if
present on the import path, e.g. in the same directory as :mod:`turtle`.
- 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.
- *using_IDLE*: Set this to ``True`` if you regularly work with IDLE and its -n
switch ("no subprocess"). This will prevent :func:`exitonclick` to enter the
mainloop.
There can be a :file:`turtle.cfg` file in the directory where :mod:`turtle` is
stored and an additional one in the current working directory. The latter will
override the settings of the first one.
The :file:`Demo/turtle` directory contains a :file:`turtle.cfg` file. You can
study it as an example and see its effects when running the demos (preferably
not from within the demo-viewer).
Demo scripts
============
There is a set of demo scripts in the turtledemo directory located in the
:file:`Demo/turtle` directory in the source distribution.
It contains:
- a set of 15 demo scripts demonstrating differet features of the new module
:mod:`turtle`
- a demo viewer :file:`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 :file:`turtledemo_two_canvases.py` demonstrates the simultaneous
use of two canvases with the turtle module. Therefore it only can be run
standalone.
- There is a :file:`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 | :func:`tracer`, delay,|
| | turtlegraphics pattern | :func:`update` |
+----------------+------------------------------+-----------------------+
| chaos | graphs verhust dynamics, | world coordinates |
| | proves 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 | :func:`ondrag` |
+----------------+------------------------------+-----------------------+
| fractalcurves | Hilbert & Koch curves | recursion |
+----------------+------------------------------+-----------------------+
| lindenmayer | ethnomathematics | L-System |
| | (indian kolams) | |
+----------------+------------------------------+-----------------------+
| minimal_hanoi | Towers of Hanoi | Rectangular Turtles |
| | | as Hanoi discs |
| | | (shape, shapesize) |
+----------------+------------------------------+-----------------------+
| paint | super minimalistic | :func:`onclick` |
| | drawing program | |
+----------------+------------------------------+-----------------------+
| peace | elementary | turtle: appearance |
| | | and animation |
+----------------+------------------------------+-----------------------+
| penrose | aperiodic tiling with | :func:`stamp` |
| | kites and darts | |
+----------------+------------------------------+-----------------------+
| planet_and_moon| simulation of | compound shapes, |
| | gravitational system | :class:`Vec2D` |
+----------------+------------------------------+-----------------------+
| tree | a (graphical) breadth | :func:`clone` |
| | first tree (using generators)| |
+----------------+------------------------------+-----------------------+
| wikipedia | a pattern from the wikipedia | :func:`clone`, |
| | article on turtle graphics | :func:`undo` |
+----------------+------------------------------+-----------------------+
| yingyang | another elementary example | :func:`circle` |
+----------------+------------------------------+-----------------------+
Have fun!
Changes since Python 2.6
========================
- The methods :meth:`Turtle.tracer`, :meth:`Turtle.window_width` and
:meth:`Turtle.window_height` have been eliminated.
Methods with these names and functionality are now available only
as methods of :class:`Screen`. The functions derived from these remain
available. (In fact already in Python 2.6 these methods were merely
duplications of the corresponding
:class:`TurtleScreen`/:class:`Screen`-methods.)
- The method :meth:`Turtle.fill` has been eliminated.
The behaviour of :meth:`begin_fill` and :meth:`end_fill`
have changed slightly: now every filling-process must be completed with an
``end_fill()`` call.
- A method :meth:`Turtle.filling` has been added. It returns a boolean
value: ``True`` if a filling process is under way, ``False`` otherwise.
This behaviour corresponds to a ``fill()`` call without arguments in
Python 2.6
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -411,6 +411,7 @@ Christopher Lindblad
Bjorn Lindqvist
Per Lindqvist
Eric Lindvall
Gregor Lingl
Nick Lockwood
Stephanie Lockwood
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