PageRenderTime 60ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/library/turtle.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 2226 lines | 1547 code | 679 blank | 0 comment | 0 complexity | b15a8100e0c3f8effa31d3387efffa71 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. ========================================
  2. :mod:`turtle` --- Turtle graphics for Tk
  3. ========================================
  4. .. module:: turtle
  5. :synopsis: Turtle graphics for Tk
  6. .. sectionauthor:: Gregor Lingl <gregor.lingl@aon.at>
  7. .. testsetup:: default
  8. from turtle import *
  9. turtle = Turtle()
  10. Introduction
  11. ============
  12. Turtle graphics is a popular way for introducing programming to kids. It was
  13. part of the original Logo programming language developed by Wally Feurzig and
  14. Seymour Papert in 1966.
  15. Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it the
  16. command ``turtle.forward(15)``, and it moves (on-screen!) 15 pixels in the
  17. direction it is facing, drawing a line as it moves. Give it the command
  18. ``turtle.left(25)``, and it rotates in-place 25 degrees clockwise.
  19. By combining together these and similar commands, intricate shapes and pictures
  20. can easily be drawn.
  21. The :mod:`turtle` module is an extended reimplementation of the same-named
  22. module from the Python standard distribution up to version Python 2.5.
  23. It tries to keep the merits of the old turtle module and to be (nearly) 100%
  24. compatible with it. This means in the first place to enable the learning
  25. programmer to use all the commands, classes and methods interactively when using
  26. the module from within IDLE run with the ``-n`` switch.
  27. The turtle module provides turtle graphics primitives, in both object-oriented
  28. and procedure-oriented ways. Because it uses :mod:`Tkinter` for the underlying
  29. graphics, it needs a version of python installed with Tk support.
  30. The object-oriented interface uses essentially two+two classes:
  31. 1. The :class:`TurtleScreen` class defines graphics windows as a playground for
  32. the drawing turtles. Its constructor needs a :class:`Tkinter.Canvas` or a
  33. :class:`ScrolledCanvas` as argument. It should be used when :mod:`turtle` is
  34. used as part of some application.
  35. The function :func:`Screen` returns a singleton object of a
  36. :class:`TurtleScreen` subclass. This function should be used when
  37. :mod:`turtle` is used as a standalone tool for doing graphics.
  38. As a singleton object, inheriting from its class is not possible.
  39. All methods of TurtleScreen/Screen also exist as functions, i.e. as part of
  40. the procedure-oriented interface.
  41. 2. :class:`RawTurtle` (alias: :class:`RawPen`) defines Turtle objects which draw
  42. on a :class:`TurtleScreen`. Its constructor needs a Canvas, ScrolledCanvas
  43. or TurtleScreen as argument, so the RawTurtle objects know where to draw.
  44. Derived from RawTurtle is the subclass :class:`Turtle` (alias: :class:`Pen`),
  45. which draws on "the" :class:`Screen` - instance which is automatically
  46. created, if not already present.
  47. All methods of RawTurtle/Turtle also exist as functions, i.e. part of the
  48. procedure-oriented interface.
  49. The procedural interface provides functions which are derived from the methods
  50. of the classes :class:`Screen` and :class:`Turtle`. They have the same names as
  51. the corresponding methods. A screen object is automatically created whenever a
  52. function derived from a Screen method is called. An (unnamed) turtle object is
  53. automatically created whenever any of the functions derived from a Turtle method
  54. is called.
  55. To use multiple turtles an a screen one has to use the object-oriented interface.
  56. .. note::
  57. In the following documentation the argument list for functions is given.
  58. Methods, of course, have the additional first argument *self* which is
  59. omitted here.
  60. Overview over available Turtle and Screen methods
  61. =================================================
  62. Turtle methods
  63. --------------
  64. Turtle motion
  65. Move and draw
  66. | :func:`forward` | :func:`fd`
  67. | :func:`backward` | :func:`bk` | :func:`back`
  68. | :func:`right` | :func:`rt`
  69. | :func:`left` | :func:`lt`
  70. | :func:`goto` | :func:`setpos` | :func:`setposition`
  71. | :func:`setx`
  72. | :func:`sety`
  73. | :func:`setheading` | :func:`seth`
  74. | :func:`home`
  75. | :func:`circle`
  76. | :func:`dot`
  77. | :func:`stamp`
  78. | :func:`clearstamp`
  79. | :func:`clearstamps`
  80. | :func:`undo`
  81. | :func:`speed`
  82. Tell Turtle's state
  83. | :func:`position` | :func:`pos`
  84. | :func:`towards`
  85. | :func:`xcor`
  86. | :func:`ycor`
  87. | :func:`heading`
  88. | :func:`distance`
  89. Setting and measurement
  90. | :func:`degrees`
  91. | :func:`radians`
  92. Pen control
  93. Drawing state
  94. | :func:`pendown` | :func:`pd` | :func:`down`
  95. | :func:`penup` | :func:`pu` | :func:`up`
  96. | :func:`pensize` | :func:`width`
  97. | :func:`pen`
  98. | :func:`isdown`
  99. Color control
  100. | :func:`color`
  101. | :func:`pencolor`
  102. | :func:`fillcolor`
  103. Filling
  104. | :func:`fill`
  105. | :func:`begin_fill`
  106. | :func:`end_fill`
  107. More drawing control
  108. | :func:`reset`
  109. | :func:`clear`
  110. | :func:`write`
  111. Turtle state
  112. Visibility
  113. | :func:`showturtle` | :func:`st`
  114. | :func:`hideturtle` | :func:`ht`
  115. | :func:`isvisible`
  116. Appearance
  117. | :func:`shape`
  118. | :func:`resizemode`
  119. | :func:`shapesize` | :func:`turtlesize`
  120. | :func:`settiltangle`
  121. | :func:`tiltangle`
  122. | :func:`tilt`
  123. Using events
  124. | :func:`onclick`
  125. | :func:`onrelease`
  126. | :func:`ondrag`
  127. Special Turtle methods
  128. | :func:`begin_poly`
  129. | :func:`end_poly`
  130. | :func:`get_poly`
  131. | :func:`clone`
  132. | :func:`getturtle` | :func:`getpen`
  133. | :func:`getscreen`
  134. | :func:`setundobuffer`
  135. | :func:`undobufferentries`
  136. | :func:`tracer`
  137. | :func:`window_width`
  138. | :func:`window_height`
  139. Methods of TurtleScreen/Screen
  140. ------------------------------
  141. Window control
  142. | :func:`bgcolor`
  143. | :func:`bgpic`
  144. | :func:`clear` | :func:`clearscreen`
  145. | :func:`reset` | :func:`resetscreen`
  146. | :func:`screensize`
  147. | :func:`setworldcoordinates`
  148. Animation control
  149. | :func:`delay`
  150. | :func:`tracer`
  151. | :func:`update`
  152. Using screen events
  153. | :func:`listen`
  154. | :func:`onkey`
  155. | :func:`onclick` | :func:`onscreenclick`
  156. | :func:`ontimer`
  157. Settings and special methods
  158. | :func:`mode`
  159. | :func:`colormode`
  160. | :func:`getcanvas`
  161. | :func:`getshapes`
  162. | :func:`register_shape` | :func:`addshape`
  163. | :func:`turtles`
  164. | :func:`window_height`
  165. | :func:`window_width`
  166. Methods specific to Screen
  167. | :func:`bye`
  168. | :func:`exitonclick`
  169. | :func:`setup`
  170. | :func:`title`
  171. Methods of RawTurtle/Turtle and corresponding functions
  172. =======================================================
  173. Most of the examples in this section refer to a Turtle instance called
  174. ``turtle``.
  175. Turtle motion
  176. -------------
  177. .. function:: forward(distance)
  178. fd(distance)
  179. :param distance: a number (integer or float)
  180. Move the turtle forward by the specified *distance*, in the direction the
  181. turtle is headed.
  182. .. doctest::
  183. >>> turtle.position()
  184. (0.00,0.00)
  185. >>> turtle.forward(25)
  186. >>> turtle.position()
  187. (25.00,0.00)
  188. >>> turtle.forward(-75)
  189. >>> turtle.position()
  190. (-50.00,0.00)
  191. .. function:: back(distance)
  192. bk(distance)
  193. backward(distance)
  194. :param distance: a number
  195. Move the turtle backward by *distance*, opposite to the direction the
  196. turtle is headed. Do not change the turtle's heading.
  197. .. doctest::
  198. :hide:
  199. >>> turtle.goto(0, 0)
  200. .. doctest::
  201. >>> turtle.position()
  202. (0.00,0.00)
  203. >>> turtle.backward(30)
  204. >>> turtle.position()
  205. (-30.00,0.00)
  206. .. function:: right(angle)
  207. rt(angle)
  208. :param angle: a number (integer or float)
  209. Turn turtle right by *angle* units. (Units are by default degrees, but
  210. can be set via the :func:`degrees` and :func:`radians` functions.) Angle
  211. orientation depends on the turtle mode, see :func:`mode`.
  212. .. doctest::
  213. :hide:
  214. >>> turtle.setheading(22)
  215. .. doctest::
  216. >>> turtle.heading()
  217. 22.0
  218. >>> turtle.right(45)
  219. >>> turtle.heading()
  220. 337.0
  221. .. function:: left(angle)
  222. lt(angle)
  223. :param angle: a number (integer or float)
  224. Turn turtle left by *angle* units. (Units are by default degrees, but
  225. can be set via the :func:`degrees` and :func:`radians` functions.) Angle
  226. orientation depends on the turtle mode, see :func:`mode`.
  227. .. doctest::
  228. :hide:
  229. >>> turtle.setheading(22)
  230. .. doctest::
  231. >>> turtle.heading()
  232. 22.0
  233. >>> turtle.left(45)
  234. >>> turtle.heading()
  235. 67.0
  236. .. function:: goto(x, y=None)
  237. setpos(x, y=None)
  238. setposition(x, y=None)
  239. :param x: a number or a pair/vector of numbers
  240. :param y: a number or ``None``
  241. If *y* is ``None``, *x* must be a pair of coordinates or a :class:`Vec2D`
  242. (e.g. as returned by :func:`pos`).
  243. Move turtle to an absolute position. If the pen is down, draw line. Do
  244. not change the turtle's orientation.
  245. .. doctest::
  246. :hide:
  247. >>> turtle.goto(0, 0)
  248. .. doctest::
  249. >>> tp = turtle.pos()
  250. >>> tp
  251. (0.00,0.00)
  252. >>> turtle.setpos(60,30)
  253. >>> turtle.pos()
  254. (60.00,30.00)
  255. >>> turtle.setpos((20,80))
  256. >>> turtle.pos()
  257. (20.00,80.00)
  258. >>> turtle.setpos(tp)
  259. >>> turtle.pos()
  260. (0.00,0.00)
  261. .. function:: setx(x)
  262. :param x: a number (integer or float)
  263. Set the turtle's first coordinate to *x*, leave second coordinate
  264. unchanged.
  265. .. doctest::
  266. :hide:
  267. >>> turtle.goto(0, 240)
  268. .. doctest::
  269. >>> turtle.position()
  270. (0.00,240.00)
  271. >>> turtle.setx(10)
  272. >>> turtle.position()
  273. (10.00,240.00)
  274. .. function:: sety(y)
  275. :param y: a number (integer or float)
  276. Set the turtle's second coordinate to *y*, leave first coordinate unchanged.
  277. .. doctest::
  278. :hide:
  279. >>> turtle.goto(0, 40)
  280. .. doctest::
  281. >>> turtle.position()
  282. (0.00,40.00)
  283. >>> turtle.sety(-10)
  284. >>> turtle.position()
  285. (0.00,-10.00)
  286. .. function:: setheading(to_angle)
  287. seth(to_angle)
  288. :param to_angle: a number (integer or float)
  289. Set the orientation of the turtle to *to_angle*. Here are some common
  290. directions in degrees:
  291. =================== ====================
  292. standard mode logo mode
  293. =================== ====================
  294. 0 - east 0 - north
  295. 90 - north 90 - east
  296. 180 - west 180 - south
  297. 270 - south 270 - west
  298. =================== ====================
  299. .. doctest::
  300. >>> turtle.setheading(90)
  301. >>> turtle.heading()
  302. 90.0
  303. .. function:: home()
  304. Move turtle to the origin -- coordinates (0,0) -- and set its heading to
  305. its start-orientation (which depends on the mode, see :func:`mode`).
  306. .. doctest::
  307. :hide:
  308. >>> turtle.setheading(90)
  309. >>> turtle.goto(0, -10)
  310. .. doctest::
  311. >>> turtle.heading()
  312. 90.0
  313. >>> turtle.position()
  314. (0.00,-10.00)
  315. >>> turtle.home()
  316. >>> turtle.position()
  317. (0.00,0.00)
  318. >>> turtle.heading()
  319. 0.0
  320. .. function:: circle(radius, extent=None, steps=None)
  321. :param radius: a number
  322. :param extent: a number (or ``None``)
  323. :param steps: an integer (or ``None``)
  324. Draw a circle with given *radius*. The center is *radius* units left of
  325. the turtle; *extent* -- an angle -- determines which part of the circle
  326. is drawn. If *extent* is not given, draw the entire circle. If *extent*
  327. is not a full circle, one endpoint of the arc is the current pen
  328. position. Draw the arc in counterclockwise direction if *radius* is
  329. positive, otherwise in clockwise direction. Finally the direction of the
  330. turtle is changed by the amount of *extent*.
  331. As the circle is approximated by an inscribed regular polygon, *steps*
  332. determines the number of steps to use. If not given, it will be
  333. calculated automatically. May be used to draw regular polygons.
  334. .. doctest::
  335. >>> turtle.home()
  336. >>> turtle.position()
  337. (0.00,0.00)
  338. >>> turtle.heading()
  339. 0.0
  340. >>> turtle.circle(50)
  341. >>> turtle.position()
  342. (-0.00,0.00)
  343. >>> turtle.heading()
  344. 0.0
  345. >>> turtle.circle(120, 180) # draw a semicircle
  346. >>> turtle.position()
  347. (0.00,240.00)
  348. >>> turtle.heading()
  349. 180.0
  350. .. function:: dot(size=None, *color)
  351. :param size: an integer >= 1 (if given)
  352. :param color: a colorstring or a numeric color tuple
  353. Draw a circular dot with diameter *size*, using *color*. If *size* is
  354. not given, the maximum of pensize+4 and 2*pensize is used.
  355. .. doctest::
  356. >>> turtle.home()
  357. >>> turtle.dot()
  358. >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
  359. >>> turtle.position()
  360. (100.00,-0.00)
  361. >>> turtle.heading()
  362. 0.0
  363. .. function:: stamp()
  364. Stamp a copy of the turtle shape onto the canvas at the current turtle
  365. position. Return a stamp_id for that stamp, which can be used to delete
  366. it by calling ``clearstamp(stamp_id)``.
  367. .. doctest::
  368. >>> turtle.color("blue")
  369. >>> turtle.stamp()
  370. 11
  371. >>> turtle.fd(50)
  372. .. function:: clearstamp(stampid)
  373. :param stampid: an integer, must be return value of previous
  374. :func:`stamp` call
  375. Delete stamp with given *stampid*.
  376. .. doctest::
  377. >>> turtle.position()
  378. (150.00,-0.00)
  379. >>> turtle.color("blue")
  380. >>> astamp = turtle.stamp()
  381. >>> turtle.fd(50)
  382. >>> turtle.position()
  383. (200.00,-0.00)
  384. >>> turtle.clearstamp(astamp)
  385. >>> turtle.position()
  386. (200.00,-0.00)
  387. .. function:: clearstamps(n=None)
  388. :param n: an integer (or ``None``)
  389. Delete all or first/last *n* of turtle's stamps. If *n* is None, delete
  390. all stamps, if *n* > 0 delete first *n* stamps, else if *n* < 0 delete
  391. last *n* stamps.
  392. .. doctest::
  393. >>> for i in range(8):
  394. ... turtle.stamp(); turtle.fd(30)
  395. 13
  396. 14
  397. 15
  398. 16
  399. 17
  400. 18
  401. 19
  402. 20
  403. >>> turtle.clearstamps(2)
  404. >>> turtle.clearstamps(-2)
  405. >>> turtle.clearstamps()
  406. .. function:: undo()
  407. Undo (repeatedly) the last turtle action(s). Number of available
  408. undo actions is determined by the size of the undobuffer.
  409. .. doctest::
  410. >>> for i in range(4):
  411. ... turtle.fd(50); turtle.lt(80)
  412. ...
  413. >>> for i in range(8):
  414. ... turtle.undo()
  415. .. function:: speed(speed=None)
  416. :param speed: an integer in the range 0..10 or a speedstring (see below)
  417. Set the turtle's speed to an integer value in the range 0..10. If no
  418. argument is given, return current speed.
  419. If input is a number greater than 10 or smaller than 0.5, speed is set
  420. to 0. Speedstrings are mapped to speedvalues as follows:
  421. * "fastest": 0
  422. * "fast": 10
  423. * "normal": 6
  424. * "slow": 3
  425. * "slowest": 1
  426. Speeds from 1 to 10 enforce increasingly faster animation of line drawing
  427. and turtle turning.
  428. Attention: *speed* = 0 means that *no* animation takes
  429. place. forward/back makes turtle jump and likewise left/right make the
  430. turtle turn instantly.
  431. .. doctest::
  432. >>> turtle.speed()
  433. 3
  434. >>> turtle.speed('normal')
  435. >>> turtle.speed()
  436. 6
  437. >>> turtle.speed(9)
  438. >>> turtle.speed()
  439. 9
  440. Tell Turtle's state
  441. -------------------
  442. .. function:: position()
  443. pos()
  444. Return the turtle's current location (x,y) (as a :class:`Vec2D` vector).
  445. .. doctest::
  446. >>> turtle.pos()
  447. (440.00,-0.00)
  448. .. function:: towards(x, y=None)
  449. :param x: a number or a pair/vector of numbers or a turtle instance
  450. :param y: a number if *x* is a number, else ``None``
  451. Return the angle between the line from turtle position to position specified
  452. by (x,y), the vector or the other turtle. This depends on the turtle's start
  453. orientation which depends on the mode - "standard"/"world" or "logo").
  454. .. doctest::
  455. >>> turtle.goto(10, 10)
  456. >>> turtle.towards(0,0)
  457. 225.0
  458. .. function:: xcor()
  459. Return the turtle's x coordinate.
  460. .. doctest::
  461. >>> turtle.home()
  462. >>> turtle.left(50)
  463. >>> turtle.forward(100)
  464. >>> turtle.pos()
  465. (64.28,76.60)
  466. >>> print turtle.xcor()
  467. 64.2787609687
  468. .. function:: ycor()
  469. Return the turtle's y coordinate.
  470. .. doctest::
  471. >>> turtle.home()
  472. >>> turtle.left(60)
  473. >>> turtle.forward(100)
  474. >>> print turtle.pos()
  475. (50.00,86.60)
  476. >>> print turtle.ycor()
  477. 86.6025403784
  478. .. function:: heading()
  479. Return the turtle's current heading (value depends on the turtle mode, see
  480. :func:`mode`).
  481. .. doctest::
  482. >>> turtle.home()
  483. >>> turtle.left(67)
  484. >>> turtle.heading()
  485. 67.0
  486. .. function:: distance(x, y=None)
  487. :param x: a number or a pair/vector of numbers or a turtle instance
  488. :param y: a number if *x* is a number, else ``None``
  489. Return the distance from the turtle to (x,y), the given vector, or the given
  490. other turtle, in turtle step units.
  491. .. doctest::
  492. >>> turtle.home()
  493. >>> turtle.distance(30,40)
  494. 50.0
  495. >>> turtle.distance((30,40))
  496. 50.0
  497. >>> joe = Turtle()
  498. >>> joe.forward(77)
  499. >>> turtle.distance(joe)
  500. 77.0
  501. Settings for measurement
  502. ------------------------
  503. .. function:: degrees(fullcircle=360.0)
  504. :param fullcircle: a number
  505. Set angle measurement units, i.e. set number of "degrees" for a full circle.
  506. Default value is 360 degrees.
  507. .. doctest::
  508. >>> turtle.home()
  509. >>> turtle.left(90)
  510. >>> turtle.heading()
  511. 90.0
  512. >>> turtle.degrees(400.0) # angle measurement in gon
  513. >>> turtle.heading()
  514. 100.0
  515. >>> turtle.degrees(360)
  516. >>> turtle.heading()
  517. 90.0
  518. .. function:: radians()
  519. Set the angle measurement units to radians. Equivalent to
  520. ``degrees(2*math.pi)``.
  521. .. doctest::
  522. >>> turtle.home()
  523. >>> turtle.left(90)
  524. >>> turtle.heading()
  525. 90.0
  526. >>> turtle.radians()
  527. >>> turtle.heading()
  528. 1.5707963267948966
  529. .. doctest::
  530. :hide:
  531. >>> turtle.degrees(360)
  532. Pen control
  533. -----------
  534. Drawing state
  535. ~~~~~~~~~~~~~
  536. .. function:: pendown()
  537. pd()
  538. down()
  539. Pull the pen down -- drawing when moving.
  540. .. function:: penup()
  541. pu()
  542. up()
  543. Pull the pen up -- no drawing when moving.
  544. .. function:: pensize(width=None)
  545. width(width=None)
  546. :param width: a positive number
  547. Set the line thickness to *width* or return it. If resizemode is set to
  548. "auto" and turtleshape is a polygon, that polygon is drawn with the same line
  549. thickness. If no argument is given, the current pensize is returned.
  550. .. doctest::
  551. >>> turtle.pensize()
  552. 1
  553. >>> turtle.pensize(10) # from here on lines of width 10 are drawn
  554. .. function:: pen(pen=None, **pendict)
  555. :param pen: a dictionary with some or all of the below listed keys
  556. :param pendict: one or more keyword-arguments with the below listed keys as keywords
  557. Return or set the pen's attributes in a "pen-dictionary" with the following
  558. key/value pairs:
  559. * "shown": True/False
  560. * "pendown": True/False
  561. * "pencolor": color-string or color-tuple
  562. * "fillcolor": color-string or color-tuple
  563. * "pensize": positive number
  564. * "speed": number in range 0..10
  565. * "resizemode": "auto" or "user" or "noresize"
  566. * "stretchfactor": (positive number, positive number)
  567. * "outline": positive number
  568. * "tilt": number
  569. This dictionary can be used as argument for a subsequent call to :func:`pen`
  570. to restore the former pen-state. Moreover one or more of these attributes
  571. can be provided as keyword-arguments. This can be used to set several pen
  572. attributes in one statement.
  573. .. doctest::
  574. :options: +NORMALIZE_WHITESPACE
  575. >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
  576. >>> sorted(turtle.pen().items())
  577. [('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),
  578. ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
  579. ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0)]
  580. >>> penstate=turtle.pen()
  581. >>> turtle.color("yellow", "")
  582. >>> turtle.penup()
  583. >>> sorted(turtle.pen().items())
  584. [('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow'),
  585. ('pendown', False), ('pensize', 10), ('resizemode', 'noresize'),
  586. ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0)]
  587. >>> turtle.pen(penstate, fillcolor="green")
  588. >>> sorted(turtle.pen().items())
  589. [('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red'),
  590. ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
  591. ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0)]
  592. .. function:: isdown()
  593. Return ``True`` if pen is down, ``False`` if it's up.
  594. .. doctest::
  595. >>> turtle.penup()
  596. >>> turtle.isdown()
  597. False
  598. >>> turtle.pendown()
  599. >>> turtle.isdown()
  600. True
  601. Color control
  602. ~~~~~~~~~~~~~
  603. .. function:: pencolor(*args)
  604. Return or set the pencolor.
  605. Four input formats are allowed:
  606. ``pencolor()``
  607. Return the current pencolor as color specification string or
  608. as a tuple (see example). May be used as input to another
  609. color/pencolor/fillcolor call.
  610. ``pencolor(colorstring)``
  611. Set pencolor to *colorstring*, which is a Tk color specification string,
  612. such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.
  613. ``pencolor((r, g, b))``
  614. Set pencolor to the RGB color represented by the tuple of *r*, *g*, and
  615. *b*. Each of *r*, *g*, and *b* must be in the range 0..colormode, where
  616. colormode is either 1.0 or 255 (see :func:`colormode`).
  617. ``pencolor(r, g, b)``
  618. Set pencolor to the RGB color represented by *r*, *g*, and *b*. Each of
  619. *r*, *g*, and *b* must be in the range 0..colormode.
  620. If turtleshape is a polygon, the outline of that polygon is drawn with the
  621. newly set pencolor.
  622. .. doctest::
  623. >>> colormode()
  624. 1.0
  625. >>> turtle.pencolor()
  626. 'red'
  627. >>> turtle.pencolor("brown")
  628. >>> turtle.pencolor()
  629. 'brown'
  630. >>> tup = (0.2, 0.8, 0.55)
  631. >>> turtle.pencolor(tup)
  632. >>> turtle.pencolor()
  633. (0.20000000000000001, 0.80000000000000004, 0.5490196078431373)
  634. >>> colormode(255)
  635. >>> turtle.pencolor()
  636. (51, 204, 140)
  637. >>> turtle.pencolor('#32c18f')
  638. >>> turtle.pencolor()
  639. (50, 193, 143)
  640. .. function:: fillcolor(*args)
  641. Return or set the fillcolor.
  642. Four input formats are allowed:
  643. ``fillcolor()``
  644. Return the current fillcolor as color specification string, possibly
  645. in tuple format (see example). May be used as input to another
  646. color/pencolor/fillcolor call.
  647. ``fillcolor(colorstring)``
  648. Set fillcolor to *colorstring*, which is a Tk color specification string,
  649. such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.
  650. ``fillcolor((r, g, b))``
  651. Set fillcolor to the RGB color represented by the tuple of *r*, *g*, and
  652. *b*. Each of *r*, *g*, and *b* must be in the range 0..colormode, where
  653. colormode is either 1.0 or 255 (see :func:`colormode`).
  654. ``fillcolor(r, g, b)``
  655. Set fillcolor to the RGB color represented by *r*, *g*, and *b*. Each of
  656. *r*, *g*, and *b* must be in the range 0..colormode.
  657. If turtleshape is a polygon, the interior of that polygon is drawn
  658. with the newly set fillcolor.
  659. .. doctest::
  660. >>> turtle.fillcolor("violet")
  661. >>> turtle.fillcolor()
  662. 'violet'
  663. >>> col = turtle.pencolor()
  664. >>> col
  665. (50, 193, 143)
  666. >>> turtle.fillcolor(col)
  667. >>> turtle.fillcolor()
  668. (50, 193, 143)
  669. >>> turtle.fillcolor('#ffffff')
  670. >>> turtle.fillcolor()
  671. (255, 255, 255)
  672. .. function:: color(*args)
  673. Return or set pencolor and fillcolor.
  674. Several input formats are allowed. They use 0 to 3 arguments as
  675. follows:
  676. ``color()``
  677. Return the current pencolor and the current fillcolor as a pair of color
  678. specification strings or tuples as returned by :func:`pencolor` and
  679. :func:`fillcolor`.
  680. ``color(colorstring)``, ``color((r,g,b))``, ``color(r,g,b)``
  681. Inputs as in :func:`pencolor`, set both, fillcolor and pencolor, to the
  682. given value.
  683. ``color(colorstring1, colorstring2)``, ``color((r1,g1,b1), (r2,g2,b2))``
  684. Equivalent to ``pencolor(colorstring1)`` and ``fillcolor(colorstring2)``
  685. and analogously if the other input format is used.
  686. If turtleshape is a polygon, outline and interior of that polygon is drawn
  687. with the newly set colors.
  688. .. doctest::
  689. >>> turtle.color("red", "green")
  690. >>> turtle.color()
  691. ('red', 'green')
  692. >>> color("#285078", "#a0c8f0")
  693. >>> color()
  694. ((40, 80, 120), (160, 200, 240))
  695. See also: Screen method :func:`colormode`.
  696. Filling
  697. ~~~~~~~
  698. .. doctest::
  699. :hide:
  700. >>> turtle.home()
  701. .. function:: fill(flag)
  702. :param flag: True/False (or 1/0 respectively)
  703. Call ``fill(True)`` before drawing the shape you want to fill, and
  704. ``fill(False)`` when done. When used without argument: return fillstate
  705. (``True`` if filling, ``False`` else).
  706. .. doctest::
  707. >>> turtle.fill(True)
  708. >>> for _ in range(3):
  709. ... turtle.forward(100)
  710. ... turtle.left(120)
  711. ...
  712. >>> turtle.fill(False)
  713. .. function:: begin_fill()
  714. Call just before drawing a shape to be filled. Equivalent to ``fill(True)``.
  715. .. function:: end_fill()
  716. Fill the shape drawn after the last call to :func:`begin_fill`. Equivalent
  717. to ``fill(False)``.
  718. .. doctest::
  719. >>> turtle.color("black", "red")
  720. >>> turtle.begin_fill()
  721. >>> turtle.circle(80)
  722. >>> turtle.end_fill()
  723. More drawing control
  724. ~~~~~~~~~~~~~~~~~~~~
  725. .. function:: reset()
  726. Delete the turtle's drawings from the screen, re-center the turtle and set
  727. variables to the default values.
  728. .. doctest::
  729. >>> turtle.goto(0,-22)
  730. >>> turtle.left(100)
  731. >>> turtle.position()
  732. (0.00,-22.00)
  733. >>> turtle.heading()
  734. 100.0
  735. >>> turtle.reset()
  736. >>> turtle.position()
  737. (0.00,0.00)
  738. >>> turtle.heading()
  739. 0.0
  740. .. function:: clear()
  741. Delete the turtle's drawings from the screen. Do not move turtle. State and
  742. position of the turtle as well as drawings of other turtles are not affected.
  743. .. function:: write(arg, move=False, align="left", font=("Arial", 8, "normal"))
  744. :param arg: object to be written to the TurtleScreen
  745. :param move: True/False
  746. :param align: one of the strings "left", "center" or right"
  747. :param font: a triple (fontname, fontsize, fonttype)
  748. Write text - the string representation of *arg* - at the current turtle
  749. position according to *align* ("left", "center" or right") and with the given
  750. font. If *move* is True, the pen is moved to the bottom-right corner of the
  751. text. By default, *move* is False.
  752. >>> turtle.write("Home = ", True, align="center")
  753. >>> turtle.write((0,0), True)
  754. Turtle state
  755. ------------
  756. Visibility
  757. ~~~~~~~~~~
  758. .. function:: hideturtle()
  759. ht()
  760. Make the turtle invisible. It's a good idea to do this while you're in the
  761. middle of doing some complex drawing, because hiding the turtle speeds up the
  762. drawing observably.
  763. .. doctest::
  764. >>> turtle.hideturtle()
  765. .. function:: showturtle()
  766. st()
  767. Make the turtle visible.
  768. .. doctest::
  769. >>> turtle.showturtle()
  770. .. function:: isvisible()
  771. Return True if the Turtle is shown, False if it's hidden.
  772. >>> turtle.hideturtle()
  773. >>> turtle.isvisible()
  774. False
  775. >>> turtle.showturtle()
  776. >>> turtle.isvisible()
  777. True
  778. Appearance
  779. ~~~~~~~~~~
  780. .. function:: shape(name=None)
  781. :param name: a string which is a valid shapename
  782. Set turtle shape to shape with given *name* or, if name is not given, return
  783. name of current shape. Shape with *name* must exist in the TurtleScreen's
  784. shape dictionary. Initially there are the following polygon shapes: "arrow",
  785. "turtle", "circle", "square", "triangle", "classic". To learn about how to
  786. deal with shapes see Screen method :func:`register_shape`.
  787. .. doctest::
  788. >>> turtle.shape()
  789. 'classic'
  790. >>> turtle.shape("turtle")
  791. >>> turtle.shape()
  792. 'turtle'
  793. .. function:: resizemode(rmode=None)
  794. :param rmode: one of the strings "auto", "user", "noresize"
  795. Set resizemode to one of the values: "auto", "user", "noresize". If *rmode*
  796. is not given, return current resizemode. Different resizemodes have the
  797. following effects:
  798. - "auto": adapts the appearance of the turtle corresponding to the value of pensize.
  799. - "user": adapts the appearance of the turtle according to the values of
  800. stretchfactor and outlinewidth (outline), which are set by
  801. :func:`shapesize`.
  802. - "noresize": no adaption of the turtle's appearance takes place.
  803. resizemode("user") is called by :func:`shapesize` when used with arguments.
  804. .. doctest::
  805. >>> turtle.resizemode()
  806. 'noresize'
  807. >>> turtle.resizemode("auto")
  808. >>> turtle.resizemode()
  809. 'auto'
  810. .. function:: shapesize(stretch_wid=None, stretch_len=None, outline=None)
  811. turtlesize(stretch_wid=None, stretch_len=None, outline=None)
  812. :param stretch_wid: positive number
  813. :param stretch_len: positive number
  814. :param outline: positive number
  815. Return or set the pen's attributes x/y-stretchfactors and/or outline. Set
  816. resizemode to "user". If and only if resizemode is set to "user", the turtle
  817. will be displayed stretched according to its stretchfactors: *stretch_wid* is
  818. stretchfactor perpendicular to its orientation, *stretch_len* is
  819. stretchfactor in direction of its orientation, *outline* determines the width
  820. of the shapes's outline.
  821. .. doctest::
  822. >>> turtle.shapesize()
  823. (1, 1, 1)
  824. >>> turtle.resizemode("user")
  825. >>> turtle.shapesize(5, 5, 12)
  826. >>> turtle.shapesize()
  827. (5, 5, 12)
  828. >>> turtle.shapesize(outline=8)
  829. >>> turtle.shapesize()
  830. (5, 5, 8)
  831. .. function:: tilt(angle)
  832. :param angle: a number
  833. Rotate the turtleshape by *angle* from its current tilt-angle, but do *not*
  834. change the turtle's heading (direction of movement).
  835. .. doctest::
  836. >>> turtle.reset()
  837. >>> turtle.shape("circle")
  838. >>> turtle.shapesize(5,2)
  839. >>> turtle.tilt(30)
  840. >>> turtle.fd(50)
  841. >>> turtle.tilt(30)
  842. >>> turtle.fd(50)
  843. .. function:: settiltangle(angle)
  844. :param angle: a number
  845. Rotate the turtleshape to point in the direction specified by *angle*,
  846. regardless of its current tilt-angle. *Do not* change the turtle's heading
  847. (direction of movement).
  848. .. doctest::
  849. >>> turtle.reset()
  850. >>> turtle.shape("circle")
  851. >>> turtle.shapesize(5,2)
  852. >>> turtle.settiltangle(45)
  853. >>> turtle.fd(50)
  854. >>> turtle.settiltangle(-45)
  855. >>> turtle.fd(50)
  856. .. function:: tiltangle()
  857. Return the current tilt-angle, i.e. the angle between the orientation of the
  858. turtleshape and the heading of the turtle (its direction of movement).
  859. .. doctest::
  860. >>> turtle.reset()
  861. >>> turtle.shape("circle")
  862. >>> turtle.shapesize(5,2)
  863. >>> turtle.tilt(45)
  864. >>> turtle.tiltangle()
  865. 45.0
  866. Using events
  867. ------------
  868. .. function:: onclick(fun, btn=1, add=None)
  869. :param fun: a function with two arguments which will be called with the
  870. coordinates of the clicked point on the canvas
  871. :param num: number of the mouse-button, defaults to 1 (left mouse button)
  872. :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
  873. added, otherwise it will replace a former binding
  874. Bind *fun* to mouse-click events on this turtle. If *fun* is ``None``,
  875. existing bindings are removed. Example for the anonymous turtle, i.e. the
  876. procedural way:
  877. .. doctest::
  878. >>> def turn(x, y):
  879. ... left(180)
  880. ...
  881. >>> onclick(turn) # Now clicking into the turtle will turn it.
  882. >>> onclick(None) # event-binding will be removed
  883. .. function:: onrelease(fun, btn=1, add=None)
  884. :param fun: a function with two arguments which will be called with the
  885. coordinates of the clicked point on the canvas
  886. :param num: number of the mouse-button, defaults to 1 (left mouse button)
  887. :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
  888. added, otherwise it will replace a former binding
  889. Bind *fun* to mouse-button-release events on this turtle. If *fun* is
  890. ``None``, existing bindings are removed.
  891. .. doctest::
  892. >>> class MyTurtle(Turtle):
  893. ... def glow(self,x,y):
  894. ... self.fillcolor("red")
  895. ... def unglow(self,x,y):
  896. ... self.fillcolor("")
  897. ...
  898. >>> turtle = MyTurtle()
  899. >>> turtle.onclick(turtle.glow) # clicking on turtle turns fillcolor red,
  900. >>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
  901. .. function:: ondrag(fun, btn=1, add=None)
  902. :param fun: a function with two arguments which will be called with the
  903. coordinates of the clicked point on the canvas
  904. :param num: number of the mouse-button, defaults to 1 (left mouse button)
  905. :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
  906. added, otherwise it will replace a former binding
  907. Bind *fun* to mouse-move events on this turtle. If *fun* is ``None``,
  908. existing bindings are removed.
  909. Remark: Every sequence of mouse-move-events on a turtle is preceded by a
  910. mouse-click event on that turtle.
  911. .. doctest::
  912. >>> turtle.ondrag(turtle.goto)
  913. Subsequently, clicking and dragging the Turtle will move it across
  914. the screen thereby producing handdrawings (if pen is down).
  915. Special Turtle methods
  916. ----------------------
  917. .. function:: begin_poly()
  918. Start recording the vertices of a polygon. Current turtle position is first
  919. vertex of polygon.
  920. .. function:: end_poly()
  921. Stop recording the vertices of a polygon. Current turtle position is last
  922. vertex of polygon. This will be connected with the first vertex.
  923. .. function:: get_poly()
  924. Return the last recorded polygon.
  925. .. doctest::
  926. >>> turtle.home()
  927. >>> turtle.begin_poly()
  928. >>> turtle.fd(100)
  929. >>> turtle.left(20)
  930. >>> turtle.fd(30)
  931. >>> turtle.left(60)
  932. >>> turtle.fd(50)
  933. >>> turtle.end_poly()
  934. >>> p = turtle.get_poly()
  935. >>> register_shape("myFavouriteShape", p)
  936. .. function:: clone()
  937. Create and return a clone of the turtle with same position, heading and
  938. turtle properties.
  939. .. doctest::
  940. >>> mick = Turtle()
  941. >>> joe = mick.clone()
  942. .. function:: getturtle()
  943. getpen()
  944. Return the Turtle object itself. Only reasonable use: as a function to
  945. return the "anonymous turtle":
  946. .. doctest::
  947. >>> pet = getturtle()
  948. >>> pet.fd(50)
  949. >>> pet
  950. <turtle.Turtle object at 0x...>
  951. .. function:: getscreen()
  952. Return the :class:`TurtleScreen` object the turtle is drawing on.
  953. TurtleScreen methods can then be called for that object.
  954. .. doctest::
  955. >>> ts = turtle.getscreen()
  956. >>> ts
  957. <turtle._Screen object at 0x...>
  958. >>> ts.bgcolor("pink")
  959. .. function:: setundobuffer(size)
  960. :param size: an integer or ``None``
  961. Set or disable undobuffer. If *size* is an integer an empty undobuffer of
  962. given size is installed. *size* gives the maximum number of turtle actions
  963. that can be undone by the :func:`undo` method/function. If *size* is
  964. ``None``, the undobuffer is disabled.
  965. .. doctest::
  966. >>> turtle.setundobuffer(42)
  967. .. function:: undobufferentries()
  968. Return number of entries in the undobuffer.
  969. .. doctest::
  970. >>> while undobufferentries():
  971. ... undo()
  972. .. function:: tracer(flag=None, delay=None)
  973. A replica of the corresponding TurtleScreen method.
  974. .. deprecated:: 2.6
  975. .. function:: window_width()
  976. window_height()
  977. Both are replicas of the corresponding TurtleScreen methods.
  978. .. deprecated:: 2.6
  979. .. _compoundshapes:
  980. Excursus about the use of compound shapes
  981. -----------------------------------------
  982. To use compound turtle shapes, which consist of several polygons of different
  983. color, you must use the helper class :class:`Shape` explicitly as described
  984. below:
  985. 1. Create an empty Shape object of type "compound".
  986. 2. Add as many components to this object as desired, using the
  987. :meth:`addcomponent` method.
  988. For example:
  989. .. doctest::
  990. >>> s = Shape("compound")
  991. >>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))
  992. >>> s.addcomponent(poly1, "red", "blue")
  993. >>> poly2 = ((0,0),(10,-5),(-10,-5))
  994. >>> s.addcomponent(poly2, "blue", "red")
  995. 3. Now add the Shape to the Screen's shapelist and use it:
  996. .. doctest::
  997. >>> register_shape("myshape", s)
  998. >>> shape("myshape")
  999. .. note::
  1000. The :class:`Shape` class is used internally by the :func:`register_shape`
  1001. method in different ways. The application programmer has to deal with the
  1002. Shape class *only* when using compound shapes like shown above!
  1003. Methods of TurtleScreen/Screen and corresponding functions
  1004. ==========================================================
  1005. Most of the examples in this section refer to a TurtleScreen instance called
  1006. ``screen``.
  1007. .. doctest::
  1008. :hide:
  1009. >>> screen = Screen()
  1010. Window control
  1011. --------------
  1012. .. function:: bgcolor(*args)
  1013. :param args: a color string or three numbers in the range 0..colormode or a
  1014. 3-tuple of such numbers
  1015. Set or return background color of the TurtleScreen.
  1016. .. doctest::
  1017. >>> screen.bgcolor("orange")
  1018. >>> screen.bgcolor()
  1019. 'orange'
  1020. >>> screen.bgcolor("#800080")
  1021. >>> screen.bgcolor()
  1022. (128, 0, 128)
  1023. .. function:: bgpic(picname=None)
  1024. :param picname: a string, name of a gif-file or ``"nopic"``, or ``None``
  1025. Set background image or return name of current backgroundimage. If *picname*
  1026. is a filename, set the corresponding image as background. If *picname* is
  1027. ``"nopic"``, delete background image, if present. If *picname* is ``None``,
  1028. return the filename of the current backgroundimage. ::
  1029. >>> screen.bgpic()
  1030. 'nopic'
  1031. >>> screen.bgpic("landscape.gif")
  1032. >>> screen.bgpic()
  1033. "landscape.gif"
  1034. .. function:: clear()
  1035. clearscreen()
  1036. Delete all drawings and all turtles from the TurtleScreen. Reset the now
  1037. empty TurtleScreen to its initial state: white background, no background
  1038. image, no event bindings and tracing on.
  1039. .. note::
  1040. This TurtleScreen method is available as a global function only under the
  1041. name ``clearscreen``. The global function ``clear`` is another one
  1042. derived from the Turtle method ``clear``.
  1043. .. function:: reset()
  1044. resetscreen()
  1045. Reset all Turtles on the Screen to their initial state.
  1046. .. note::
  1047. This TurtleScreen method is available as a global function only under the
  1048. name ``resetscreen``. The global function ``reset`` is another one
  1049. derived from the Turtle method ``reset``.
  1050. .. function:: screensize(canvwidth=None, canvheight=None, bg=None)
  1051. :param canvwidth: positive integer, new width of canvas in pixels
  1052. :param canvheight: positive integer, new height of canvas in pixels
  1053. :param bg: colorstring or color-tuple, new background color
  1054. If no arguments are given, return current (canvaswidth, canvasheight). Else
  1055. resize the canvas the turtles are drawing on. Do not alter the drawing
  1056. window. To observe hidden parts of the canvas, use the scrollbars. With this
  1057. method, one can make visible those parts of a drawing which were outside the
  1058. canvas before.
  1059. >>> screen.screensize()
  1060. (400, 300)
  1061. >>> screen.screensize(2000,1500)
  1062. >>> screen.screensize()
  1063. (2000, 1500)
  1064. e.g. to search for an erroneously escaped turtle ;-)
  1065. .. function:: setworldcoordinates(llx, lly, urx, ury)
  1066. :param llx: a number, x-coordinate of lower left corner of canvas
  1067. :param lly: a number, y-coordinate of lower left corner of canvas
  1068. :param urx: a number, x-coordinate of upper right corner of canvas
  1069. :param ury: a number, y-coordinate of upper right corner of canvas
  1070. Set up user-defined coordinate system and switch to mode "world" if
  1071. necessary. This performs a ``screen.reset()``. If mode "world" is already
  1072. active, all drawings are redrawn according to the new coordinates.
  1073. **ATTENTION**: in user-defined coordinate systems angles may appear
  1074. distorted.
  1075. .. doctest::
  1076. >>> screen.reset()
  1077. >>> screen.setworldcoordinates(-50,-7.5,50,7.5)
  1078. >>> for _ in range(72):
  1079. ... left(10)
  1080. ...
  1081. >>> for _ in range(8):
  1082. ... left(45); fd(2) # a regular octagon
  1083. .. doctest::
  1084. :hide:
  1085. >>> screen.reset()
  1086. >>> for t in turtles():
  1087. ... t.reset()
  1088. Animation control
  1089. -----------------
  1090. .. function:: delay(delay=None)
  1091. :param delay: positive integer
  1092. Set or return the drawing *delay* in milliseconds. (This is approximately
  1093. the time interval between two consecutive canvas updates.) The longer the
  1094. drawing delay, the slower the animation.
  1095. Optional argument:
  1096. .. doctest::
  1097. >>> screen.delay()
  1098. 10
  1099. >>> screen.delay(5)
  1100. >>> screen.delay()
  1101. 5
  1102. .. function:: tracer(n=None, delay=None)
  1103. :param n: nonnegative integer
  1104. :param delay: nonnegative integer
  1105. Turn turtle animation on/off and set delay for update drawings. If *n* is
  1106. given, only each n-th regular screen update is really performed. (Can be
  1107. used to accelerate the drawing of complex graphics.) Second argument sets
  1108. delay value (see :func:`delay`).
  1109. .. doctest::
  1110. >>> screen.tracer(8, 25)
  1111. >>> dist = 2
  1112. >>> for i in range(200):
  1113. ... fd(dist)
  1114. ... rt(90)
  1115. ... dist += 2
  1116. .. function:: update()
  1117. Perform a TurtleScreen update. To be used when tracer is turned off.
  1118. See also the RawTurtle/Turtle method :func:`speed`.
  1119. Using screen events
  1120. -------------------
  1121. .. function:: listen(xdummy=None, ydummy=None)
  1122. Set focus on TurtleScreen (in order to collect key-events). Dummy arguments
  1123. are provided in order to be able to pass :func:`listen` to the onclick method.
  1124. .. function:: onkey(fun, key)
  1125. :param fun: a function with no arguments or ``None``
  1126. :param key: a string: key (e.g. "a") or key-symbol (e.g. "space")
  1127. Bind *fun* to key-release event of key. If *fun* is ``None``, event bindings
  1128. are removed. Remark: in order to be able to register key-events, TurtleScreen
  1129. must have the focus. (See method :func:`listen`.)
  1130. .. doctest::
  1131. >>> def f():
  1132. ... fd(50)
  1133. ... lt(60)
  1134. ...
  1135. >>> screen.onkey(f, "Up")
  1136. >>> screen.listen()
  1137. .. function:: onclick(fun, btn=1, add=None)
  1138. onscreenclick(fun, btn=1, add=None)
  1139. :param fun: a function with two arguments which will be called with the
  1140. coordinates of the clicked point on the canvas
  1141. :param num: number of the mouse-button, defaults to 1 (left mouse button)
  1142. :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
  1143. added, otherwise it will replace a former binding
  1144. Bind *fun* to mouse-click events on this screen. If *fun* is ``None``,
  1145. existing bindings are removed.
  1146. Example for a TurtleScreen instance named ``screen`` and a Turtle instance
  1147. named turtle:
  1148. .. doctest::
  1149. >>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
  1150. >>> # make the turtle move to the clicked point.
  1151. >>> screen.onclick(None) # remove event binding again
  1152. .. note::
  1153. This TurtleScreen method is available as a global function only under the
  1154. name ``onscreenclick``. The global function ``onclick`` is another one
  1155. derived from the Turtle method ``onclick``.
  1156. .. function:: ontimer(fun, t=0)
  1157. :param fun: a function with no arguments
  1158. :param t: a number >= 0
  1159. Install a timer that calls *fun* after *t* milliseconds.
  1160. .. doctest::
  1161. >>> running = True
  1162. >>> def f():
  1163. ... if running:
  1164. ... fd(50)
  1165. ... lt(60)
  1166. ... screen.ontimer(f, 250)
  1167. >>> f() ### makes the turtle march around
  1168. >>> running = False
  1169. Settings and special methods
  1170. ----------------------------
  1171. .. function:: mode(mode=None)
  1172. :param mode: one of the strings "standard", "logo" or "world"
  1173. Set turtle mode ("standard", "logo" or "world") and perform reset. If mode
  1174. is not given, current mode is returned.
  1175. Mode "standard" is compatible with old :mod:`turtle`. Mode "logo" is
  1176. compatible with most Logo turtle graphics. Mode "world" uses user-defined
  1177. "world coordinates". **Attention**: in this mode angles appear distorted if
  1178. ``x/y`` unit-ratio doesn't equal 1.
  1179. ============ ========================= ===================
  1180. Mode Initial turtle heading positive angles
  1181. ============ ========================= ===================
  1182. "standard" to the right (east) counterclockwise
  1183. "logo" upward (north) clockwise
  1184. ============ ========================= ===================
  1185. .. doctest::
  1186. >>> mode("logo") # resets turtle heading to north
  1187. >>> mode()
  1188. 'logo'
  1189. .. function:: colormode(cmode=None)
  1190. :param cmode: one of the values 1.0 or 255
  1191. Return the colormode or set it to 1.0 or 255. Subsequently *r*, *g*, *b*
  1192. values of color triples have to be in the range 0..\ *cmode*.
  1193. .. doctest::
  1194. >>> screen.colormode(1)
  1195. >>> turtle.pencolor(240, 160, 80)
  1196. Traceback (most recent call last):
  1197. ...
  1198. TurtleGraphicsError: bad color sequence: (240, 160, 80)
  1199. >>> screen.colormode()
  1200. 1.0
  1201. >>> screen.colormode(255)
  1202. >>> screen.colormode()
  1203. 255
  1204. >>> turtle.pencolor(240,160,80)
  1205. .. function:: getcanvas()
  1206. Return the Canvas of this TurtleScreen. Useful for insiders who know what to
  1207. do with a Tkinter Canvas.
  1208. .. doctest::
  1209. >>> cv = screen.getcanvas()
  1210. >>> cv
  1211. <turtle.ScrolledCanvas instance at 0x...>
  1212. .. function:: getshapes()
  1213. Return a list of names of all currently available turtle shapes.
  1214. .. doctest::
  1215. >>> screen.getshapes()
  1216. ['arrow', 'blank', 'circle', ..., 'turtle']
  1217. .. function:: register_shape(name, shape=None)
  1218. addshape(name, shape=None)
  1219. There are three different ways to call this function:
  1220. (1) *name* is the name of a gif-file and *shape* is ``None``: Install the
  1221. corresponding image shape. ::
  1222. >>> screen.register_shape("turtle.gif")
  1223. .. note::
  1224. Image shapes *do not* rotate when turning the turtle, so they do not
  1225. display the heading of the turtle!
  1226. (2) *name* is an arbitrary string and *shape* is a tuple of pairs of
  1227. coordinates: Install the corresponding polygon shape.
  1228. .. doctest::
  1229. >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
  1230. (3) *name* is an arbitrary string and shape is a (compound) :class:`Shape`
  1231. object: Install the corresponding compound shape.
  1232. Add a turtle shape to TurtleScreen's shapelist. Only thusly registered
  1233. shapes can be used by issuing the command ``shape(shapename)``.
  1234. .. function:: turtles()
  1235. Return the list of turtles on the screen.
  1236. .. doctest::
  1237. >>> for turtle in screen.turtles():
  1238. ... turtle.color("red")
  1239. .. function:: window_height()
  1240. Return the height of the turtle window. ::
  1241. >>> screen.window_height()
  1242. 480
  1243. .. function:: window_width()
  1244. Return the width of the turtle window. ::
  1245. >>> screen.window_width()
  1246. 640
  1247. .. _screenspecific:
  1248. Methods specific to Screen, not inherited from TurtleScreen
  1249. -----------------------------------------------------------
  1250. .. function:: bye()
  1251. Shut the turtlegraphics window.
  1252. .. function:: exitonclick()
  1253. Bind bye() method to mouse clicks on the Screen.
  1254. If the value "using_IDLE" in the configuration dictionary is ``False``
  1255. (default value), also enter mainloop. Remark: If IDLE with the ``-n`` switch
  1256. (no subprocess) is used, this value should be set to ``True`` in
  1257. :file:`turtle.cfg`. In this case IDLE's own mainloop is active also for the
  1258. client script.
  1259. .. function:: setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])
  1260. Set the size and position of the main window. Default values of arguments
  1261. are stored in the configuration dicionary and can be changed via a
  1262. :file:`turtle.cfg` file.
  1263. :param width: if an integer, a size in pixels, if a float, a fraction of the
  1264. screen; default is 50% of screen
  1265. :param height: if an integer, the height in pixels, if a float, a fraction of
  1266. the screen; default is 75% of screen
  1267. :param startx: if positive, starting position in pixels from the left
  1268. edge of the screen, if negative from the right edge, if None,
  1269. center window horizontally
  1270. :param startx: if positive, starting position in pixels from the top
  1271. edge of the screen, if negative from the bottom edge, if None,
  1272. center window vertically
  1273. .. doctest::
  1274. >>> screen.setup (width=200, height=200, startx=0, starty=0)
  1275. >>> # sets window to 200x200 pixels, in upper left of screen
  1276. >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
  1277. >>> # sets window to 75% of screen by 50% of screen and centers
  1278. .. function:: title(titlestring)
  1279. :param titlestring: a string that is shown in the titlebar of the turtle
  1280. graphics window
  1281. Set title of turtle window to *titlestring*.
  1282. .. doctest::
  1283. >>> screen.title("Welcome to the turtle zoo!")
  1284. The public classes of the module :mod:`turtle`
  1285. ==============================================
  1286. .. class:: RawTurtle(canvas)
  1287. RawPen(canvas)
  1288. :param canvas: a :class:`Tkinter.Canvas`, a :class:`ScrolledCanvas` or a
  1289. :class:`TurtleScreen`
  1290. Create a turtle. The turtle has all methods described above as "methods of
  1291. Turtle/RawTurtle".
  1292. .. class:: Turtle()
  1293. Subclass of RawTurtle, has the same interface but draws on a default
  1294. :class:`Screen` object created automatically when needed for the first time.
  1295. .. class:: TurtleScreen(cv)
  1296. :param cv: a :class:`Tkinter.Canvas`
  1297. Provides screen oriented methods like :func:`setbg` etc. that are described
  1298. above.
  1299. .. class:: Screen()
  1300. Subclass of TurtleScreen, with :ref:`four methods added <screenspecific>`.
  1301. .. class:: ScrolledCavas(master)
  1302. :param master: some Tkinter widget to contain the ScrolledCanvas, i.e.
  1303. a Tkinter-canvas with scrollbars added
  1304. Used by class Screen, which thus automatically provides a ScrolledCanvas as
  1305. playground for the turtles.
  1306. .. class:: Shape(type_, data)
  1307. :param type\_: one of the strings "polygon", "image", "compound"
  1308. Data structure modeling shapes. The pair ``(type_, data)`` must follow this
  1309. specification:
  1310. =========== ===========
  1311. *type_* *data*
  1312. =========== ===========
  1313. "polygon" a polygon-tuple, i.e. a tuple of pairs of coordinates
  1314. "image" an image (in this form only used internally!)
  1315. "compound" ``None`` (a compound shape has to be constructed using the
  1316. :meth:`addcomponent` method)
  1317. =========== ===========
  1318. .. method:: addcomponent(poly, fill, outline=None)
  1319. :param poly: a polygon, i.e. a tuple of pairs of numbers
  1320. :param fill: a color the *poly* will be filled with
  1321. :param outline: a color for the poly's outline (if given)
  1322. Example:
  1323. .. doctest::
  1324. >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
  1325. >>> s = Shape("compound")
  1326. >>> s.addcomponent(poly, "red", "blue")
  1327. >>> # ... add more components and then use register_shape()
  1328. See :ref:`compoundshapes`.
  1329. .. class:: Vec2D(x, y)
  1330. A two-dimensional vector class, used as a helper class for implementing
  1331. turtle graphics. May be useful for turtle graphics programs too. Derived
  1332. from tuple, so a vector is a tuple!
  1333. Provides (for *a*, *b* vectors, *k* number):
  1334. * ``a + b`` vector addition
  1335. * ``a - b`` vector subtraction
  1336. * ``a * b`` inner product
  1337. * ``k * a`` and ``a * k`` multiplication with scalar
  1338. * ``abs(a)`` absolute value of a
  1339. * ``a.rotate(angle)`` rotation
  1340. Help and configuration
  1341. ======================
  1342. How to use help
  1343. ---------------
  1344. The public methods of the Screen and Turtle classes are documented extensively
  1345. via docstrings. So these can be used as online-help via the Python help
  1346. facilities:
  1347. - When using IDLE, tooltips show the signatures and first lines of the
  1348. docstrings of typed in function-/method calls.
  1349. - Calling :func:`help` on methods or functions displays the docstrings::
  1350. >>> help(Screen.bgcolor)
  1351. Help on method bgcolor in module turtle:
  1352. bgcolor(self, *args) unbound turtle.Screen method
  1353. Set or return backgroundcolor of the TurtleScreen.
  1354. Arguments (if given): a color string or three numbers
  1355. in the range 0..colormode or a 3-tuple of such numbers.
  1356. >>> screen.bgcolor("orange")
  1357. >>> screen.bgcolor()
  1358. "orange"
  1359. >>> screen.bgcolor(0.5,0,0.5)
  1360. >>> screen.bgcolor()
  1361. "#800080"
  1362. >>> help(Turtle.penup)
  1363. Help on method penup in module turtle:
  1364. penup(self) unbound turtle.Turtle method
  1365. Pull the pen up -- no drawing when moving.
  1366. Aliases: penup | pu | up
  1367. No argument
  1368. >>> turtle.penup()
  1369. - The docstrings of the functions which are derived from methods have a modified
  1370. form::
  1371. >>> help(bgcolor)
  1372. Help on function bgcolor in module turtle:
  1373. bgcolor(*args)
  1374. Set or return backgroundcolor of the TurtleScreen.
  1375. Arguments (if given): a color string or three numbers
  1376. in the range 0..colormode or a 3-tuple of such numbers.
  1377. Example::
  1378. >>> bgcolor("orange")
  1379. >>> bgcolor()
  1380. "orange"
  1381. >>> bgcolor(0.5,0,0.5)
  1382. >>> bgcolor()
  1383. "#800080"
  1384. >>> help(penup)
  1385. Help on function penup in module turtle:
  1386. penup()
  1387. Pull the pen up -- no drawing when moving.
  1388. Aliases: penup | pu | up
  1389. No argument
  1390. Example:
  1391. >>> penup()
  1392. These modified docstrings are created automatically together with the function
  1393. definitions that are derived from the methods at import time.
  1394. Translation of docstrings into different languages
  1395. --------------------------------------------------
  1396. There is a utility to create a dictionary the keys of which are the method names
  1397. and the values of which are the docstrings of the public methods of the classes
  1398. Screen and Turtle.
  1399. .. function:: write_docstringdict(filename="turtle_docstringdict")
  1400. :param filename: a string, used as filename
  1401. Create and write docstring-dictionary to a Python script with the given
  1402. filename. This function has to be called explicitly (it is not used by the
  1403. turtle graphics classes). The docstring dictionary will be written to the
  1404. Python script :file:`{filename}.py`. It is intended to serve as a template
  1405. for translation of the docstrings into different languages.
  1406. If you (or your students) want to use :mod:`turtle` with online help in your
  1407. native language, you have to translate the docstrings and save the resulting
  1408. file as e.g. :file:`turtle_docstringdict_german.py`.
  1409. If you have an appropriate entry in your :file:`turtle.cfg` file this dictionary
  1410. will be read in at import time and will replace the original English docstrings.
  1411. At the time of this writing there are docstring dictionaries in German and in
  1412. Italian. (Requests please to glingl@aon.at.)
  1413. How to configure Screen and Turtles
  1414. -----------------------------------
  1415. The built-in default configuration mimics the appearance and behaviour of the
  1416. old turtle module in order to retain best possible compatibility with it.
  1417. If you want to use a different configuration which better reflects the features
  1418. of this module or which better fits to your needs, e.g. for use in a classroom,
  1419. you can prepare a configuration file ``turtle.cfg`` which will be read at import
  1420. time and modify the configuration according to its settings.
  1421. The built in configuration would correspond to the following turtle.cfg::
  1422. width = 0.5
  1423. height = 0.75
  1424. leftright = None
  1425. topbottom = None
  1426. canvwidth = 400
  1427. canvheight = 300
  1428. mode = standard
  1429. colormode = 1.0
  1430. delay = 10
  1431. undobuffersize = 1000
  1432. shape = classic
  1433. pencolor = black
  1434. fillcolor = black
  1435. resizemode = noresize
  1436. visible = True
  1437. language = english
  1438. exampleturtle = turtle
  1439. examplescreen = screen
  1440. title = Python Turtle Graphics
  1441. using_IDLE = False
  1442. Short explanation of selected entries:
  1443. - The first four lines correspond to the arguments of the :meth:`Screen.setup`
  1444. method.
  1445. - Line 5 and 6 correspond to the arguments of the method
  1446. :meth:`Screen.screensize`.
  1447. - *shape* can be any of the built-in shapes, e.g: arrow, turtle, etc. For more
  1448. info try ``help(shape)``.
  1449. - If you want to use no fillcolor (i.e. make the turtle transparent), you have
  1450. to write ``fillcolor = ""`` (but all nonempty strings must not have quotes in
  1451. the cfg-file).
  1452. - If you want to reflect the turtle its state, you have to use ``resizemode =
  1453. auto``.
  1454. - If you set e.g. ``language = italian`` the docstringdict
  1455. :file:`turtle_docstringdict_italian.py` will be loaded at import time (if
  1456. present on the import path, e.g. in the same directory as :mod:`turtle`.
  1457. - The entries *exampleturtle* and *examplescreen* define the names of these
  1458. objects as they occur in the docstrings. The transformation of
  1459. method-docstrings to function-docstrings will delete these names from the
  1460. docstrings.
  1461. - *using_IDLE*: Set this to ``True`` if you regularly work with IDLE and its -n
  1462. switch ("no subprocess"). This will prevent :func:`exitonclick` to enter the
  1463. mainloop.
  1464. There can be a :file:`turtle.cfg` file in the directory where :mod:`turtle` is
  1465. stored and an additional one in the current working directory. The latter will
  1466. override the settings of the first one.
  1467. The :file:`Demo/turtle` directory contains a :file:`turtle.cfg` file. You can
  1468. study it as an example and see its effects when running the demos (preferably
  1469. not from within the demo-viewer).
  1470. Demo scripts
  1471. ============
  1472. There is a set of demo scripts in the turtledemo directory located in the
  1473. :file:`Demo/turtle` directory in the source distribution.
  1474. It contains:
  1475. - a set of 15 demo scripts demonstrating different features of the new module
  1476. :mod:`turtle`
  1477. - a demo viewer :file:`turtleDemo.py` which can be used to view the sourcecode
  1478. of the scripts and run them at the same time. 14 of the examples can be
  1479. accessed via the Examples menu; all of them can also be run standalone.
  1480. - The example :file:`turtledemo_two_canvases.py` demonstrates the simultaneous
  1481. use of two canvases with the turtle module. Therefore it only can be run
  1482. standalone.
  1483. - There is a :file:`turtle.cfg` file in this directory, which also serves as an
  1484. example for how to write and use such files.
  1485. The demoscripts are:
  1486. +----------------+------------------------------+-----------------------+
  1487. | Name | Description | Features |
  1488. +----------------+------------------------------+-----------------------+
  1489. | bytedesign | complex classical | :func:`tracer`, delay,|
  1490. | | turtlegraphics pattern | :func:`update` |
  1491. +----------------+------------------------------+-----------------------+
  1492. | chaos | graphs verhust dynamics, | world coordinates |
  1493. | | proves that you must not | |
  1494. | | trust computers' computations| |
  1495. +----------------+------------------------------+-----------------------+
  1496. | clock | analog clock showing time | turtles as clock's |
  1497. | | of your computer | hands, ontimer |
  1498. +----------------+------------------------------+-----------------------+
  1499. | colormixer | experiment with r, g, b | :func:`ondrag` |
  1500. +----------------+------------------------------+-----------------------+
  1501. | fractalcurves | Hilbert & Koch curves | recursion |
  1502. +----------------+------------------------------+-----------------------+
  1503. | lindenmayer | ethnomathematics | L-System |
  1504. | | (indian kolams) | |
  1505. +----------------+------------------------------+-----------------------+
  1506. | minimal_hanoi | Towers of Hanoi | Rectangular Turtles |
  1507. | | | as Hanoi discs |
  1508. | | | (shape, shapesize) |
  1509. +----------------+------------------------------+-----------------------+
  1510. | paint | super minimalistic | :func:`onclick` |
  1511. | | drawing program | |
  1512. +----------------+------------------------------+-----------------------+
  1513. | peace | elementary | turtle: appearance |
  1514. | | | and animation |
  1515. +----------------+------------------------------+-----------------------+
  1516. | penrose | aperiodic tiling with | :func:`stamp` |
  1517. | | kites and darts | |
  1518. +----------------+------------------------------+-----------------------+
  1519. | planet_and_moon| simulation of | compound shapes, |
  1520. | | gravitational system | :class:`Vec2D` |
  1521. +----------------+------------------------------+-----------------------+
  1522. | tree | a (graphical) breadth | :func:`clone` |
  1523. | | first tree (using generators)| |
  1524. +----------------+------------------------------+-----------------------+
  1525. | wikipedia | a pattern from the wikipedia | :func:`clone`, |
  1526. | | article on turtle graphics | :func:`undo` |
  1527. +----------------+------------------------------+-----------------------+
  1528. | yingyang | another elementary example | :func:`circle` |
  1529. +----------------+------------------------------+-----------------------+
  1530. Have fun!
  1531. .. doctest::
  1532. :hide:
  1533. >>> for turtle in turtles():
  1534. ... turtle.reset()
  1535. >>> turtle.penup()
  1536. >>> turtle.goto(-200,25)
  1537. >>> turtle.pendown()
  1538. >>> turtle.write("No one expects the Spanish Inquisition!",
  1539. ... font=("Arial", 20, "normal"))
  1540. >>> turtle.penup()
  1541. >>> turtle.goto(-100,-50)
  1542. >>> turtle.pendown()
  1543. >>> turtle.write("Our two chief Turtles are...",
  1544. ... font=("Arial", 16, "normal"))
  1545. >>> turtle.penup()
  1546. >>> turtle.goto(-450,-75)
  1547. >>> turtle.write(str(turtles()))