Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ryPythonTurtleDemo.pdf

Renyuan Lyu
November 13, 2014
730

 ryPythonTurtleDemo.pdf

Renyuan Lyu

November 13, 2014
Tweet

Transcript

  1. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\bytedesign.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:43 1 #!/usr/bin/env python3 2 """ turtle-example-suite: 3 4 tdemo_bytedesign.py 5 6 An example adapted from the example-suite 7 of PythonCard's turtle graphics. 8 9 It's based on an article in BYTE magazine 10 Problem Solving with Logo: Using Turtle 11 Graphics to Redraw a Design 12 November 1982, p. 118 - 134 13 14 ------------------------------------------- 15 16 Due to the statement 17 18 t.delay(0) 19 20 in line 152, which sets the animation delay 21 to 0, this animation runs in "line per line" 22 mode as fast as possible. 23 """ 24 25 import math 26 from turtle import Turtle, mainloop 27 from time import clock 28 29 # wrapper for any additional drawing routines 30 # that need to know about each other 31 class Designer(Turtle): 32 33 def design(self, homePos, scale): 34 self.up() 35 for i in range(5): 36 self.forward(64.65 * scale) 37 self.down() 38 self.wheel(self.position(), scale) 39 self.up() 40 self.backward(64.65 * scale) 41 self.right(72) 42 self.up() 43 self.goto(homePos) 44 self.right(36) 45 self.forward(24.5 * scale) 46 self.right(198) 47 self.down() 48 self.centerpiece(46 * scale, 143.4, scale) 49 self.getscreen().tracer(True) 50 51 def wheel(self, initpos, scale): 52 self.right(54) 53 for i in range(4): 54 self.pentpiece(initpos, scale) 55 self.down() 56 self.left(36) 57 for i in range(5): -1- 2
  2. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\bytedesign.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:43 58 self.tripiece(initpos, scale) 59 self.left(36) 60 for i in range(5): 61 self.down() 62 self.right(72) 63 self.forward(28 * scale) 64 self.up() 65 self.backward(28 * scale) 66 self.left(54) 67 self.getscreen().update() 68 69 def tripiece(self, initpos, scale): 70 oldh = self.heading() 71 self.down() 72 self.backward(2.5 * scale) 73 self.tripolyr(31.5 * scale, scale) 74 self.up() 75 self.goto(initpos) 76 self.setheading(oldh) 77 self.down() 78 self.backward(2.5 * scale) 79 self.tripolyl(31.5 * scale, scale) 80 self.up() 81 self.goto(initpos) 82 self.setheading(oldh) 83 self.left(72) 84 self.getscreen().update() 85 86 def pentpiece(self, initpos, scale): 87 oldh = self.heading() 88 self.up() 89 self.forward(29 * scale) 90 self.down() 91 for i in range(5): 92 self.forward(18 * scale) 93 self.right(72) 94 self.pentr(18 * scale, 75, scale) 95 self.up() 96 self.goto(initpos) 97 self.setheading(oldh) 98 self.forward(29 * scale) 99 self.down() 100 for i in range(5): 101 self.forward(18 * scale) 102 self.right(72) 103 self.pentl(18 * scale, 75, scale) 104 self.up() 105 self.goto(initpos) 106 self.setheading(oldh) 107 self.left(72) 108 self.getscreen().update() 109 110 def pentl(self, side, ang, scale): 111 if side < (2 * scale): return 112 self.forward(side) 113 self.left(ang) 114 self.pentl(side - (.38 * scale), ang, scale) -2- 3
  3. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\bytedesign.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:43 115 116 def pentr(self, side, ang, scale): 117 if side < (2 * scale): return 118 self.forward(side) 119 self.right(ang) 120 self.pentr(side - (.38 * scale), ang, scale) 121 122 def tripolyr(self, side, scale): 123 if side < (4 * scale): return 124 self.forward(side) 125 self.right(111) 126 self.forward(side / 1.78) 127 self.right(111) 128 self.forward(side / 1.3) 129 self.right(146) 130 self.tripolyr(side * .75, scale) 131 132 def tripolyl(self, side, scale): 133 if side < (4 * scale): return 134 self.forward(side) 135 self.left(111) 136 self.forward(side / 1.78) 137 self.left(111) 138 self.forward(side / 1.3) 139 self.left(146) 140 self.tripolyl(side * .75, scale) 141 142 def centerpiece(self, s, a, scale): 143 self.forward(s); self.left(a) 144 if s < (7.5 * scale): 145 return 146 self.centerpiece(s - (1.2 * scale), a, scale) 147 148 def main(): 149 t = Designer() 150 t.speed(0) 151 t.hideturtle() 152 t.getscreen().delay(0) 153 t.getscreen().tracer(0) 154 at = clock() 155 t.design(t.position(), 2) 156 et = clock() 157 return "runtime: %.2f sec." % (et-at) 158 159 if __name__ == '__main__': 160 msg = main() 161 print(msg) 162 mainloop() 163 -3- 4
  4. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\chaos.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:43 1 # File: tdemo_chaos.py 2 # Author: Gregor Lingl 3 # Date: 2009-06-24 4 5 # A demonstration of chaos 6 7 from turtle import * 8 9 N = 80 10 11 def f(x): 12 return 3.9*x*(1-x) 13 14 def g(x): 15 return 3.9*(x-x**2) 16 17 def h(x): 18 return 3.9*x-3.9*x*x 19 20 def jumpto(x, y): 21 penup(); goto(x,y) 22 23 def line(x1, y1, x2, y2): 24 jumpto(x1, y1) 25 pendown() 26 goto(x2, y2) 27 28 def coosys(): 29 line(-1, 0, N+1, 0) 30 line(0, -0.1, 0, 1.1) 31 32 def plot(fun, start, colour): 33 pencolor(colour) 34 x = start 35 jumpto(0, x) 36 pendown() 37 dot(5) 38 for i in range(N): 39 x=fun(x) 40 goto(i+1,x) 41 dot(5) 42 43 def main(): 44 reset() 45 setworldcoordinates(-1.0,-0.1, N+1, 1.1) 46 speed(0) 47 hideturtle() 48 coosys() 49 plot(f, 0.35, "blue") 50 plot(g, 0.35, "green") 51 plot(h, 0.35, "red") 52 # Now zoom in: 53 for s in range(100): 54 setworldcoordinates(0.5*s,-0.1, N+1, 1.1) 55 return "Done!" 56 57 if __name__ == "__main__": -1- 5
  5. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\chaos.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:43 58 main() 59 mainloop() 60 -2- 6
  6. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\clock.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:44 1 #!/usr/bin/env python3 2 # -*- coding: cp1252 -*- 3 """ turtle-example-suite: 4 5 tdemo_clock.py 6 7 Enhanced clock-program, showing date 8 and time 9 ------------------------------------ 10 Press STOP to exit the program! 11 ------------------------------------ 12 """ 13 from turtle import * 14 from datetime import datetime 15 16 def jump(distanz, winkel=0): 17 penup() 18 right(winkel) 19 forward(distanz) 20 left(winkel) 21 pendown() 22 23 def hand(laenge, spitze): 24 fd(laenge*1.15) 25 rt(90) 26 fd(spitze/2.0) 27 lt(120) 28 fd(spitze) 29 lt(120) 30 fd(spitze) 31 lt(120) 32 fd(spitze/2.0) 33 34 def make_hand_shape(name, laenge, spitze): 35 reset() 36 jump(-laenge*0.15) 37 begin_poly() 38 hand(laenge, spitze) 39 end_poly() 40 hand_form = get_poly() 41 register_shape(name, hand_form) 42 43 def clockface(radius): 44 reset() 45 pensize(7) 46 for i in range(60): 47 jump(radius) 48 if i % 5 == 0: 49 fd(25) 50 jump(-radius-25) 51 else: 52 dot(3) 53 jump(-radius) 54 rt(6) 55 56 def setup(): 57 global second_hand, minute_hand, hour_hand, writer -1- 7
  7. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\clock.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:44 58 mode("logo") 59 make_hand_shape("second_hand", 125, 25) 60 make_hand_shape("minute_hand", 130, 25) 61 make_hand_shape("hour_hand", 90, 25) 62 clockface(160) 63 second_hand = Turtle() 64 second_hand.shape("second_hand") 65 second_hand.color("gray20", "gray80") 66 minute_hand = Turtle() 67 minute_hand.shape("minute_hand") 68 minute_hand.color("blue1", "red1") 69 hour_hand = Turtle() 70 hour_hand.shape("hour_hand") 71 hour_hand.color("blue3", "red3") 72 for hand in second_hand, minute_hand, hour_hand: 73 hand.resizemode("user") 74 hand.shapesize(1, 1, 3) 75 hand.speed(0) 76 ht() 77 writer = Turtle() 78 #writer.mode("logo") 79 writer.ht() 80 writer.pu() 81 writer.bk(85) 82 83 def wochentag(t): 84 wochentag = ["Monday", "Tuesday", "Wednesday", 85 "Thursday", "Friday", "Saturday", "Sunday"] 86 return wochentag[t.weekday()] 87 88 def datum(z): 89 monat = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "June", 90 "July", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."] 91 j = z.year 92 m = monat[z.month - 1] 93 t = z.day 94 return "%s %d %d" % (m, t, j) 95 96 def tick(): 97 t = datetime.today() 98 sekunde = t.second + t.microsecond*0.000001 99 minute = t.minute + sekunde/60.0 100 stunde = t.hour + minute/60.0 101 try: 102 tracer(False) # Terminator can occur here 103 writer.clear() 104 writer.home() 105 writer.forward(65) 106 writer.write(wochentag(t), 107 align="center", font=("Courier", 14, "bold")) 108 writer.back(150) 109 writer.write(datum(t), 110 align="center", font=("Courier", 14, "bold")) 111 writer.forward(85) 112 tracer(True) 113 second_hand.setheading(6*sekunde) # or here 114 minute_hand.setheading(6*minute) -2- 8
  8. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\clock.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:44 115 hour_hand.setheading(30*stunde) 116 tracer(True) 117 ontimer(tick, 100) 118 except Terminator: 119 pass # turtledemo user pressed STOP 120 121 def main(): 122 tracer(False) 123 setup() 124 tracer(True) 125 tick() 126 return "EVENTLOOP" 127 128 if __name__ == "__main__": 129 mode("logo") 130 msg = main() 131 print(msg) 132 mainloop() 133 -3- 9
  9. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\colormixer.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:44 1 # colormixer 2 3 from turtle import Screen, Turtle, mainloop 4 5 class ColorTurtle(Turtle): 6 7 def __init__(self, x, y): 8 Turtle.__init__(self) 9 self.shape("turtle") 10 self.resizemode("user") 11 self.shapesize(3,3,5) 12 self.pensize(10) 13 self._color = [0,0,0] 14 self.x = x 15 self._color[x] = y 16 self.color(self._color) 17 self.speed(0) 18 self.left(90) 19 self.pu() 20 self.goto(x,0) 21 self.pd() 22 self.sety(1) 23 self.pu() 24 self.sety(y) 25 self.pencolor("gray25") 26 self.ondrag(self.shift) 27 28 def shift(self, x, y): 29 self.sety(max(0,min(y,1))) 30 self._color[self.x] = self.ycor() 31 self.fillcolor(self._color) 32 setbgcolor() 33 34 def setbgcolor(): 35 screen.bgcolor(red.ycor(), green.ycor(), blue.ycor()) 36 37 def main(): 38 global screen, red, green, blue 39 screen = Screen() 40 screen.delay(0) 41 screen.setworldcoordinates(-1, -0.3, 3, 1.3) 42 43 red = ColorTurtle(0, .5) 44 green = ColorTurtle(1, .5) 45 blue = ColorTurtle(2, .5) 46 setbgcolor() 47 48 writer = Turtle() 49 writer.ht() 50 writer.pu() 51 writer.goto(1,1.15) 52 writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic"))) 53 return "EVENTLOOP" 54 55 if __name__ == "__main__": 56 msg = main() 57 print(msg) -1- 10
  10. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\forest.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:45 1 #!/usr/bin/env python3 2 """ turtlegraphics-example-suite: 3 4 tdemo_forest.py 5 6 Displays a 'forest' of 3 breadth-first-trees 7 similar to the one in tree. 8 For further remarks see tree.py 9 10 This example is a 'breadth-first'-rewrite of 11 a Logo program written by Erich Neuwirth. See 12 http://homepage.univie.ac.at/erich.neuwirth/ 13 """ 14 from turtle import Turtle, colormode, tracer, mainloop 15 from random import randrange 16 from time import clock 17 18 def symRandom(n): 19 return randrange(-n,n+1) 20 21 def randomize( branchlist, angledist, sizedist ): 22 return [ (angle+symRandom(angledist), 23 sizefactor*1.01**symRandom(sizedist)) 24 for angle, sizefactor in branchlist ] 25 26 def randomfd( t, distance, parts, angledist ): 27 for i in range(parts): 28 t.left(symRandom(angledist)) 29 t.forward( (1.0 * distance)/parts ) 30 31 def tree(tlist, size, level, widthfactor, branchlists, angledist=10, sizedist=5): 32 # benutzt Liste von turtles und Liste von Zweiglisten, 33 # fuer jede turtle eine! 34 if level > 0: 35 lst = [] 36 brs = [] 37 for t, branchlist in list(zip(tlist,branchlists)): 38 t.pensize( size * widthfactor ) 39 t.pencolor( 255 - (180 - 11 * level + symRandom(15)), 40 180 - 11 * level + symRandom(15), 41 0 ) 42 t.pendown() 43 randomfd(t, size, level, angledist ) 44 yield 1 45 for angle, sizefactor in branchlist: 46 t.left(angle) 47 lst.append(t.clone()) 48 brs.append(randomize(branchlist, angledist, sizedist)) 49 t.right(angle) 50 for x in tree(lst, size*sizefactor, level-1, widthfactor, brs, 51 angledist, sizedist): 52 yield None 53 54 55 def start(t,x,y): 56 colormode(255) 57 t.reset() -1- 12
  11. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\forest.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:45 58 t.speed(0) 59 t.hideturtle() 60 t.left(90) 61 t.penup() 62 t.setpos(x,y) 63 t.pendown() 64 65 def doit1(level, pen): 66 pen.hideturtle() 67 start(pen, 20, -208) 68 t = tree( [pen], 80, level, 0.1, [[ (45,0.69), (0,0.65), (-45,0.71) ]] ) 69 return t 70 71 def doit2(level, pen): 72 pen.hideturtle() 73 start(pen, -135, -130) 74 t = tree( [pen], 120, level, 0.1, [[ (45,0.69), (-45,0.71) ]] ) 75 return t 76 77 def doit3(level, pen): 78 pen.hideturtle() 79 start(pen, 190, -90) 80 t = tree( [pen], 100, level, 0.1, [[ (45,0.7), (0,0.72), (-45,0.65) ]] ) 81 return t 82 83 # Hier 3 Baumgeneratoren: 84 def main(): 85 p = Turtle() 86 p.ht() 87 tracer(75,0) 88 u = doit1(6, Turtle(undobuffersize=1)) 89 s = doit2(7, Turtle(undobuffersize=1)) 90 t = doit3(5, Turtle(undobuffersize=1)) 91 a = clock() 92 while True: 93 done = 0 94 for b in u,s,t: 95 try: 96 b.__next__() 97 except: 98 done += 1 99 if done == 3: 100 break 101 102 tracer(1,10) 103 b = clock() 104 return "runtime: %.2f sec." % (b-a) 105 106 if __name__ == '__main__': 107 main() 108 mainloop() 109 -2- 13
  12. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\fractalcurves.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:45 1 #!/usr/bin/env python3 2 """ turtle-example-suite: 3 4 tdemo_fractalCurves.py 5 6 This program draws two fractal-curve-designs: 7 (1) A hilbert curve (in a box) 8 (2) A combination of Koch-curves. 9 10 The CurvesTurtle class and the fractal-curve- 11 methods are taken from the PythonCard example 12 scripts for turtle-graphics. 13 """ 14 from turtle import * 15 from time import sleep, clock 16 17 class CurvesTurtle(Pen): 18 # example derived from 19 # Turtle Geometry: The Computer as a Medium for Exploring Mathematics 20 # by Harold Abelson and Andrea diSessa 21 # p. 96-98 22 def hilbert(self, size, level, parity): 23 if level == 0: 24 return 25 # rotate and draw first subcurve with opposite parity to big curve 26 self.left(parity * 90) 27 self.hilbert(size, level - 1, -parity) 28 # interface to and draw second subcurve with same parity as big curve 29 self.forward(size) 30 self.right(parity * 90) 31 self.hilbert(size, level - 1, parity) 32 # third subcurve 33 self.forward(size) 34 self.hilbert(size, level - 1, parity) 35 # fourth subcurve 36 self.right(parity * 90) 37 self.forward(size) 38 self.hilbert(size, level - 1, -parity) 39 # a final turn is needed to make the turtle 40 # end up facing outward from the large square 41 self.left(parity * 90) 42 43 # Visual Modeling with Logo: A Structural Approach to Seeing 44 # by James Clayson 45 # Koch curve, after Helge von Koch who introduced this geometric figure in 1904 46 # p. 146 47 def fractalgon(self, n, rad, lev, dir): 48 import math 49 50 # if dir = 1 turn outward 51 # if dir = -1 turn inward 52 edge = 2 * rad * math.sin(math.pi / n) 53 self.pu() 54 self.fd(rad) 55 self.pd() 56 self.rt(180 - (90 * (n - 2) / n)) 57 for i in range(n): -1- 14
  13. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\fractalcurves.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:45 58 self.fractal(edge, lev, dir) 59 self.rt(360 / n) 60 self.lt(180 - (90 * (n - 2) / n)) 61 self.pu() 62 self.bk(rad) 63 self.pd() 64 65 # p. 146 66 def fractal(self, dist, depth, dir): 67 if depth < 1: 68 self.fd(dist) 69 return 70 self.fractal(dist / 3, depth - 1, dir) 71 self.lt(60 * dir) 72 self.fractal(dist / 3, depth - 1, dir) 73 self.rt(120 * dir) 74 self.fractal(dist / 3, depth - 1, dir) 75 self.lt(60 * dir) 76 self.fractal(dist / 3, depth - 1, dir) 77 78 def main(): 79 ft = CurvesTurtle() 80 81 ft.reset() 82 ft.speed(0) 83 ft.ht() 84 ft.getscreen().tracer(1,0) 85 ft.pu() 86 87 size = 6 88 ft.setpos(-33*size, -32*size) 89 ft.pd() 90 91 ta=clock() 92 ft.fillcolor("red") 93 ft.begin_fill() 94 ft.fd(size) 95 96 ft.hilbert(size, 6, 1) 97 98 # frame 99 ft.fd(size) 100 for i in range(3): 101 ft.lt(90) 102 ft.fd(size*(64+i%2)) 103 ft.pu() 104 for i in range(2): 105 ft.fd(size) 106 ft.rt(90) 107 ft.pd() 108 for i in range(4): 109 ft.fd(size*(66+i%2)) 110 ft.rt(90) 111 ft.end_fill() 112 tb=clock() 113 res = "Hilbert: %.2fsec. " % (tb-ta) 114 -2- 15
  14. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\fractalcurves.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:45 115 sleep(3) 116 117 ft.reset() 118 ft.speed(0) 119 ft.ht() 120 ft.getscreen().tracer(1,0) 121 122 ta=clock() 123 ft.color("black", "blue") 124 ft.begin_fill() 125 ft.fractalgon(3, 250, 4, 1) 126 ft.end_fill() 127 ft.begin_fill() 128 ft.color("red") 129 ft.fractalgon(3, 200, 4, -1) 130 ft.end_fill() 131 tb=clock() 132 res += "Koch: %.2fsec." % (tb-ta) 133 return res 134 135 if __name__ == '__main__': 136 msg = main() 137 print(msg) 138 mainloop() 139 -3- 16
  15. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\lindenmayer.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:45 1 #!/usr/bin/env python3 2 """ turtle-example-suite: 3 4 xtx_lindenmayer_indian.py 5 6 Each morning women in Tamil Nadu, in southern 7 India, place designs, created by using rice 8 flour and known as kolam on the thresholds of 9 their homes. 10 11 These can be described by Lindenmayer systems, 12 which can easily be implemented with turtle 13 graphics and Python. 14 15 Two examples are shown here: 16 (1) the snake kolam 17 (2) anklets of Krishna 18 19 Taken from Marcia Ascher: Mathematics 20 Elsewhere, An Exploration of Ideas Across 21 Cultures 22 23 """ 24 ################################ 25 # Mini Lindenmayer tool 26 ############################### 27 28 from turtle import * 29 30 def replace( seq, replacementRules, n ): 31 for i in range(n): 32 newseq = "" 33 for element in seq: 34 newseq = newseq + replacementRules.get(element,element) 35 seq = newseq 36 return seq 37 38 def draw( commands, rules ): 39 for b in commands: 40 try: 41 rules[b]() 42 except TypeError: 43 try: 44 draw(rules[b], rules) 45 except: 46 pass 47 48 49 def main(): 50 ################################ 51 # Example 1: Snake kolam 52 ################################ 53 54 55 def r(): 56 right(45) 57 -1- 17
  16. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\lindenmayer.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:45 58 def l(): 59 left(45) 60 61 def f(): 62 forward(7.5) 63 64 snake_rules = {"-":r, "+":l, "f":f, "b":"f+f+f--f--f+f+f"} 65 snake_replacementRules = {"b": "b+f+b--f--b+f+b"} 66 snake_start = "b--f--b--f" 67 68 drawing = replace(snake_start, snake_replacementRules, 3) 69 70 reset() 71 speed(3) 72 tracer(1,0) 73 ht() 74 up() 75 backward(195) 76 down() 77 draw(drawing, snake_rules) 78 79 from time import sleep 80 sleep(3) 81 82 ################################ 83 # Example 2: Anklets of Krishna 84 ################################ 85 86 def A(): 87 color("red") 88 circle(10,90) 89 90 def B(): 91 from math import sqrt 92 color("black") 93 l = 5/sqrt(2) 94 forward(l) 95 circle(l, 270) 96 forward(l) 97 98 def F(): 99 color("green") 100 forward(10) 101 102 krishna_rules = {"a":A, "b":B, "f":F} 103 krishna_replacementRules = {"a" : "afbfa", "b" : "afbfbfbfa" } 104 krishna_start = "fbfbfbfb" 105 106 reset() 107 speed(0) 108 tracer(3,0) 109 ht() 110 left(45) 111 drawing = replace(krishna_start, krishna_replacementRules, 3) 112 draw(drawing, krishna_rules) 113 tracer(1) 114 return "Done!" -2- 18
  17. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\lindenmayer.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:45 115 116 if __name__=='__main__': 117 msg = main() 118 print(msg) 119 mainloop() 120 -3- 19
  18. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\minimal_hanoi.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:46 1 #!/usr/bin/env python3 2 """ turtle-example-suite: 3 4 tdemo_minimal_hanoi.py 5 6 A minimal 'Towers of Hanoi' animation: 7 A tower of 6 discs is transferred from the 8 left to the right peg. 9 10 An imho quite elegant and concise 11 implementation using a tower class, which 12 is derived from the built-in type list. 13 14 Discs are turtles with shape "square", but 15 stretched to rectangles by shapesize() 16 --------------------------------------- 17 To exit press STOP button 18 --------------------------------------- 19 """ 20 from turtle import * 21 22 class Disc(Turtle): 23 def __init__(self, n): 24 Turtle.__init__(self, shape="square", visible=False) 25 self.pu() 26 self.shapesize(1.5, n*1.5, 2) # square-->rectangle 27 self.fillcolor(n/6., 0, 1-n/6.) 28 self.st() 29 30 class Tower(list): 31 "Hanoi tower, a subclass of built-in type list" 32 def __init__(self, x): 33 "create an empty tower. x is x-position of peg" 34 self.x = x 35 def push(self, d): 36 d.setx(self.x) 37 d.sety(-150+34*len(self)) 38 self.append(d) 39 def pop(self): 40 d = list.pop(self) 41 d.sety(150) 42 return d 43 44 def hanoi(n, from_, with_, to_): 45 if n > 0: 46 hanoi(n-1, from_, to_, with_) 47 to_.push(from_.pop()) 48 hanoi(n-1, with_, from_, to_) 49 50 def play(): 51 onkey(None,"space") 52 clear() 53 try: 54 hanoi(6, t1, t2, t3) 55 write("press STOP button to exit", 56 align="center", font=("Courier", 16, "bold")) 57 except Terminator: -1- 20
  19. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\minimal_hanoi.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:46 58 pass # turtledemo user pressed STOP 59 60 def main(): 61 global t1, t2, t3 62 ht(); penup(); goto(0, -225) # writer turtle 63 t1 = Tower(-250) 64 t2 = Tower(0) 65 t3 = Tower(250) 66 # make tower of 6 discs 67 for i in range(6,0,-1): 68 t1.push(Disc(i)) 69 # prepare spartanic user interface ;-) 70 write("press spacebar to start game", 71 align="center", font=("Courier", 16, "bold")) 72 onkey(play, "space") 73 listen() 74 return "EVENTLOOP" 75 76 if __name__=="__main__": 77 msg = main() 78 print(msg) 79 mainloop() 80 -2- 21
  20. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\nim.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:46 1 """ turtle-example-suite: 2 3 tdemo_nim.py 4 5 Play nim against the computer. The player 6 who takes the last stick is the winner. 7 8 Implements the model-view-controller 9 design pattern. 10 """ 11 12 13 import turtle 14 import random 15 import time 16 17 SCREENWIDTH = 640 18 SCREENHEIGHT = 480 19 20 MINSTICKS = 7 21 MAXSTICKS = 31 22 23 HUNIT = SCREENHEIGHT // 12 24 WUNIT = SCREENWIDTH // ((MAXSTICKS // 5) * 11 + (MAXSTICKS % 5) * 2) 25 26 SCOLOR = (63, 63, 31) 27 HCOLOR = (255, 204, 204) 28 COLOR = (204, 204, 255) 29 30 def randomrow(): 31 return random.randint(MINSTICKS, MAXSTICKS) 32 33 def computerzug(state): 34 xored = state[0] ^ state[1] ^ state[2] 35 if xored == 0: 36 return randommove(state) 37 for z in range(3): 38 s = state[z] ^ xored 39 if s <= state[z]: 40 move = (z, s) 41 return move 42 43 def randommove(state): 44 m = max(state) 45 while True: 46 z = random.randint(0,2) 47 if state[z] > (m > 1): 48 break 49 rand = random.randint(m > 1, state[z]-1) 50 return z, rand 51 52 53 class NimModel(object): 54 def __init__(self, game): 55 self.game = game 56 57 def setup(self): -1- 22
  21. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\nim.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:46 58 if self.game.state not in [Nim.CREATED, Nim.OVER]: 59 return 60 self.sticks = [randomrow(), randomrow(), randomrow()] 61 self.player = 0 62 self.winner = None 63 self.game.view.setup() 64 self.game.state = Nim.RUNNING 65 66 def move(self, row, col): 67 maxspalte = self.sticks[row] 68 self.sticks[row] = col 69 self.game.view.notify_move(row, col, maxspalte, self.player) 70 if self.game_over(): 71 self.game.state = Nim.OVER 72 self.winner = self.player 73 self.game.view.notify_over() 74 elif self.player == 0: 75 self.player = 1 76 row, col = computerzug(self.sticks) 77 self.move(row, col) 78 self.player = 0 79 80 def game_over(self): 81 return self.sticks == [0, 0, 0] 82 83 def notify_move(self, row, col): 84 if self.sticks[row] <= col: 85 return 86 self.move(row, col) 87 88 89 class Stick(turtle.Turtle): 90 def __init__(self, row, col, game): 91 turtle.Turtle.__init__(self, visible=False) 92 self.row = row 93 self.col = col 94 self.game = game 95 x, y = self.coords(row, col) 96 self.shape("square") 97 self.shapesize(HUNIT/10.0, WUNIT/20.0) 98 self.speed(0) 99 self.pu() 100 self.goto(x,y) 101 self.color("white") 102 self.showturtle() 103 104 def coords(self, row, col): 105 packet, remainder = divmod(col, 5) 106 x = (3 + 11 * packet + 2 * remainder) * WUNIT 107 y = (2 + 3 * row) * HUNIT 108 return x - SCREENWIDTH // 2 + WUNIT // 2, SCREENHEIGHT // 2 - y - HUNIT // 2 109 110 def makemove(self, x, y): 111 if self.game.state != Nim.RUNNING: 112 return 113 self.game.controller.notify_move(self.row, self.col) 114 -2- 23
  22. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\nim.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:46 115 116 class NimView(object): 117 def __init__(self, game): 118 self.game = game 119 self.screen = game.screen 120 self.model = game.model 121 self.screen.colormode(255) 122 self.screen.tracer(False) 123 self.screen.bgcolor((240, 240, 255)) 124 self.writer = turtle.Turtle(visible=False) 125 self.writer.pu() 126 self.writer.speed(0) 127 self.sticks = {} 128 for row in range(3): 129 for col in range(MAXSTICKS): 130 self.sticks[(row, col)] = Stick(row, col, game) 131 self.display("... a moment please ...") 132 self.screen.tracer(True) 133 134 def display(self, msg1, msg2=None): 135 self.screen.tracer(False) 136 self.writer.clear() 137 if msg2 is not None: 138 self.writer.goto(0, - SCREENHEIGHT // 2 + 48) 139 self.writer.pencolor("red") 140 self.writer.write(msg2, align="center", font=("Courier",18,"bold")) 141 self.writer.goto(0, - SCREENHEIGHT // 2 + 20) 142 self.writer.pencolor("black") 143 self.writer.write(msg1, align="center", font=("Courier",14,"bold")) 144 self.screen.tracer(True) 145 146 def setup(self): 147 self.screen.tracer(False) 148 for row in range(3): 149 for col in range(self.model.sticks[row]): 150 self.sticks[(row, col)].color(SCOLOR) 151 for row in range(3): 152 for col in range(self.model.sticks[row], MAXSTICKS): 153 self.sticks[(row, col)].color("white") 154 self.display("Your turn! Click leftmost stick to remove.") 155 self.screen.tracer(True) 156 157 def notify_move(self, row, col, maxspalte, player): 158 if player == 0: 159 farbe = HCOLOR 160 for s in range(col, maxspalte): 161 self.sticks[(row, s)].color(farbe) 162 else: 163 self.display(" ... thinking ... ") 164 time.sleep(0.5) 165 self.display(" ... thinking ... aaah ...") 166 farbe = COLOR 167 for s in range(maxspalte-1, col-1, -1): 168 time.sleep(0.2) 169 self.sticks[(row, s)].color(farbe) 170 self.display("Your turn! Click leftmost stick to remove.") 171 -3- 24
  23. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\nim.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:46 172 def notify_over(self): 173 if self.game.model.winner == 0: 174 msg2 = "Congrats. You're the winner!!!" 175 else: 176 msg2 = "Sorry, the computer is the winner." 177 self.display("To play again press space bar. To leave press ESC.", msg2) 178 179 def clear(self): 180 if self.game.state == Nim.OVER: 181 self.screen.clear() 182 183 184 class NimController(object): 185 186 def __init__(self, game): 187 self.game = game 188 self.sticks = game.view.sticks 189 self.BUSY = False 190 for stick in self.sticks.values(): 191 stick.onclick(stick.makemove) 192 self.game.screen.onkey(self.game.model.setup, "space") 193 self.game.screen.onkey(self.game.view.clear, "Escape") 194 self.game.view.display("Press space bar to start game") 195 self.game.screen.listen() 196 197 def notify_move(self, row, col): 198 if self.BUSY: 199 return 200 self.BUSY = True 201 self.game.model.notify_move(row, col) 202 self.BUSY = False 203 204 205 class Nim(object): 206 CREATED = 0 207 RUNNING = 1 208 OVER = 2 209 def __init__(self, screen): 210 self.state = Nim.CREATED 211 self.screen = screen 212 self.model = NimModel(self) 213 self.view = NimView(self) 214 self.controller = NimController(self) 215 216 217 def main(): 218 mainscreen = turtle.Screen() 219 mainscreen.mode("standard") 220 mainscreen.setup(SCREENWIDTH, SCREENHEIGHT) 221 nim = Nim(mainscreen) 222 return "EVENTLOOP" 223 224 if __name__ == "__main__": 225 main() 226 turtle.mainloop() 227 -4- 25
  24. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\paint.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:46 1 #!/usr/bin/env python3 2 """ turtle-example-suite: 3 4 tdemo_paint.py 5 6 A simple event-driven paint program 7 8 - left mouse button moves turtle 9 - middle mouse button changes color 10 - right mouse button toogles betweem pen up 11 (no line drawn when the turtle moves) and 12 pen down (line is drawn). If pen up follows 13 at least two pen-down moves, the polygon that 14 includes the starting point is filled. 15 ------------------------------------------- 16 Play around by clicking into the canvas 17 using all three mouse buttons. 18 ------------------------------------------- 19 To exit press STOP button 20 ------------------------------------------- 21 """ 22 from turtle import * 23 24 def switchupdown(x=0, y=0): 25 if pen()["pendown"]: 26 end_fill() 27 up() 28 else: 29 down() 30 begin_fill() 31 32 def changecolor(x=0, y=0): 33 global colors 34 colors = colors[1:]+colors[:1] 35 color(colors[0]) 36 37 def main(): 38 global colors 39 shape("circle") 40 resizemode("user") 41 shapesize(.5) 42 width(3) 43 colors=["red", "green", "blue", "yellow"] 44 color(colors[0]) 45 switchupdown() 46 onscreenclick(goto,1) 47 onscreenclick(changecolor,2) 48 onscreenclick(switchupdown,3) 49 return "EVENTLOOP" 50 51 if __name__ == "__main__": 52 msg = main() 53 print(msg) 54 mainloop() 55 -1- 26
  25. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\peace.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:46 1 #!/usr/bin/env python3 2 """ turtle-example-suite: 3 4 tdemo_peace.py 5 6 A simple drawing suitable as a beginner's 7 programming example. Aside from the 8 peacecolors assignment and the for loop, 9 it only uses turtle commands. 10 """ 11 12 from turtle import * 13 14 def main(): 15 peacecolors = ("red3", "orange", "yellow", 16 "seagreen4", "orchid4", 17 "royalblue1", "dodgerblue4") 18 19 reset() 20 Screen() 21 up() 22 goto(-320,-195) 23 width(70) 24 25 for pcolor in peacecolors: 26 color(pcolor) 27 down() 28 forward(640) 29 up() 30 backward(640) 31 left(90) 32 forward(66) 33 right(90) 34 35 width(25) 36 color("white") 37 goto(0,-170) 38 down() 39 40 circle(170) 41 left(90) 42 forward(340) 43 up() 44 left(180) 45 forward(170) 46 right(45) 47 down() 48 forward(170) 49 up() 50 backward(170) 51 left(90) 52 down() 53 forward(170) 54 up() 55 56 goto(0,300) # vanish if hideturtle() is not available ;-) 57 return "Done!" -1- 27
  26. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\peace.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:46 58 59 if __name__ == "__main__": 60 main() 61 mainloop() 62 -2- 28
  27. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\penrose.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:47 1 #!/usr/bin/env python3 2 """ xturtle-example-suite: 3 4 xtx_kites_and_darts.py 5 6 Constructs two aperiodic penrose-tilings, 7 consisting of kites and darts, by the method 8 of inflation in six steps. 9 10 Starting points are the patterns "sun" 11 consisting of five kites and "star" 12 consisting of five darts. 13 14 For more information see: 15 http://en.wikipedia.org/wiki/Penrose_tiling 16 ------------------------------------------- 17 """ 18 from turtle import * 19 from math import cos, pi 20 from time import clock, sleep 21 22 f = (5**0.5-1)/2.0 # (sqrt(5)-1)/2 -- golden ratio 23 d = 2 * cos(3*pi/10) 24 25 def kite(l): 26 fl = f * l 27 lt(36) 28 fd(l) 29 rt(108) 30 fd(fl) 31 rt(36) 32 fd(fl) 33 rt(108) 34 fd(l) 35 rt(144) 36 37 def dart(l): 38 fl = f * l 39 lt(36) 40 fd(l) 41 rt(144) 42 fd(fl) 43 lt(36) 44 fd(fl) 45 rt(144) 46 fd(l) 47 rt(144) 48 49 def inflatekite(l, n): 50 if n == 0: 51 px, py = pos() 52 h, x, y = int(heading()), round(px,3), round(py,3) 53 tiledict[(h,x,y)] = True 54 return 55 fl = f * l 56 lt(36) 57 inflatedart(fl, n-1) -1- 29
  28. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\penrose.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:47 58 fd(l) 59 rt(144) 60 inflatekite(fl, n-1) 61 lt(18) 62 fd(l*d) 63 rt(162) 64 inflatekite(fl, n-1) 65 lt(36) 66 fd(l) 67 rt(180) 68 inflatedart(fl, n-1) 69 lt(36) 70 71 def inflatedart(l, n): 72 if n == 0: 73 px, py = pos() 74 h, x, y = int(heading()), round(px,3), round(py,3) 75 tiledict[(h,x,y)] = False 76 return 77 fl = f * l 78 inflatekite(fl, n-1) 79 lt(36) 80 fd(l) 81 rt(180) 82 inflatedart(fl, n-1) 83 lt(54) 84 fd(l*d) 85 rt(126) 86 inflatedart(fl, n-1) 87 fd(l) 88 rt(144) 89 90 def draw(l, n, th=2): 91 clear() 92 l = l * f**n 93 shapesize(l/100.0, l/100.0, th) 94 for k in tiledict: 95 h, x, y = k 96 setpos(x, y) 97 setheading(h) 98 if tiledict[k]: 99 shape("kite") 100 color("black", (0, 0.75, 0)) 101 else: 102 shape("dart") 103 color("black", (0.75, 0, 0)) 104 stamp() 105 106 def sun(l, n): 107 for i in range(5): 108 inflatekite(l, n) 109 lt(72) 110 111 def star(l,n): 112 for i in range(5): 113 inflatedart(l, n) 114 lt(72) -2- 30
  29. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\penrose.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:47 115 116 def makeshapes(): 117 tracer(0) 118 begin_poly() 119 kite(100) 120 end_poly() 121 register_shape("kite", get_poly()) 122 begin_poly() 123 dart(100) 124 end_poly() 125 register_shape("dart", get_poly()) 126 tracer(1) 127 128 def start(): 129 reset() 130 ht() 131 pu() 132 makeshapes() 133 resizemode("user") 134 135 def test(l=200, n=4, fun=sun, startpos=(0,0), th=2): 136 global tiledict 137 goto(startpos) 138 setheading(0) 139 tiledict = {} 140 a = clock() 141 tracer(0) 142 fun(l, n) 143 b = clock() 144 draw(l, n, th) 145 tracer(1) 146 c = clock() 147 print("Calculation: %7.4f s" % (b - a)) 148 print("Drawing: %7.4f s" % (c - b)) 149 print("Together: %7.4f s" % (c - a)) 150 nk = len([x for x in tiledict if tiledict[x]]) 151 nd = len([x for x in tiledict if not tiledict[x]]) 152 print("%d kites and %d darts = %d pieces." % (nk, nd, nk+nd)) 153 154 def demo(fun=sun): 155 start() 156 for i in range(8): 157 a = clock() 158 test(300, i, fun) 159 b = clock() 160 t = b - a 161 if t < 2: 162 sleep(2 - t) 163 164 def main(): 165 #title("Penrose-tiling with kites and darts.") 166 mode("logo") 167 bgcolor(0.3, 0.3, 0) 168 demo(sun) 169 sleep(2) 170 demo(star) 171 pencolor("black") -3- 31
  30. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\penrose.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:47 172 goto(0,-200) 173 pencolor(0.7,0.7,1) 174 write("Please wait...", 175 align="center", font=('Arial Black', 36, 'bold')) 176 test(600, 8, startpos=(70, 117)) 177 return "Done" 178 179 if __name__ == "__main__": 180 msg = main() 181 mainloop() 182 -4- 32
  31. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\planet_and_moon.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:47 1 #!/usr/bin/env python3 2 """ turtle-example-suite: 3 4 tdemo_planets_and_moon.py 5 6 Gravitational system simulation using the 7 approximation method from Feynman-lectures, 8 p.9-8, using turtlegraphics. 9 10 Example: heavy central body, light planet, 11 very light moon! 12 Planet has a circular orbit, moon a stable 13 orbit around the planet. 14 15 You can hold the movement temporarily by 16 pressing the left mouse button with the 17 mouse over the scrollbar of the canvas. 18 19 """ 20 from turtle import Shape, Turtle, mainloop, Vec2D as Vec 21 from time import sleep 22 23 G = 8 24 25 class GravSys(object): 26 def __init__(self): 27 self.planets = [] 28 self.t = 0 29 self.dt = 0.01 30 def init(self): 31 for p in self.planets: 32 p.init() 33 def start(self): 34 for i in range(10000): 35 self.t += self.dt 36 for p in self.planets: 37 p.step() 38 39 class Star(Turtle): 40 def __init__(self, m, x, v, gravSys, shape): 41 Turtle.__init__(self, shape=shape) 42 self.penup() 43 self.m = m 44 self.setpos(x) 45 self.v = v 46 gravSys.planets.append(self) 47 self.gravSys = gravSys 48 self.resizemode("user") 49 self.pendown() 50 def init(self): 51 dt = self.gravSys.dt 52 self.a = self.acc() 53 self.v = self.v + 0.5*dt*self.a 54 def acc(self): 55 a = Vec(0,0) 56 for planet in self.gravSys.planets: 57 if planet != self: -1- 33
  32. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\planet_and_moon.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:47 58 v = planet.pos()-self.pos() 59 a += (G*planet.m/abs(v)**3)*v 60 return a 61 def step(self): 62 dt = self.gravSys.dt 63 self.setpos(self.pos() + dt*self.v) 64 if self.gravSys.planets.index(self) != 0: 65 self.setheading(self.towards(self.gravSys.planets[0])) 66 self.a = self.acc() 67 self.v = self.v + dt*self.a 68 69 ## create compound yellow/blue turtleshape for planets 70 71 def main(): 72 s = Turtle() 73 s.reset() 74 s.getscreen().tracer(0,0) 75 s.ht() 76 s.pu() 77 s.fd(6) 78 s.lt(90) 79 s.begin_poly() 80 s.circle(6, 180) 81 s.end_poly() 82 m1 = s.get_poly() 83 s.begin_poly() 84 s.circle(6,180) 85 s.end_poly() 86 m2 = s.get_poly() 87 88 planetshape = Shape("compound") 89 planetshape.addcomponent(m1,"orange") 90 planetshape.addcomponent(m2,"blue") 91 s.getscreen().register_shape("planet", planetshape) 92 s.getscreen().tracer(1,0) 93 94 ## setup gravitational system 95 gs = GravSys() 96 sun = Star(1000000, Vec(0,0), Vec(0,-2.5), gs, "circle") 97 sun.color("yellow") 98 sun.shapesize(1.8) 99 sun.pu() 100 earth = Star(12500, Vec(210,0), Vec(0,195), gs, "planet") 101 earth.pencolor("green") 102 earth.shapesize(0.8) 103 moon = Star(1, Vec(220,0), Vec(0,295), gs, "planet") 104 moon.pencolor("blue") 105 moon.shapesize(0.5) 106 gs.init() 107 gs.start() 108 return "Done!" 109 110 if __name__ == '__main__': 111 main() 112 mainloop() 113 -2- 34
  33. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\round_dance.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:47 1 """ turtle-example-suite: 2 3 tdemo_round_dance.py 4 5 (Needs version 1.1 of the turtle module that 6 comes with Python 3.1) 7 8 Dancing turtles have a compound shape 9 consisting of a series of triangles of 10 decreasing size. 11 12 Turtles march along a circle while rotating 13 pairwise in opposite direction, with one 14 exception. Does that breaking of symmetry 15 enhance the attractiveness of the example? 16 17 Press any key to stop the animation. 18 19 Technically: demonstrates use of compound 20 shapes, transformation of shapes as well as 21 cloning turtles. The animation is 22 controlled through update(). 23 """ 24 25 from turtle import * 26 27 def stop(): 28 global running 29 running = False 30 31 def main(): 32 global running 33 clearscreen() 34 bgcolor("gray10") 35 tracer(False) 36 shape("triangle") 37 f = 0.793402 38 phi = 9.064678 39 s = 5 40 c = 1 41 # create compound shape 42 sh = Shape("compound") 43 for i in range(10): 44 shapesize(s) 45 p =get_shapepoly() 46 s *= f 47 c *= f 48 tilt(-phi) 49 sh.addcomponent(p, (c, 0.25, 1-c), "black") 50 register_shape("multitri", sh) 51 # create dancers 52 shapesize(1) 53 shape("multitri") 54 pu() 55 setpos(0, -200) 56 dancers = [] 57 for i in range(180): -1- 35
  34. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\round_dance.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:47 58 fd(7) 59 tilt(-4) 60 lt(2) 61 update() 62 if i % 12 == 0: 63 dancers.append(clone()) 64 home() 65 # dance 66 running = True 67 onkeypress(stop) 68 listen() 69 cs = 1 70 while running: 71 ta = -4 72 for dancer in dancers: 73 dancer.fd(7) 74 dancer.lt(2) 75 dancer.tilt(ta) 76 ta = -4 if ta > 0 else 2 77 if cs < 180: 78 right(4) 79 shapesize(cs) 80 cs *= 1.005 81 update() 82 return "DONE!" 83 84 if __name__=='__main__': 85 print(main()) 86 mainloop() 87 -2- 36
  35. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\tree.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:48 1 #!/usr/bin/env python3 2 """ turtle-example-suite: 3 4 tdemo_tree.py 5 6 Displays a 'breadth-first-tree' - in contrast 7 to the classical Logo tree drawing programs, 8 which use a depth-first-algorithm. 9 10 Uses: 11 (1) a tree-generator, where the drawing is 12 quasi the side-effect, whereas the generator 13 always yields None. 14 (2) Turtle-cloning: At each branching point 15 the current pen is cloned. So in the end 16 there are 1024 turtles. 17 """ 18 from turtle import Turtle, mainloop 19 from time import clock 20 21 def tree(plist, l, a, f): 22 """ plist is list of pens 23 l is length of branch 24 a is half of the angle between 2 branches 25 f is factor by which branch is shortened 26 from level to level.""" 27 if l > 3: 28 lst = [] 29 for p in plist: 30 p.forward(l) 31 q = p.clone() 32 p.left(a) 33 q.right(a) 34 lst.append(p) 35 lst.append(q) 36 for x in tree(lst, l*f, a, f): 37 yield None 38 39 def maketree(): 40 p = Turtle() 41 p.setundobuffer(None) 42 p.hideturtle() 43 p.speed(0) 44 p.getscreen().tracer(30,0) 45 p.left(90) 46 p.penup() 47 p.forward(-210) 48 p.pendown() 49 t = tree([p], 200, 65, 0.6375) 50 for x in t: 51 pass 52 print(len(p.getscreen().turtles())) 53 54 def main(): 55 a=clock() 56 maketree() 57 b=clock() -1- 37
  36. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\tree.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:48 58 return "done: %.2f sec." % (b-a) 59 60 if __name__ == "__main__": 61 msg = main() 62 print(msg) 63 mainloop() 64 -2- 38
  37. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\two_canvases.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:48 1 """turtledemo.two_canvases 2 3 Use TurtleScreen and RawTurtle to draw on two 4 distinct canvases in a separate windows. The 5 new window must be separately closed in 6 addition to pressing the STOP button. 7 """ 8 9 from turtle import TurtleScreen, RawTurtle, TK 10 11 def main(): 12 root = TK.Tk() 13 cv1 = TK.Canvas(root, width=300, height=200, bg="#ddffff") 14 cv2 = TK.Canvas(root, width=300, height=200, bg="#ffeeee") 15 cv1.pack() 16 cv2.pack() 17 18 s1 = TurtleScreen(cv1) 19 s1.bgcolor(0.85, 0.85, 1) 20 s2 = TurtleScreen(cv2) 21 s2.bgcolor(1, 0.85, 0.85) 22 23 p = RawTurtle(s1) 24 q = RawTurtle(s2) 25 26 p.color("red", (1, 0.85, 0.85)) 27 p.width(3) 28 q.color("blue", (0.85, 0.85, 1)) 29 q.width(3) 30 31 for t in p,q: 32 t.shape("turtle") 33 t.lt(36) 34 35 q.lt(180) 36 37 for t in p, q: 38 t.begin_fill() 39 for i in range(5): 40 for t in p, q: 41 t.fd(50) 42 t.lt(72) 43 for t in p,q: 44 t.end_fill() 45 t.lt(54) 46 t.pu() 47 t.bk(50) 48 49 return "EVENTLOOP" 50 51 52 if __name__ == '__main__': 53 main() 54 TK.mainloop() # keep window open until user closes it 55 -1- 39
  38. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\wikipedia.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:48 1 """ turtle-example-suite: 2 3 tdemo_wikipedia3.py 4 5 This example is 6 inspired by the Wikipedia article on turtle 7 graphics. (See example wikipedia1 for URLs) 8 9 First we create (ne-1) (i.e. 35 in this 10 example) copies of our first turtle p. 11 Then we let them perform their steps in 12 parallel. 13 14 Followed by a complete undo(). 15 """ 16 from turtle import Screen, Turtle, mainloop 17 from time import clock, sleep 18 19 def mn_eck(p, ne,sz): 20 turtlelist = [p] 21 #create ne-1 additional turtles 22 for i in range(1,ne): 23 q = p.clone() 24 q.rt(360.0/ne) 25 turtlelist.append(q) 26 p = q 27 for i in range(ne): 28 c = abs(ne/2.0-i)/(ne*.7) 29 # let those ne turtles make a step 30 # in parallel: 31 for t in turtlelist: 32 t.rt(360./ne) 33 t.pencolor(1-c,0,c) 34 t.fd(sz) 35 36 def main(): 37 s = Screen() 38 s.bgcolor("black") 39 p=Turtle() 40 p.speed(0) 41 p.hideturtle() 42 p.pencolor("red") 43 p.pensize(3) 44 45 s.tracer(36,0) 46 47 at = clock() 48 mn_eck(p, 36, 19) 49 et = clock() 50 z1 = et-at 51 52 sleep(1) 53 54 at = clock() 55 while any([t.undobufferentries() for t in s.turtles()]): 56 for t in s.turtles(): 57 t.undo() -1- 40
  39. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\wikipedia.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:48 58 et = clock() 59 return "runtime: %.3f sec" % (z1+et-at) 60 61 62 if __name__ == '__main__': 63 msg = main() 64 print(msg) 65 mainloop() 66 -2- 41
  40. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\yinyang.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:49 1 #!/usr/bin/env python3 2 """ turtle-example-suite: 3 4 tdemo_yinyang.py 5 6 Another drawing suitable as a beginner's 7 programming example. 8 9 The small circles are drawn by the circle 10 command. 11 12 """ 13 14 from turtle import * 15 16 def yin(radius, color1, color2): 17 width(3) 18 color("black", color1) 19 begin_fill() 20 circle(radius/2., 180) 21 circle(radius, 180) 22 left(180) 23 circle(-radius/2., 180) 24 end_fill() 25 left(90) 26 up() 27 forward(radius*0.35) 28 right(90) 29 down() 30 color(color1, color2) 31 begin_fill() 32 circle(radius*0.15) 33 end_fill() 34 left(90) 35 up() 36 backward(radius*0.35) 37 down() 38 left(90) 39 40 def main(): 41 reset() 42 yin(200, "black", "white") 43 yin(200, "white", "black") 44 ht() 45 return "Done!" 46 47 if __name__ == '__main__': 48 main() 49 mainloop() 50 -1- 42
  41. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\__main__.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:42 1 #!/usr/bin/env python3 2 3 """ 4 ---------------------------------------------- 5 turtleDemo - Help 6 ---------------------------------------------- 7 8 This document has two sections: 9 10 (1) How to use the demo viewer 11 (2) How to add your own demos to the demo repository 12 13 14 (1) How to use the demo viewer. 15 16 Select a demoscript from the example menu. 17 The (syntax coloured) source code appears in the left 18 source code window. IT CANNOT BE EDITED, but ONLY VIEWED! 19 20 The demo viewer windows can be resized. The divider between text 21 and canvas can be moved by grabbing it with the mouse. The text font 22 size can be changed from the menu and with Control/Command '-'/'+'. 23 It can also be changed on most systems with Control-mousewheel 24 when the mouse is over the text. 25 26 Press START button to start the demo. 27 Stop execution by pressing the STOP button. 28 Clear screen by pressing the CLEAR button. 29 Restart by pressing the START button again. 30 31 SPECIAL demos, such as clock.py are those which run EVENTDRIVEN. 32 33 Press START button to start the demo. 34 35 - Until the EVENTLOOP is entered everything works 36 as in an ordinary demo script. 37 38 - When the EVENTLOOP is entered, you control the 39 application by using the mouse and/or keys (or it's 40 controlled by some timer events) 41 To stop it you can and must press the STOP button. 42 43 While the EVENTLOOP is running, the examples menu is disabled. 44 45 - Only after having pressed the STOP button, you may 46 restart it or choose another example script. 47 48 * * * * * * * * 49 In some rare situations there may occur interferences/conflicts 50 between events concerning the demo script and those concerning the 51 demo-viewer. (They run in the same process.) Strange behaviour may be 52 the consequence and in the worst case you must close and restart the 53 viewer. 54 * * * * * * * * 55 56 57 (2) How to add your own demos to the demo repository -1- 43
  42. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\__main__.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:42 58 59 - Place the file in the same directory as turtledemo/__main__.py 60 IMPORTANT! When imported, the demo should not modify the system 61 by calling functions in other modules, such as sys, tkinter, or 62 turtle. Global variables should be initialized in main(). 63 64 - The code must contain a main() function which will 65 be executed by the viewer (see provided example scripts). 66 It may return a string which will be displayed in the Label below 67 the source code window (when execution has finished.) 68 69 - In order to run mydemo.py by itself, such as during development, 70 add the following at the end of the file: 71 72 if __name__ == '__main__': 73 main() 74 mainloop() # keep window open 75 76 python -m turtledemo.mydemo # will then run it 77 78 - If the demo is EVENT DRIVEN, main must return the string 79 "EVENTLOOP". This informs the demo viewer that the script is 80 still running and must be stopped by the user! 81 82 If an "EVENTLOOP" demo runs by itself, as with clock, which uses 83 ontimer, or minimal_hanoi, which loops by recursion, then the 84 code should catch the turtle.Terminator exception that will be 85 raised when the user presses the STOP button. (Paint is not such 86 a demo; it only acts in response to mouse clicks and movements.) 87 """ 88 import sys 89 import os 90 91 from tkinter import * 92 from idlelib.Percolator import Percolator 93 from idlelib.ColorDelegator import ColorDelegator 94 from idlelib.textView import view_text 95 from turtledemo import __doc__ as about_turtledemo 96 97 import turtle 98 import time 99 100 demo_dir = os.path.dirname(os.path.abspath(__file__)) 101 darwin = sys.platform == 'darwin' 102 103 STARTUP = 1 104 READY = 2 105 RUNNING = 3 106 DONE = 4 107 EVENTDRIVEN = 5 108 109 menufont = ("Arial", 12, NORMAL) 110 btnfont = ("Arial", 12, 'bold') 111 txtfont = ['Lucida Console', 10, 'normal'] 112 113 MINIMUM_FONT_SIZE = 6 114 MAXIMUM_FONT_SIZE = 100 -2- 44
  43. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\__main__.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:42 115 font_sizes = [8, 9, 10, 11, 12, 14, 18, 20, 22, 24, 30] 116 117 def getExampleEntries(): 118 return [entry[:-3] for entry in os.listdir(demo_dir) if 119 entry.endswith(".py") and entry[0] != '_'] 120 121 help_entries = ( # (help_label, help_doc) 122 ('Turtledemo help', __doc__), 123 ('About turtledemo', about_turtledemo), 124 ('About turtle module', turtle.__doc__), 125 ) 126 127 class DemoWindow(object): 128 129 def __init__(self, filename=None): 130 self.root = root = turtle._root = Tk() 131 root.title('Python turtle-graphics examples') 132 root.wm_protocol("WM_DELETE_WINDOW", self._destroy) 133 134 if darwin: 135 import subprocess 136 # Make sure we are the currently activated OS X application 137 # so that our menu bar appears. 138 p = subprocess.Popen( 139 [ 140 'osascript', 141 '-e', 'tell application "System Events"', 142 '-e', 'set frontmost of the first process whose ' 143 'unix id is {} to true'.format(os.getpid()), 144 '-e', 'end tell', 145 ], 146 stderr=subprocess.DEVNULL, 147 stdout=subprocess.DEVNULL,) 148 149 root.grid_rowconfigure(0, weight=1) 150 root.grid_columnconfigure(0, weight=1) 151 root.grid_columnconfigure(1, minsize=90, weight=1) 152 root.grid_columnconfigure(2, minsize=90, weight=1) 153 root.grid_columnconfigure(3, minsize=90, weight=1) 154 155 self.mBar = Menu(root, relief=RAISED, borderwidth=2) 156 self.mBar.add_cascade(menu=self.makeLoadDemoMenu(self.mBar), 157 label='Examples', underline=0) 158 self.mBar.add_cascade(menu=self.makeFontMenu(self.mBar), 159 label='Fontsize', underline=0) 160 self.mBar.add_cascade(menu=self.makeHelpMenu(self.mBar), 161 label='Help', underline=0) 162 root['menu'] = self.mBar 163 164 pane = PanedWindow(orient=HORIZONTAL, sashwidth=5, 165 sashrelief=SOLID, bg='#ddd') 166 pane.add(self.makeTextFrame(pane)) 167 pane.add(self.makeGraphFrame(pane)) 168 pane.grid(row=0, columnspan=4, sticky='news') 169 170 self.output_lbl = Label(root, height= 1, text=" --- ", bg="#ddf", 171 font=("Arial", 16, 'normal'), borderwidth=2, -3- 45
  44. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\__main__.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:42 172 relief=RIDGE) 173 self.start_btn = Button(root, text=" START ", font=btnfont, 174 fg="white", disabledforeground = "#fed", 175 command=self.startDemo) 176 self.stop_btn = Button(root, text=" STOP ", font=btnfont, 177 fg="white", disabledforeground = "#fed", 178 command=self.stopIt) 179 self.clear_btn = Button(root, text=" CLEAR ", font=btnfont, 180 fg="white", disabledforeground="#fed", 181 command = self.clearCanvas) 182 self.output_lbl.grid(row=1, column=0, sticky='news', padx=(0,5)) 183 self.start_btn.grid(row=1, column=1, sticky='ew') 184 self.stop_btn.grid(row=1, column=2, sticky='ew') 185 self.clear_btn.grid(row=1, column=3, sticky='ew') 186 187 Percolator(self.text).insertfilter(ColorDelegator()) 188 self.dirty = False 189 self.exitflag = False 190 if filename: 191 self.loadfile(filename) 192 self.configGUI(DISABLED, DISABLED, DISABLED, 193 "Choose example from menu", "black") 194 self.state = STARTUP 195 196 197 def onResize(self, event): 198 cwidth = self._canvas.winfo_width() 199 cheight = self._canvas.winfo_height() 200 self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth) 201 self._canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight) 202 203 def makeTextFrame(self, root): 204 self.text_frame = text_frame = Frame(root) 205 self.text = text = Text(text_frame, name='text', padx=5, 206 wrap='none', width=45) 207 208 self.vbar = vbar = Scrollbar(text_frame, name='vbar') 209 vbar['command'] = text.yview 210 vbar.pack(side=LEFT, fill=Y) 211 self.hbar = hbar = Scrollbar(text_frame, name='hbar', orient=HORIZONTAL) 212 hbar['command'] = text.xview 213 hbar.pack(side=BOTTOM, fill=X) 214 text['yscrollcommand'] = vbar.set 215 text['xscrollcommand'] = hbar.set 216 217 text['font'] = tuple(txtfont) 218 shortcut = 'Command' if darwin else 'Control' 219 text.bind_all('<%s-minus>' % shortcut, self.decrease_size) 220 text.bind_all('<%s-underscore>' % shortcut, self.decrease_size) 221 text.bind_all('<%s-equal>' % shortcut, self.increase_size) 222 text.bind_all('<%s-plus>' % shortcut, self.increase_size) 223 text.bind('<Control-MouseWheel>', self.update_mousewheel) 224 text.bind('<Control-Button-4>', self.increase_size) 225 text.bind('<Control-Button-5>', self.decrease_size) 226 227 text.pack(side=LEFT, fill=BOTH, expand=1) 228 return text_frame -4- 46
  45. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\__main__.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:42 229 230 def makeGraphFrame(self, root): 231 turtle._Screen._root = root 232 self.canvwidth = 1000 233 self.canvheight = 800 234 turtle._Screen._canvas = self._canvas = canvas = turtle.ScrolledCanvas( 235 root, 800, 600, self.canvwidth, self.canvheight) 236 canvas.adjustScrolls() 237 canvas._rootwindow.bind('<Configure>', self.onResize) 238 canvas._canvas['borderwidth'] = 0 239 240 self.screen = _s_ = turtle.Screen() 241 turtle.TurtleScreen.__init__(_s_, _s_._canvas) 242 self.scanvas = _s_._canvas 243 turtle.RawTurtle.screens = [_s_] 244 return canvas 245 246 def set_txtsize(self, size): 247 txtfont[1] = size 248 self.text['font'] = tuple(txtfont) 249 self.output_lbl['text'] = 'Font size %d' % size 250 251 def decrease_size(self, dummy=None): 252 self.set_txtsize(max(txtfont[1] - 1, MINIMUM_FONT_SIZE)) 253 return 'break' 254 255 def increase_size(self, dummy=None): 256 self.set_txtsize(min(txtfont[1] + 1, MAXIMUM_FONT_SIZE)) 257 return 'break' 258 259 def update_mousewheel(self, event): 260 # For wheel up, event.delte = 120 on Windows, -1 on darwin. 261 # X-11 sends Control-Button-4 event instead. 262 if (event.delta < 0) == (not darwin): 263 return self.decrease_size() 264 else: 265 return self.increase_size() 266 267 def configGUI(self, start, stop, clear, txt="", color="blue"): 268 self.start_btn.config(state=start, 269 bg="#d00" if start == NORMAL else "#fca") 270 self.stop_btn.config(state=stop, 271 bg="#d00" if stop == NORMAL else "#fca") 272 self.clear_btn.config(state=clear, 273 bg="#d00" if clear == NORMAL else"#fca") 274 self.output_lbl.config(text=txt, fg=color) 275 276 def makeLoadDemoMenu(self, master): 277 menu = Menu(master) 278 279 for entry in getExampleEntries(): 280 def load(entry=entry): 281 self.loadfile(entry) 282 menu.add_command(label=entry, underline=0, 283 font=menufont, command=load) 284 return menu 285 -5- 47
  46. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\__main__.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:42 286 def makeFontMenu(self, master): 287 menu = Menu(master) 288 menu.add_command(label="Decrease (C-'-')", command=self.decrease_size, 289 font=menufont) 290 menu.add_command(label="Increase (C-'+')", command=self.increase_size, 291 font=menufont) 292 menu.add_separator() 293 294 for size in font_sizes: 295 def resize(size=size): 296 self.set_txtsize(size) 297 menu.add_command(label=str(size), underline=0, 298 font=menufont, command=resize) 299 return menu 300 301 def makeHelpMenu(self, master): 302 menu = Menu(master) 303 304 for help_label, help_file in help_entries: 305 def show(help_label=help_label, help_file=help_file): 306 view_text(self.root, help_label, help_file) 307 menu.add_command(label=help_label, font=menufont, command=show) 308 return menu 309 310 def refreshCanvas(self): 311 if self.dirty: 312 self.screen.clear() 313 self.dirty=False 314 315 def loadfile(self, filename): 316 self.clearCanvas() 317 turtle.TurtleScreen._RUNNING = False 318 modname = 'turtledemo.' + filename 319 __import__(modname) 320 self.module = sys.modules[modname] 321 with open(self.module.__file__, 'r') as f: 322 chars = f.read() 323 self.text.delete("1.0", "end") 324 self.text.insert("1.0", chars) 325 self.root.title(filename + " - a Python turtle graphics example") 326 self.configGUI(NORMAL, DISABLED, DISABLED, 327 "Press start button", "red") 328 self.state = READY 329 330 def startDemo(self): 331 self.refreshCanvas() 332 self.dirty = True 333 turtle.TurtleScreen._RUNNING = True 334 self.configGUI(DISABLED, NORMAL, DISABLED, 335 "demo running...", "black") 336 self.screen.clear() 337 self.screen.mode("standard") 338 self.state = RUNNING 339 340 try: 341 result = self.module.main() 342 if result == "EVENTLOOP": -6- 48
  47. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\__main__.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:42 343 self.state = EVENTDRIVEN 344 else: 345 self.state = DONE 346 except turtle.Terminator: 347 self.state = DONE 348 result = "stopped!" 349 if self.state == DONE: 350 self.configGUI(NORMAL, DISABLED, NORMAL, 351 result) 352 elif self.state == EVENTDRIVEN: 353 self.exitflag = True 354 self.configGUI(DISABLED, NORMAL, DISABLED, 355 "use mouse/keys or STOP", "red") 356 357 def clearCanvas(self): 358 self.refreshCanvas() 359 self.screen._delete("all") 360 self.scanvas.config(cursor="") 361 self.configGUI(NORMAL, DISABLED, DISABLED) 362 363 def stopIt(self): 364 if self.exitflag: 365 self.clearCanvas() 366 self.exitflag = False 367 self.configGUI(NORMAL, DISABLED, DISABLED, 368 "STOPPED!", "red") 369 turtle.TurtleScreen._RUNNING = False 370 371 def _destroy(self): 372 self.root.destroy() 373 374 375 def main(): 376 demo = DemoWindow() 377 demo.root.mainloop() 378 379 if __name__ == '__main__': 380 main() 381 -7- 49
  48. C:\Users\renyuan\Desktop\ryTurtle2014\turtledemo\__init__.py 2014年 年 年 年11月 月 月 月3日 日 日

    日 下 下 下 下下 下 下 下 07:42 1 """ 2 -------------------------------------- 3 About this viewer 4 -------------------------------------- 5 6 Tiny demo viewer to view turtle graphics example scripts. 7 8 Quickly and dirtyly assembled by Gregor Lingl. 9 June, 2006 10 11 For more information see: turtledemo - Help 12 13 Have fun! 14 """ 15 -1- 50
  49. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 1/40 Turtle star Turtle can draw intricate shapes using programs that repeat simple moves. 24.1. turtle — Turtle graphics 24.1.1. 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. After an import turtle, 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.right(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 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 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 TurtleScreen class defines graphics windows as a playground for the drawing turtles. Its constructor needs a tkinter.Canvas or a ScrolledCanvas as argument. It should be used when turtle is used as part of some application. The function Screen() returns a singleton object of a TurtleScreen subclass. This function should be used when turtle is used as a standalone tool for doing graphics. As a singleton object, inheriting from its class is not possible. from turtle import * color('red', 'yellow') begin_fill() while True: forward(200) left(170) if abs(pos()) < 1: break end_fill() done() 51
  50. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 2/40 All methods of TurtleScreen/Screen also exist as functions, i.e. as part of the procedure-oriented interface. 2. RawTurtle (alias: RawPen) defines Turtle objects which draw on a TurtleScreen. Its constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle objects know where to draw. Derived from RawTurtle is the subclass Turtle (alias: Pen), which draws on “the” Screen instance which is automatically created, if not already present. All methods of RawTurtle/Turtle also exist as functions, i.e. part of the procedure- oriented interface. The procedural interface provides functions which are derived from the methods of the classes Screen and Turtle. They have the same names as the corresponding methods. A screen object is automatically 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 on 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. 24.1.2. Overview of available Turtle and Screen methods 24.1.2.1. Turtle methods Turtle motion Move and draw forward() | fd() backward() | bk() | back() right() | rt() left() | lt() goto() | setpos() | setposition() setx() sety() setheading() | seth() home() circle() dot() stamp() clearstamp() clearstamps() undo() 52
  51. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 3/40 speed() Tell Turtle’s state position() | pos() towards() xcor() ycor() heading() distance() Setting and measurement degrees() radians() Pen control Drawing state pendown() | pd() | down() penup() | pu() | up() pensize() | width() pen() isdown() Color control color() pencolor() fillcolor() Filling filling() begin_fill() end_fill() More drawing control reset() clear() write() Turtle state Visibility showturtle() | st() hideturtle() | ht() isvisible() Appearance shape() resizemode() shapesize() | turtlesize() shearfactor() settiltangle() 53
  52. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 4/40 tiltangle() tilt() shapetransform() get_shapepoly() Using events onclick() onrelease() ondrag() Special Turtle methods begin_poly() end_poly() get_poly() clone() getturtle() | getpen() getscreen() setundobuffer() undobufferentries() 24.1.2.2. Methods of TurtleScreen/Screen Window control bgcolor() bgpic() clear() | clearscreen() reset() | resetscreen() screensize() setworldcoordinates() Animation control delay() tracer() update() Using screen events listen() onkey() | onkeyrelease() onkeypress() onclick() | onscreenclick() ontimer() mainloop() | done() Settings and special methods mode() colormode() getcanvas() getshapes() register_shape() | addshape() 54
  53. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 5/40 turtles() window_height() window_width() Input methods textinput() numinput() Methods specific to Screen bye() exitonclick() setup() title() 24.1.3. Methods of RawTurtle/Turtle and corresponding functions Most of the examples in this section refer to a Turtle instance called turtle. 24.1.3.1. Turtle motion turtle.forward(distance) turtle.fd(distance) Parameters: distance – a number (integer or float) Move the turtle forward by the specified distance, in the direction the turtle is headed. turtle.back(distance) turtle.bk(distance) turtle.backward(distance) Parameters: 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.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00) >>> 55
  54. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 6/40 turtle.right(angle) turtle.rt(angle) Parameters: angle – a number (integer or float) Turn turtle right by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on the turtle mode, see mode(). turtle.left(angle) turtle.lt(angle) Parameters: angle – a number (integer or float) Turn turtle left by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on the turtle mode, see mode(). turtle.goto(x, y=None) turtle.setpos(x, y=None) turtle.setposition(x, y=None) Parameters: x – a number or a pair/vector of numbers y – a number or None If y is None, x must be a pair of coordinates or a Vec2D (e.g. as returned by pos()). Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation. >>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00) >>> >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.0 >>> >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.0 >>> >>> tp = turtle.pos() >>> 56
  55. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 7/40 turtle.setx(x) Parameters: x – a number (integer or float) Set the turtle’s first coordinate to x, leave second coordinate unchanged. turtle.sety(y) Parameters: y – a number (integer or float) Set the turtle’s second coordinate to y, leave first coordinate unchanged. turtle.setheading(to_angle) turtle.seth(to_angle) Parameters: to_angle – a number (integer or float) Set the orientation of the turtle to to_angle. Here are some common directions in degrees: standard mode logo mode 0 - east 0 - north 90 - north 90 - east 180 - west 180 - south 270 - south 270 - west >>> 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) >>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00) >>> >>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00) >>> 57
  56. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 8/40 turtle.home() Move turtle to the origin – coordinates (0,0) – and set its heading to its start- orientation (which depends on the mode, see mode()). turtle.circle(radius, extent=None, steps=None) Parameters: radius – a number extent – a number (or None) 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.setheading(90) >>> turtle.heading() 90.0 >>> >>> turtle.heading() 90.0 >>> turtle.position() (0.00,-10.00) >>> turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.0 >>> >>> turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.0 >>> turtle.circle(50) >>> turtle.position() (-0.00,0.00) >>> turtle.heading() 0.0 >>> turtle.circle(120, 180) # draw a semicircle >>> turtle.position() (0.00,240.00) >>> turtle.heading() >>> 58
  57. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 9/40 turtle.dot(size=None, *color) Parameters: size – an integer >= 1 (if given) color – a colorstring or a numeric color tuple Draw a circular dot with diameter size, using color. If size is not given, the maximum of pensize+4 and 2*pensize is used. turtle.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.clearstamp(stampid) Parameters: stampid – an integer, must be return value of previous stamp() call Delete stamp with given stampid. turtle.clearstamps(n=None) Parameters: n – an integer (or None) 180.0 >>> turtle.home() >>> turtle.dot() >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50) >>> turtle.position() (100.00,-0.00) >>> turtle.heading() 0.0 >>> >>> turtle.color("blue") >>> turtle.stamp() 11 >>> turtle.fd(50) >>> >>> turtle.position() (150.00,-0.00) >>> turtle.color("blue") >>> astamp = turtle.stamp() >>> turtle.fd(50) >>> turtle.position() (200.00,-0.00) >>> turtle.clearstamp(astamp) >>> turtle.position() (200.00,-0.00) >>> 59
  58. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 10/40 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. turtle.undo() Undo (repeatedly) the last turtle action(s). Number of available undo actions is determined by the size of the undobuffer. turtle.speed(speed=None) Parameters: 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. >>> for i in range(8): ... turtle.stamp(); turtle.fd(30) 13 14 15 16 17 18 19 20 >>> turtle.clearstamps(2) >>> turtle.clearstamps(-2) >>> turtle.clearstamps() >>> >>> for i in range(4): ... turtle.fd(50); turtle.lt(80) ... >>> for i in range(8): ... turtle.undo() >>> 60
  59. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 11/40 24.1.3.2. Tell Turtle’s state turtle.position() turtle.pos() Return the turtle’s current location (x,y) (as a Vec2D vector). turtle.towards(x, y=None) Parameters: x – a number or a pair/vector of numbers or a turtle instance 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.xcor() Return the turtle’s x coordinate. turtle.ycor() Return the turtle’s y coordinate. >>> turtle.speed() 3 >>> turtle.speed('normal') >>> turtle.speed() 6 >>> turtle.speed(9) >>> turtle.speed() 9 >>> >>> turtle.pos() (440.00,-0.00) >>> >>> turtle.goto(10, 10) >>> turtle.towards(0,0) 225.0 >>> >>> turtle.home() >>> turtle.left(50) >>> turtle.forward(100) >>> turtle.pos() (64.28,76.60) >>> print(round(turtle.xcor(), 5)) 64.27876 >>> >>> turtle.home() >>> turtle.left(60) >>> turtle.forward(100) >>> 61
  60. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 12/40 turtle.heading() Return the turtle’s current heading (value depends on the turtle mode, see mode()). turtle.distance(x, y=None) Parameters: x – a number or a pair/vector of numbers or a turtle instance 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. 24.1.3.3. Settings for measurement turtle.degrees(fullcircle=360.0) Parameters: fullcircle – a number Set angle measurement units, i.e. set number of “degrees” for a full circle. Default value is 360 degrees. >>> print(turtle.pos()) (50.00,86.60) >>> print(round(turtle.ycor(), 5)) 86.60254 >>> turtle.home() >>> turtle.left(67) >>> turtle.heading() 67.0 >>> >>> turtle.home() >>> turtle.distance(30,40) 50.0 >>> turtle.distance((30,40)) 50.0 >>> joe = Turtle() >>> joe.forward(77) >>> turtle.distance(joe) 77.0 >>> >>> turtle.home() >>> turtle.left(90) >>> turtle.heading() 90.0 Change angle measurement unit to grad (also known as gon, grade, or gradian and equals 1/100-th of the right angle.) >>> turtle.degrees(400.0) >>> turtle.heading() 100.0 >>> 62
  61. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 13/40 turtle.radians() Set the angle measurement units to radians. Equivalent to degrees(2*math.pi). 24.1.3.4. Pen control 24.1.3.4.1. Drawing state turtle.pendown() turtle.pd() turtle.down() Pull the pen down – drawing when moving. turtle.penup() turtle.pu() turtle.up() Pull the pen up – no drawing when moving. turtle.pensize(width=None) turtle.width(width=None) Parameters: width – a positive number Set the line thickness to width or return it. If resizemode is set to “auto” and turtleshape is a polygon, that polygon is drawn with the same line thickness. If no argument is given, the current pensize is returned. turtle.pen(pen=None, **pendict) Parameters: pen – a dictionary with some or all of the below listed keys pendict – one or more keyword-arguments with the below listed keys as keywords >>> turtle.degrees(360) >>> turtle.heading() 90.0 >>> turtle.home() >>> turtle.left(90) >>> turtle.heading() 90.0 >>> turtle.radians() >>> turtle.heading() 1.5707963267948966 >>> >>> turtle.pensize() 1 >>> turtle.pensize(10) # from here on lines of width 10 are drawn >>> 63
  62. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 14/40 Return or set the pen’s attributes in a “pen-dictionary” with the following key/value pairs: “shown”: True/False “pendown”: True/False “pencolor”: color-string or color-tuple “fillcolor”: color-string or color-tuple “pensize”: positive number “speed”: number in range 0..10 “resizemode”: “auto” or “user” or “noresize” “stretchfactor”: (positive number, positive number) “outline”: positive number “tilt”: number This dictionary can be used as argument for a subsequent call to 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.isdown() Return True if pen is down, False if it’s up. 24.1.3.4.2. Color control turtle.pencolor(*args) Return or set the pencolor. >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10) >>> sorted(turtle.pen().items()) [('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'), ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'), ('shearfactor', 0.0), ('shown', True), ('speed', 9), ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)] >>> penstate=turtle.pen() >>> turtle.color("yellow", "") >>> turtle.penup() >>> sorted(turtle.pen().items())[:3] [('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow')] >>> turtle.pen(penstate, fillcolor="green") >>> sorted(turtle.pen().items())[:3] [('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')] >>> >>> turtle.penup() >>> turtle.isdown() False >>> turtle.pendown() >>> turtle.isdown() True >>> 64
  63. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 15/40 Four input formats are allowed: pencolor() Return the current pencolor as color specification string or as a tuple (see example). May be used as input to another color/pencolor/fillcolor call. 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 colormode()). 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. If turtleshape is a polygon, the outline of that polygon is drawn with the newly set pencolor. turtle.fillcolor(*args) Return or set the fillcolor. Four input formats are allowed: fillcolor() Return the current fillcolor as color specification string, possibly in tuple 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 >>> colormode() 1.0 >>> turtle.pencolor() 'red' >>> turtle.pencolor("brown") >>> turtle.pencolor() 'brown' >>> tup = (0.2, 0.8, 0.55) >>> turtle.pencolor(tup) >>> turtle.pencolor() (0.2, 0.8, 0.5490196078431373) >>> colormode(255) >>> turtle.pencolor() (51.0, 204.0, 140.0) >>> turtle.pencolor('#32c18f') >>> turtle.pencolor() (50.0, 193.0, 143.0) >>> 65
  64. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 16/40 "red", "yellow", or "#33cc8c". 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 colormode()). 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. turtle.color(*args) Return or set pencolor and fillcolor. 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 or tuples as returned by pencolor() and fillcolor(). color(colorstring), color((r,g,b)), color(r,g,b) Inputs as in pencolor(), set both, fillcolor and pencolor, to the given value. color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2)) Equivalent to pencolor(colorstring1) and fillcolor(colorstring2) and analogously if the other input format is used. If turtleshape is a polygon, outline and interior of that polygon is drawn with the newly set colors. >>> turtle.fillcolor("violet") >>> turtle.fillcolor() 'violet' >>> col = turtle.pencolor() >>> col (50.0, 193.0, 143.0) >>> turtle.fillcolor(col) >>> turtle.fillcolor() (50.0, 193.0, 143.0) >>> turtle.fillcolor('#ffffff') >>> turtle.fillcolor() (255.0, 255.0, 255.0) >>> >>> turtle.color("red", "green") >>> turtle.color() ('red', 'green') >>> color("#285078", "#a0c8f0") >>> 66
  65. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 17/40 See also: Screen method colormode(). 24.1.3.4.3. Filling turtle.filling() Return fillstate (True if filling, False else). turtle.begin_fill() To be called just before drawing a shape to be filled. turtle.end_fill() Fill the shape drawn after the last call to begin_fill(). 24.1.3.4.4. More drawing control turtle.reset() Delete the turtle’s drawings from the screen, re-center the turtle and set variables to the default values. turtle.clear() Delete the turtle’s drawings from the screen. Do not move turtle. State and position >>> color() ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0)) >>> turtle.begin_fill() >>> if turtle.filling(): ... turtle.pensize(5) ... else: ... turtle.pensize(3) >>> >>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(80) >>> turtle.end_fill() >>> >>> turtle.goto(0,-22) >>> turtle.left(100) >>> turtle.position() (0.00,-22.00) >>> turtle.heading() 100.0 >>> turtle.reset() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.0 >>> 67
  66. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 18/40 of the turtle as well as drawings of other turtles are not affected. turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal")) Parameters: arg – object to be written to the TurtleScreen move – True/False align – one of the strings “left”, “center” or right” font – a triple (fontname, fontsize, fonttype) Write text - the string representation of arg - at the current turtle position according to align (“left”, “center” or right”) and with the given font. If move is true, the pen is moved to the bottom-right corner of the text. By default, move is False. 24.1.3.5. Turtle state 24.1.3.5.1. Visibility turtle.hideturtle() turtle.ht() 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.showturtle() turtle.st() Make the turtle visible. turtle.isvisible() Return True if the Turtle is shown, False if it’s hidden. 24.1.3.5.2. Appearance >>> turtle.write("Home = ", True, align="center") >>> turtle.write((0,0), True) >>> >>> turtle.hideturtle() >>> >>> turtle.showturtle() >>> >>> turtle.hideturtle() >>> turtle.isvisible() False >>> turtle.showturtle() >>> turtle.isvisible() True >>> 68
  67. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 19/40 turtle.shape(name=None) Parameters: 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 register_shape(). turtle.resizemode(rmode=None) Parameters: 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 shapesize(). “noresize”: no adaption of the turtle’s appearance takes place. resizemode(“user”) is called by shapesize() when used with arguments. turtle.shapesize(stretch_wid=None, stretch_len=None, outline=None) turtle.turtlesize(stretch_wid=None, stretch_len=None, outline=None) Parameters: stretch_wid – positive number stretch_len – positive number outline – positive number Return or set the pen’s attributes x/y-stretchfactors and/or outline. Set resizemode to “user”. If and only if resizemode is set to “user”, the turtle will be displayed stretched according to its stretchfactors: stretch_wid is stretchfactor perpendicular to its orientation, stretch_len is stretchfactor in direction of its orientation, outline determines the width of the shapes’s outline. >>> turtle.shape() 'classic' >>> turtle.shape("turtle") >>> turtle.shape() 'turtle' >>> >>> turtle.resizemode() 'noresize' >>> turtle.resizemode("auto") >>> turtle.resizemode() 'auto' >>> 69
  68. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 20/40 turtle.shearfactor(shear=None) Parameters: shear – number (optional) Set or return the current shearfactor. Shear the turtleshape according to the given shearfactor shear, which is the tangent of the shear angle. Do not change the turtle’s heading (direction of movement). If shear is not given: return the current shearfactor, i. e. the tangent of the shear angle, by which lines parallel to the heading of the turtle are sheared. turtle.tilt(angle) Parameters: 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.settiltangle(angle) Parameters: 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.shapesize() (1.0, 1.0, 1) >>> turtle.resizemode("user") >>> turtle.shapesize(5, 5, 12) >>> turtle.shapesize() (5, 5, 12) >>> turtle.shapesize(outline=8) >>> turtle.shapesize() (5, 5, 8) >>> >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.shearfactor(0.5) >>> turtle.shearfactor() 0.5 >>> >>> turtle.reset() >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.tilt(30) >>> turtle.fd(50) >>> turtle.tilt(30) >>> turtle.fd(50) >>> >>> turtle.reset() >>> turtle.shape("circle") >>> 70
  69. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 21/40 Deprecated since version 3.1. turtle.tiltangle(angle=None) Parameters: angle – a number (optional) Set or return the current tilt-angle. If angle is given, 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). If angle is not given: 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.shapetransform(t11=None, t12=None, t21=None, t22=None) Parameters: t11 – a number (optional) t12 – a number (optional) t21 – a number (optional) t12 – a number (optional) Set or return the current transformation matrix of the turtle shape. If none of the matrix elements are given, return the transformation matrix as a tuple of 4 elements. Otherwise set the given elements and transform the turtleshape according to the matrix consisting of first row t11, t12 and second row t21, 22. The determinant t11 * t22 - t12 * t21 must not be zero, otherwise an error is raised. Modify stretchfactor, shearfactor and tiltangle according to the given matrix. turtle.get_shapepoly() Return the current shape polygon as tuple of coordinate pairs. This can be used to >>> turtle.shapesize(5,2) >>> turtle.settiltangle(45) >>> turtle.fd(50) >>> turtle.settiltangle(-45) >>> turtle.fd(50) >>> turtle.reset() >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.tilt(45) >>> turtle.tiltangle() 45.0 >>> >>> turtle = Turtle() >>> turtle.shape("square") >>> turtle.shapesize(4,2) >>> turtle.shearfactor(-0.5) >>> turtle.shapetransform() (4.0, -1.0, -0.0, 2.0) >>> 71
  70. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 22/40 define a new shape or components of a compound shape. 24.1.3.6. Using events turtle.onclick(fun, btn=1, add=None) Parameters: fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas num – number of the mouse-button, defaults to 1 (left mouse button) add – True or False – if True, 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: turtle.onrelease(fun, btn=1, add=None) Parameters: fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas num – number of the mouse-button, defaults to 1 (left mouse button) add – True or False – if True, 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. >>> turtle.shape("square") >>> turtle.shapetransform(4, -1, 0, 2) >>> turtle.get_shapepoly() ((50, -20), (30, 20), (-50, 20), (-30, -20)) >>> >>> def turn(x, y): ... left(180) ... >>> onclick(turn) # Now clicking into the turtle will turn it. >>> onclick(None) # event-binding will be 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. >>> 72
  71. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 23/40 turtle.ondrag(fun, btn=1, add=None) Parameters: fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas num – number of the mouse-button, defaults to 1 (left mouse button) add – True or False – if True, 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. Remark: Every sequence of mouse-move-events on a turtle is preceded by a mouse-click event on that turtle. Subsequently, clicking and dragging the Turtle will move it across the screen thereby producing handdrawings (if pen is down). 24.1.3.7. Special Turtle methods turtle.begin_poly() Start recording the vertices of a polygon. Current turtle position is first vertex of polygon. turtle.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. turtle.get_poly() Return the last recorded polygon. turtle.clone() Create and return a clone of the turtle with same position, heading and turtle properties. >>> turtle.ondrag(turtle.goto) >>> >>> turtle.home() >>> turtle.begin_poly() >>> turtle.fd(100) >>> turtle.left(20) >>> turtle.fd(30) >>> turtle.left(60) >>> turtle.fd(50) >>> turtle.end_poly() >>> p = turtle.get_poly() >>> register_shape("myFavouriteShape", p) >>> 73
  72. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 24/40 turtle.getturtle() turtle.getpen() Return the Turtle object itself. Only reasonable use: as a function to return the “anonymous turtle”: turtle.getscreen() Return the TurtleScreen object the turtle is drawing on. TurtleScreen methods can then be called for that object. turtle.setundobuffer(size) Parameters: 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 undo() method/function. If size is None, the undobuffer is disabled. turtle.undobufferentries() Return number of entries in the undobuffer. 24.1.3.8. Compound shapes To use compound turtle shapes, which consist of several polygons of different color, you must use the helper 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 addcomponent() >>> mick = Turtle() >>> joe = mick.clone() >>> >>> pet = getturtle() >>> pet.fd(50) >>> pet <turtle.Turtle object at 0x...> >>> >>> ts = turtle.getscreen() >>> ts <turtle._Screen object at 0x...> >>> ts.bgcolor("pink") >>> >>> turtle.setundobuffer(42) >>> >>> while undobufferentries(): ... undo() >>> 74
  73. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 25/40 method. For example: 3. Now add the Shape to the Screen’s shapelist and use it: Note: The Shape class is used internally by the register_shape() method in different ways. The application programmer has to deal with the Shape class only when using compound shapes like shown above! 24.1.4. Methods of TurtleScreen/Screen and corresponding functions Most of the examples in this section refer to a TurtleScreen instance called screen. 24.1.4.1. Window control turtle.bgcolor(*args) Parameters: 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. turtle.bgpic(picname=None) Parameters: 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 >>> 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") >>> >>> register_shape("myshape", s) >>> shape("myshape") >>> >>> screen.bgcolor("orange") >>> screen.bgcolor() 'orange' >>> screen.bgcolor("#800080") >>> screen.bgcolor() (128.0, 0.0, 128.0) >>> 75
  74. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 26/40 current backgroundimage. turtle.clear() turtle.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 a different one derived from the Turtle method clear. turtle.reset() turtle.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. turtle.screensize(canvwidth=None, canvheight=None, bg=None) Parameters: canvwidth – positive integer, new width of canvas in pixels canvheight – positive integer, new height of canvas in pixels bg – colorstring or color-tuple, 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. e.g. to search for an erroneously escaped turtle ;-) turtle.setworldcoordinates(llx, lly, urx, ury) >>> screen.bgpic() 'nopic' >>> screen.bgpic("landscape.gif") >>> screen.bgpic() "landscape.gif" >>> >>> screen.screensize() (400, 300) >>> screen.screensize(2000,1500) >>> screen.screensize() (2000, 1500) >>> 76
  75. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 27/40 Parameters: llx – a number, x-coordinate of lower left corner of canvas lly – a number, y-coordinate of lower left corner of canvas urx – a number, x-coordinate of upper right corner of canvas ury – a number, y-coordinate of upper right corner of canvas Set up user-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. 24.1.4.2. Animation control turtle.delay(delay=None) Parameters: delay – positive integer Set or return the drawing delay in milliseconds. (This is approximately the time interval between two consecutive canvas updates.) The longer the drawing delay, the slower the animation. Optional argument: turtle.tracer(n=None, delay=None) Parameters: n – nonnegative integer delay – nonnegative integer Turn turtle animation on/off and set delay for update drawings. If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) When called without arguments, returns the currently stored value of n. Second argument sets delay value (see delay()). >>> 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 octagon >>> >>> screen.delay() 10 >>> screen.delay(5) >>> screen.delay() 5 >>> >>> screen.tracer(8, 25) >>> dist = 2 >>> 77
  76. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 28/40 turtle.update() Perform a TurtleScreen update. To be used when tracer is turned off. See also the RawTurtle/Turtle method speed(). 24.1.4.3. Using screen events turtle.listen(xdummy=None, ydummy=None) Set focus on TurtleScreen (in order to collect key-events). Dummy arguments are provided in order to be able to pass listen() to the onclick method. turtle.onkey(fun, key) turtle.onkeyrelease(fun, key) Parameters: fun – a function with no arguments or None key – a string: key (e.g. “a”) or key-symbol (e.g. “space”) Bind fun to key-release event of key. If fun is None, event bindings are removed. Remark: in order to be able to register key-events, TurtleScreen must have the focus. (See method listen().) turtle.onkeypress(fun, key=None) Parameters: fun – a function with no arguments or None key – a string: key (e.g. “a”) or key-symbol (e.g. “space”) Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given. Remark: in order to be able to register key-events, TurtleScreen must have focus. (See method listen().) >>> for i in range(200): ... fd(dist) ... rt(90) ... dist += 2 >>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkey(f, "Up") >>> screen.listen() >>> >>> def f(): ... fd(50) ... >>> screen.onkey(f, "Up") >>> screen.listen() >>> 78
  77. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 29/40 turtle.onclick(fun, btn=1, add=None) turtle.onscreenclick(fun, btn=1, add=None) Parameters: fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas num – number of the mouse-button, defaults to 1 (left mouse button) add – True or False – if True, 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: 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. turtle.ontimer(fun, t=0) Parameters: fun – a function with no arguments t – a number >= 0 Install a timer that calls fun after t milliseconds. turtle.mainloop() turtle.done() Starts event loop - calling Tkinter’s mainloop function. Must be the last statement in a turtle graphics program. Must not be used if a script is run from within IDLE in -n mode (No subprocess) - for interactive use of turtle graphics. >>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScree >>> # make the turtle move to the clicked point. >>> screen.onclick(None) # remove event binding again >>> >>> running = True >>> def f(): ... if running: ... fd(50) ... lt(60) ... screen.ontimer(f, 250) >>> f() ### makes the turtle march around >>> running = False >>> >>> screen.mainloop() >>> 79
  78. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 30/40 24.1.4.4. Input methods turtle.textinput(title, prompt) Parameters: title – string prompt – string Pop up a dialog window for input of a string. Parameter title is the title of the dialog window, propmt is a text mostly describing what information to input. Return the string input. If the dialog is canceled, return None. turtle.numinput(title, prompt, default=None, minval=None, maxval=None) Parameters: title – string prompt – string default – number (optional) minval – number (optional) maxval – number (optional) Pop up a dialog window for input of a number. title is the title of the dialog window, prompt is a text mostly describing what numerical information to input. default: default value, minval: minimum value for imput, maxval: maximum value for input The number input must be in the range minval .. maxval if these are given. If not, a hint is issued and the dialog remains open for correction. Return the number input. If the dialog is canceled, return None. 24.1.4.5. Settings and special methods turtle.mode(mode=None) Parameters: 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 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 >>> screen.textinput("NIM", "Name of first player:") >>> >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000 >>> 80
  79. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 31/40 “logo” upward (north) clockwise turtle.colormode(cmode=None) Parameters: 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. turtle.getcanvas() Return the Canvas of this TurtleScreen. Useful for insiders who know what to do with a Tkinter Canvas. turtle.getshapes() Return a list of names of all currently available turtle shapes. turtle.register_shape(name, shape=None) turtle.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. >>> mode("logo") # resets turtle heading to north >>> mode() 'logo' >>> >>> screen.colormode(1) >>> turtle.pencolor(240, 160, 80) Traceback (most recent call last): ... TurtleGraphicsError: bad color sequence: (240, 160, 80) >>> screen.colormode() 1.0 >>> screen.colormode(255) >>> screen.colormode() 255 >>> turtle.pencolor(240,160,80) >>> >>> cv = screen.getcanvas() >>> cv <turtle.ScrolledCanvas object at ...> >>> >>> screen.getshapes() ['arrow', 'blank', 'circle', ..., 'turtle'] >>> >>> screen.register_shape("turtle.gif") >>> 81
  80. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 32/40 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) 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). turtle.turtles() Return the list of turtles on the screen. turtle.window_height() Return the height of the turtle window. turtle.window_width() Return the width of the turtle window. 24.1.4.6. Methods specific to Screen, not inherited from TurtleScreen turtle.bye() Shut the turtlegraphics window. turtle.exitonclick() Bind bye() method to mouse clicks on the Screen. 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 turtle.cfg. In this case IDLE’s own mainloop is active also for the client script. >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3))) >>> >>> for turtle in screen.turtles(): ... turtle.color("red") >>> >>> screen.window_height() 480 >>> >>> screen.window_width() 640 >>> 82
  81. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 33/40 turtle.setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"]) Set the size and position of the main window. Default values of arguments are stored in the configuration dictionary and can be changed via a turtle.cfg file. Parameters: width – if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen height – if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen startx – if positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if None, center window horizontally starty – if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if None, center window vertically turtle.title(titlestring) Parameters: titlestring – a string that is shown in the titlebar of the turtle graphics window Set title of turtle window to titlestring. 24.1.5. Public classes class turtle.RawTurtle(canvas) class turtle.RawPen(canvas) Parameters: canvas – a tkinter.Canvas, a ScrolledCanvas or a TurtleScreen Create a turtle. The turtle has all methods described above as “methods of Turtle/RawTurtle”. class turtle.Turtle Subclass of RawTurtle, has the same interface but draws on a default Screen object created automatically when needed for the first time. class turtle.TurtleScreen(cv) >>> 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 >>> >>> screen.title("Welcome to the turtle zoo!") >>> 83
  82. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 34/40 Parameters: cv – a tkinter.Canvas Provides screen oriented methods like setbg() etc. that are described above. class turtle.Screen Subclass of TurtleScreen, with four methods added. class turtle.ScrolledCanvas(master) Parameters: master – some Tkinter widget to contain the ScrolledCanvas, i.e. a Tkinter-canvas with scrollbars added Used by class Screen, which thus automatically provides a ScrolledCanvas as playground for the turtles. class turtle.Shape(type_, data) Parameters: type_ – one of the strings “polygon”, “image”, “compound” 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 compound shape has to be constructed using the addcomponent() method) addcomponent(poly, fill, outline=None) Parameters: poly – a polygon, i.e. a tuple of pairs of numbers fill – a color the poly will be filled with outline – a color for the poly’s outline (if given) Example: See Compound shapes. class turtle.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! >>> 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() >>> 84
  83. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 35/40 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 24.1.6. Help and configuration 24.1.6.1. How to use help The public methods of the Screen and Turtle classes are documented extensively via docstrings. So these can be used as online-help via the Python help facilities: When using IDLE, tooltips show the signatures and first lines of the docstrings of typed in function-/method calls. Calling help() on methods or functions 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() >>> 85
  84. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 36/40 The docstrings of the functions which are derived from methods have a modified form: These modified docstrings are created automatically together with the function definitions that are derived from the methods at import time. 24.1.6.2. 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. turtle.write_docstringdict(filename="turtle_docstringdict") Parameters: 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 filename.py. >>> 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() >>> 86
  85. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 37/40 It is intended to serve as a template for translation of the docstrings into different languages. If you (or your students) want to use turtle with online help in your native language, you have to translate the docstrings and save the resulting file as e.g. turtle_docstringdict_german.py. If you have an appropriate entry in your turtle.cfg file this dictionary will be read in at import time and will replace the original English docstrings. At the time of this writing there are docstring dictionaries in German and in Italian. (Requests please to [email protected].) 24.1.6.3. 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: Short explanation of selected entries: The first four lines correspond to the arguments of the Screen.setup() method. 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 87
  86. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 38/40 Line 5 and 6 correspond to the arguments of the method Screen.screensize(). shape can be any of the built-in shapes, e.g: arrow, turtle, etc. For more info try help(shape). If you want to use no fillcolor (i.e. 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 turtle_docstringdict_italian.py will be loaded at import time (if present on the import path, e.g. in the same directory as 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 exitonclick() to enter the mainloop. There can be a turtle.cfg file in the directory where turtle is stored and an additional one in the current working directory. The latter will override the settings of the first one. The Lib/turtledemo directory contains a 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). 24.1.7. turtledemo — Demo scripts The turtledemo package includes a set of demo scripts. These scripts can be run and viewed using the supplied demo viewer as follows: Alternatively, you can run the demo scripts individually. For example, The turtledemo package directory contains: A demo viewer __main__.py which can be used to view the sourcecode of the scripts and run them at the same time. Multiple scripts demonstrating different features of the turtle module. Examples can be accessed via the Examples menu. They can also be run standalone. A turtle.cfg file which serves as an example of how to write and use such files. The demo scripts are: Name Description Features bytedesign complex classical turtle graphics pattern tracer(), delay, update() python -m turtledemo python -m turtledemo.bytedesign 88
  87. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 39/40 chaos graphs Verhulst dynamics, shows that computer’s computations can generate results sometimes against the common sense expectations world coordinates clock analog clock showing time of your computer turtles as clock’s hands, ontimer colormixer experiment with r, g, b ondrag() forest 3 breadth-first trees randomization fractalcurves Hilbert & Koch curves recursion lindenmayer ethnomathematics (indian kolams) L-System minimal_hanoi Towers of Hanoi Rectangular Turtles as Hanoi discs (shape, shapesize) nim play the classical nim game with three heaps of sticks against the computer. turtles as nimsticks, event driven (mouse, keyboard) paint super minimalistic drawing program onclick() peace elementary turtle: appearance and animation penrose aperiodic tiling with kites and darts stamp() planet_and_moon simulation of gravitational system compound shapes, Vec2D round_dance dancing turtles rotating pairwise in opposite direction compound shapes, clone shapesize, tilt, get_shapepoly, update tree a (graphical) breadth first tree (using generators) clone() two_canvases simple design turtles on two canvases wikipedia a pattern from the wikipedia article on turtle graphics clone(), undo() yingyang another elementary example circle() Have fun! 24.1.8. Changes since Python 2.6 The methods Turtle.tracer(), Turtle.window_width() and Turtle.window_height() have been eliminated. Methods with these names and functionality are now available only as methods of Screen. The functions derived from these remain available. (In fact already in Python 2.6 these methods were merely duplications of the corresponding TurtleScreen/Screen-methods.) The method Turtle.fill() has been eliminated. The behaviour of 89
  88. 2014/11/3 24.1. turtle — Turtle graphics — Python 3.4.2 documentation

    https://docs.python.org/3.4/library/turtle.html 40/40 begin_fill() and end_fill() have changed slightly: now every filling-process must be completed with an end_fill() call. A method 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. 24.1.9. Changes since Python 3.0 The methods Turtle.shearfactor(), Turtle.shapetransform() and Turtle.get_shapepoly() have been added. Thus the full range of regular linear transforms is now available for transforming turtle shapes. Turtle.tiltangle() has been enhanced in functionality: it now can be used to get or set the tiltangle. Turtle.settiltangle() has been deprecated. The method Screen.onkeypress() has been added as a complement to Screen.onkey() which in fact binds actions to the keyrelease event. Accordingly the latter has got an alias: Screen.onkeyrelease(). The method Screen.mainloop() has been added. So when working only with Screen and Turtle objects one must not additonally import mainloop() anymore. Two input methods has been added Screen.textinput() and Screen.numinput(). These popup input dialogs and return strings and numbers respectively. Two example scripts tdemo_nim.py and tdemo_round_dance.py have been added to the Lib/turtledemo directory. 90