turtle
— Tortue graphique¶
Code Source : Lib/turtle.py
Introduction¶
Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.
Imaginez un robot sous forme de tortue partant au centre (0, 0) d'un plan cartésien x-y. Après un import turtle
, exécutez la commande turtle.forward(15)
et la tortue se déplace (sur l'écran) de 15 pixels en face d'elle, en dessinant une ligne.
On peut donc facilement construire des formes et images à partir de commandes simples.
Le module turtle
est une version étendue du module homonyme appartenant à la distribution standard de Python jusqu'à la version 2.5.
Cette bibliothèque essaye de garder les avantages de l'ancien module et d'être (presque) 100% compatible avec celui-ci. Cela permet à l'apprenti développeur d'utiliser toutes les commandes, classes et méthodes de façon interactive pendant qu'il utilise le module depuis IDLE lancé avec l'option -n
.
Turtle permet d'utiliser des primitives graphiques en utilisant un style de programmation orienté objet ou procédural. Du fait qu'il utilise la bibliothèque graphique tkinter
, Turtle a besoin d'une version de python implémentant Tk.
L'interface orientée objet utilise essentiellement deux + deux classes :
La classe
TurtleScreen
définit une fenêtre graphique utilisé comme un terrain de jeu pour les dessins de la tortue. Le constructeur de cette classe a besoin d'untkinter.Canvas
ouScrolledCanvas
comme argument. Cette classe doit être utilisée seulement siturtle
fait partie intégrante d'une autre application.La fonction
Screen()
renvoie un singleton d'une sous-classe deTurtleScreen
. Elle doit être utilisée quand le moduleturtle
est utilisé de façon autonome pour dessiner. Le singleton renvoyé ne peut hériter de sa classe.Toutes les méthodes de TurtleScreen/Screen existent également sous la forme de fonctions, c'est-à-dire que ces dernières peuvent être utilisées dans un style procédural.
La classe
RawTurtle
(aliasRawPen
) définit des objets Turtle qui peuvent dessiner sur la classeTurtleScreen
. Son constructeur prend en paramètre un Canvas, un ScrolledCanvas ou un TurtleScreen permettant à l'objet RawTurtle de savoir où écrire.La sous-classe
Turtle
(alias:Pen
), dérivée de RawTurtle, dessine sur l'instanceScreen
qui est créée automatiquement si elle n'est pas déjà présente.Toutes les méthodes de RawTurtle/Turtle existent également sous la forme de fonctions, c'est-à-dire que ces dernières pourront être utilisées en style procédural.
L'interface procédurale met à disposition des fonctions équivalentes à celles des méthodes des classes Screen
et Turtle
. Le nom d'une fonction est le même que la méthode équivalente. Un objet Screen est créé automatiquement dès qu'une fonction dérivée d'une méthode Screen est appelée. Un objet Turtle (sans nom) est créé automatiquement dès qu'une fonction dérivée d'une méthode Turtle est appelée.
Afin de pouvoir utiliser plusieurs tortues simultanément sur l'écran, vous devez utiliser l'interface orientée-objet.
Note
La liste des paramètres des fonctions est donnée dans cette documentation. Les méthodes ont, évidemment, le paramètre self comme premier argument, mais ce dernier n'est pas indiqué ici.
Résumé des méthodes de Turtle et Screen¶
Les méthodes du module Turtle¶
- Les mouvements dans le module Turtle
- Bouger et dessiner
- Connaître l'état de la tortue
- Paramétrage et mesure
- Réglage des pinceaux
- État des pinceaux
- Réglage des couleurs
- Remplissage
- Plus des réglages pour le dessin
- État de la tortue
- Visibilité
- Apparence
- Utilisation des événements
- Méthodes spéciales de la tortue
Méthodes de TurtleScreen/Screen¶
- Réglage de la fenêtre
- Réglage de l'animation
- Utilisation des événements concernant l'écran
- Paramétrages et méthodes spéciales
- Méthodes de saisie
- Méthodes spécifiques de Screen
Méthodes de RawTurtle/Turtle et leurs fonctions correspondantes¶
La plupart des exemples de cette section se réfèrent à une instance de Turtle appelée turtle
.
Les mouvements dans le module Turtle¶
-
turtle.
forward
(distance)¶ -
turtle.
fd
(distance)¶ - Paramètres
distance -- un nombre (entier ou flottant)
Avance la tortue de la distance spécifiée, dans la direction où elle se dirige.
>>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)
-
turtle.
back
(distance)¶ -
turtle.
bk
(distance)¶ -
turtle.
backward
(distance)¶ - Paramètres
distance -- un nombre
Déplace la tortue de distance vers l'arrière (dans le sens opposé à celui vers lequel elle pointe). Ne change pas le cap de la tortue.
>>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)
-
turtle.
right
(angle)¶ -
turtle.
rt
(angle)¶ - Paramètres
angle -- un nombre (entier ou flottant)
Tourne la tortue à droite de angle unités (les unités sont par défaut des degrés, mais peuvent être définies via les fonctions
degrees()
etradians()
). L'orientation de l'angle dépend du mode de la tortue, voirmode()
.>>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.0
-
turtle.
left
(angle)¶ -
turtle.
lt
(angle)¶ - Paramètres
angle -- un nombre (entier ou flottant)
Tourne la tortue à gauche d'une valeur de angle unités (les unités sont par défaut des degrés, mais peuvent être définies via les fonctions
degrees()
etradians()
). L'orientation de l'angle dépend du mode de la tortue, voirmode()
.>>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.0
-
turtle.
goto
(x, y=None)¶ -
turtle.
setpos
(x, y=None)¶ -
turtle.
setposition
(x, y=None)¶ - Paramètres
x -- un nombre ou une paire / un vecteur de nombres
y -- un nombre ou
None
Si y est
None
, x doit être une paire de coordonnées, ou bien une instance deVec2D
(par exemple, tel que renvoyé parpos()
).Déplace la tortue vers une position absolue. Si le pinceau est en bas, trace une ligne. Ne change pas l'orientation de la tortue.
>>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)
-
turtle.
setx
(x)¶ - Paramètres
x -- un nombre (entier ou flottant)
Définit la première coordonnée de la tortue à x, en laissant la deuxième coordonnée inchangée.
>>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)
-
turtle.
sety
(y)¶ - Paramètres
y -- un nombre (entier ou flottant)
Définit la deuxième coordonnée de la tortue à y, en laissant la première coordonnée inchangée.
>>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)
-
turtle.
setheading
(to_angle)¶ -
turtle.
seth
(to_angle)¶ - Paramètres
to_angle -- un nombre (entier ou flottant)
Règle l'orientation de la tortue à la valeur to_angle. Voici quelques orientations courantes en degrés :
mode standard
mode logo
0 – Est
0 – Nord
90 – Nord
90 – Est
180 – Ouest
180 – Sud
270 – Sud
270 – Ouest
>>> turtle.setheading(90) >>> turtle.heading() 90.0
-
turtle.
home
()¶ Déplace la tortue à l'origine — coordonnées (0,0) — et l'oriente à son cap initial (qui dépend du mode, voir
mode()
).>>> turtle.heading() 90.0 >>> turtle.position() (0.00,-10.00) >>> turtle.home() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.0
-
turtle.
circle
(radius, extent=None, steps=None)¶ - Paramètres
radius -- un nombre
extent -- un nombre (ou
None
)steps -- un entier (ou
None
)
Dessine un cercle de rayon radius. Le centre se trouve à une distance de radius à gauche de la tortue ; l'angle extent détermine quelle partie du cercle est dessinée. Si extent n'est pas fourni, dessine le cercle en entier. Si extent ne correspond pas à un cercle entier, la position actuelle du stylo est donnée par l'un des points d'extrémité de l'arc de cercle. Si la valeur de radius est positive, dessine l'arc de cercle dans le sens inverse des aiguilles d'une montre, sinon le dessine dans le sens des aiguilles d'une montre. Enfin, la direction de la tortue peut être modifiée en réglant la valeur de extent.
Comme le cercle est approximé par un polygone régulier inscrit, steps détermine le nombre de pas à utiliser. Si cette valeur n'est pas donnée, elle sera calculée automatiquement. Elle peut être utilisée pour dessiner des polygones réguliers.
>>> 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() 180.0
-
turtle.
dot
(size=None, *color)¶ - Paramètres
size -- un entier supérieur ou égal à 1 (si fourni)
color -- une chaîne qui désigne une couleur ou un n-uplet de couleur numérique
Dessine un point circulaire de diamètre size, de la couleur color. Si le paramètre size n'est pas indiqué, utilise la valeur maximum de la taille du pinceau plus 4 et de la taille du pinceau multiplié par 2.
>>> 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.
stamp
()¶ Stamp a copy of the turtle shape onto the canvas at the current turtle position. Return a stamp_id for that stamp, which can be used to delete it by calling
clearstamp(stamp_id)
.>>> turtle.color("blue") >>> turtle.stamp() 11 >>> turtle.fd(50)
-
turtle.
clearstamp
(stampid)¶ - Paramètres
stampid -- un entier, doit être la valeur renvoyée par l'appel précédent de
stamp()
Delete stamp with given stampid.
>>> 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)
-
turtle.
clearstamps
(n=None)¶ - Paramètres
n -- un entier (ou
None
)
Delete all or first/last n of turtle's stamps. If n is
None
, delete all stamps, if n > 0 delete first n stamps, else if n < 0 delete last n stamps.>>> for i in range(8): ... turtle.stamp(); turtle.fd(30) 13 14 15 16 17 18 19 20 >>> turtle.clearstamps(2) >>> turtle.clearstamps(-2) >>> turtle.clearstamps()
-
turtle.
undo
()¶ Annule la ou les dernières (si répété) actions de la tortue. Le nombre d'annulations disponible est déterminé par la taille de la mémoire tampon d'annulations.
>>> for i in range(4): ... turtle.fd(50); turtle.lt(80) ... >>> for i in range(8): ... turtle.undo()
-
turtle.
speed
(speed=None)¶ - Paramètres
speed -- un nombre entier compris dans l’intervalle entre 0 et 10 inclus, ou une chaîne de vitesse (voir ci-dessous)
Règle la vitesse de la tortue à une valeur entière comprise entre 0 et 10 inclus. Si aucun argument n'est donné, renvoie la vitesse actuelle.
Si l'entrée est un nombre supérieur à 10 ou inférieur à 0,5, la vitesse est fixée à 0. Les chaînes de vitesse sont mises en correspondance avec les valeurs de vitesse comme suit :
« le plus rapide » : 0
« rapide » : 10
« vitesse normale » : 6
« lent » : 3
« le plus lent » : 1
Les vitesses de 1 à 10 permettent une animation de plus en plus rapide du trait du dessin et de la rotation des tortues.
Attention: speed = 0 means that no animation takes place. forward/back makes turtle jump and likewise left/right make the turtle turn instantly.
>>> turtle.speed() 3 >>> turtle.speed('normal') >>> turtle.speed() 6 >>> turtle.speed(9) >>> turtle.speed() 9
Connaître l'état de la tortue¶
-
turtle.
position
()¶ -
turtle.
pos
()¶ Return the turtle's current location (x,y) (as a
Vec2D
vector).>>> turtle.pos() (440.00,-0.00)
-
turtle.
towards
(x, y=None)¶ - Paramètres
x -- un nombre, ou une paire / un vecteur de nombres, ou une instance de tortue
y -- un nombre si x est un nombre, sinon
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.goto(10, 10) >>> turtle.towards(0,0) 225.0
-
turtle.
xcor
()¶ Renvoie la coordonnée x de la tortue.
>>> turtle.home() >>> turtle.left(50) >>> turtle.forward(100) >>> turtle.pos() (64.28,76.60) >>> print(round(turtle.xcor(), 5)) 64.27876
-
turtle.
ycor
()¶ Renvoie la coordonnée y de la tortue.
>>> turtle.home() >>> turtle.left(60) >>> turtle.forward(100) >>> print(turtle.pos()) (50.00,86.60) >>> print(round(turtle.ycor(), 5)) 86.60254
-
turtle.
heading
()¶ Renvoie le cap de la tortue (la valeur dépend du mode de la tortue, voir
mode()
).>>> turtle.home() >>> turtle.left(67) >>> turtle.heading() 67.0
-
turtle.
distance
(x, y=None)¶ - Paramètres
x -- un nombre, ou une paire / un vecteur de nombres, ou une instance de tortue
y -- un nombre si x est un nombre, sinon
None
Return the distance from the turtle to (x,y), the given vector, or the given other turtle, in turtle step units.
>>> turtle.home() >>> turtle.distance(30,40) 50.0 >>> turtle.distance((30,40)) 50.0 >>> joe = Turtle() >>> joe.forward(77) >>> turtle.distance(joe) 77.0
Paramètres de mesure¶
-
turtle.
degrees
(fullcircle=360.0)¶ - Paramètres
fullcircle -- un nombre
Définit les unités de mesure des angles, c.-à-d. fixe le nombre de « degrés » pour un cercle complet. La valeur par défaut est de 360 degrés.
>>> 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 >>> turtle.degrees(360) >>> turtle.heading() 90.0
-
turtle.
radians
()¶ Règle l'unité de mesure des angles sur radians. Équivalent à
degrees(2*math.pi)
.>>> turtle.home() >>> turtle.left(90) >>> turtle.heading() 90.0 >>> turtle.radians() >>> turtle.heading() 1.5707963267948966
Réglage des pinceaux¶
État des pinceaux¶
-
turtle.
pendown
()¶ -
turtle.
pd
()¶ -
turtle.
down
()¶ Baisse la pointe du stylo — dessine quand il se déplace.
-
turtle.
penup
()¶ -
turtle.
pu
()¶ -
turtle.
up
()¶ Lève la pointe du stylo — pas de dessin quand il se déplace.
-
turtle.
pensize
(width=None)¶ -
turtle.
width
(width=None)¶ - Paramètres
width -- un nombre positif
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.pensize() 1 >>> turtle.pensize(10) # from here on lines of width 10 are drawn
-
turtle.
pen
(pen=None, **pendict)¶ - Paramètres
pen -- un dictionnaire avec certaines ou toutes les clés énumérées ci-dessous
pendict -- un ou plusieurs arguments par mots-clés avec les clés suivantes comme mots-clés
Renvoie ou définit les attributs du pinceau dans un "pen-dictionary" avec les paires clés / valeurs suivantes :
"shown" :
True
/False
"pendown" :
True
/False
"pencolor" : chaîne de caractères ou n-uplet désignant la couleur du pinceau
"fillcolor" : chaîne de caractères ou n-uplet pour la couleur de remplissage
"pensize" : nombre positif
"speed" : nombre compris dans intervalle 0 et 10
"resizemode" : "auto", "user" ou "noresize"
"stretchfactor" : (nombre positif, nombre positif)
"outline" : nombre positif
"tilt" : nombre
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.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.
isdown
()¶ Renvoie
True
si la pointe du stylo est en bas etFalse
si elle est en haut.>>> turtle.penup() >>> turtle.isdown() False >>> turtle.pendown() >>> turtle.isdown() True
Réglage des couleurs¶
-
turtle.
pencolor
(*args)¶ Renvoie ou règle la couleur du pinceau
Quatre formats d'entrée sont autorisés :
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)
Définit la couleur du pinceau à colorstring, qui est une chaîne de spécification de couleur Tk, telle que
"red"
,"yellow"
, ou"#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.
Si la forme de la tortue est un polygone, le contour de ce polygone est dessiné avec la nouvelle couleur du pinceau.
>>> 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)
-
turtle.
fillcolor
(*args)¶ Renvoie ou règle la couleur de remplissage
Quatre formats d'entrée sont autorisés :
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
"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.fillcolor("violet") >>> turtle.fillcolor() 'violet' >>> turtle.pencolor() (50.0, 193.0, 143.0) >>> turtle.fillcolor((50, 193, 143)) # Integers, not floats >>> turtle.fillcolor() (50.0, 193.0, 143.0) >>> turtle.fillcolor('#ffffff') >>> turtle.fillcolor() (255.0, 255.0, 255.0)
-
turtle.
color
(*args)¶ Renvoie ou règle la couleur du pinceau et la couleur de remplissage.
Plusieurs formats d'entrée sont autorisés. Ils peuvent avoir de zéro jusqu'à trois arguments, employés comme suit :
color()
Return the current pencolor and the current fillcolor as a pair of color specification strings or tuples as returned by
pencolor()
andfillcolor()
.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)
andfillcolor(colorstring2)
and analogously if the other input format is used.Si la forme de la tortue est un polygone, le contour et l'intérieur de ce polygone sont dessinés avec les nouvelles couleurs.
>>> turtle.color("red", "green") >>> turtle.color() ('red', 'green') >>> color("#285078", "#a0c8f0") >>> color() ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))
Voir aussi : la méthode colormode()
de Screen.
Remplissage¶
-
turtle.
filling
()¶ Renvoie l'état de remplissage (
True
signifie en train de faire un remplissage,False
sinon).>>> turtle.begin_fill() >>> if turtle.filling(): ... turtle.pensize(5) ... else: ... turtle.pensize(3)
-
turtle.
begin_fill
()¶ À appeler juste avant de dessiner une forme à remplir.
-
turtle.
end_fill
()¶ Remplit la forme dessinée après le dernier appel à
begin_fill()
.Whether or not overlap regions for self-intersecting polygons or multiple shapes are filled depends on the operating system graphics, type of overlap, and number of overlaps. For example, the Turtle star above may be either all yellow or have some white regions.
>>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(80) >>> turtle.end_fill()
Plus des réglages pour le dessin¶
-
turtle.
reset
()¶ Supprime les dessins de la tortue de l'écran, recentre la tortue et assigne les variables aux valeurs par défaut.
>>> 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
-
turtle.
clear
()¶ Supprime les dessins de la tortue de l'écran. Ne déplace pas la tortue. L'état et la position de la tortue ainsi que les dessins des autres tortues ne sont pas affectés.
-
turtle.
write
(arg, move=False, align="left", font=("Arial", 8, "normal"))¶ - Paramètres
arg -- objet à écrire sur le TurtleScreen
move --
True
/False
align -- l'une des chaînes de caractères suivantes : "left", "center" ou "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
.>>> turtle.write("Home = ", True, align="center") >>> turtle.write((0,0), True)
État de la tortue¶
Visibilité¶
-
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.hideturtle()
-
turtle.
isvisible
()¶ Renvoie
True
si la tortue est visible, etFalse
si elle est cachée.>>> turtle.hideturtle() >>> turtle.isvisible() False >>> turtle.showturtle() >>> turtle.isvisible() True
Apparence¶
-
turtle.
shape
(name=None)¶ - Paramètres
name -- une chaîne de caractères qui correspond à un nom de forme valide
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.shape() 'classic' >>> turtle.shape("turtle") >>> turtle.shape() 'turtle'
-
turtle.
resizemode
(rmode=None)¶ - Paramètres
rmode -- l'une des chaînes suivantes : "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" : adapte l'apparence de la tortue en fonction de la largeur du pinceau (value of pensize en anglais).
"user" : adapte l'apparence de la tortue en fonction des valeurs du paramètre d'étirement et de la largeur des contours, déterminés par
shapesize()
."noresize" : il n'y a pas de modification de l'apparence de la tortue.
resizemode("user") is called by
shapesize()
when used with arguments.>>> turtle.resizemode() 'noresize' >>> turtle.resizemode("auto") >>> turtle.resizemode() 'auto'
-
turtle.
shapesize
(stretch_wid=None, stretch_len=None, outline=None)¶ -
turtle.
turtlesize
(stretch_wid=None, stretch_len=None, outline=None)¶ - Paramètres
stretch_wid -- nombre positif
stretch_len -- nombre positif
outline -- nombre positif
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.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.
shearfactor
(shear=None)¶ - Paramètres
shear -- un nombre (facultatif)
Définit ou renvoie le paramétrage de cisaillement actuel. Déforme la tortue en fonction du paramètre shear donné, qui est la tangente de l'angle de cisaillement. Ne change pas le sens de déplacement de la tortue. Si le paramètre shear n'est pas indiqué, renvoie la valeur actuelle du cisaillement, c.-à-d. la valeur de la tangente de l'angle de cisaillement, celui par rapport auquel les lignes parallèles à la direction de la tortue sont cisaillées.
>>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.shearfactor(0.5) >>> turtle.shearfactor() 0.5
-
turtle.
tilt
(angle)¶ - Paramètres
angle -- un nombre
Rotate the turtleshape by angle from its current tilt-angle, but do not change the turtle's heading (direction of movement).
>>> turtle.reset() >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.tilt(30) >>> turtle.fd(50) >>> turtle.tilt(30) >>> turtle.fd(50)
-
turtle.
settiltangle
(angle)¶ - Paramètres
angle -- un nombre
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.reset() >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.settiltangle(45) >>> turtle.fd(50) >>> turtle.settiltangle(-45) >>> turtle.fd(50)
Obsolète depuis la version 3.1.
-
turtle.
tiltangle
(angle=None)¶ - Paramètres
angle -- un nombre (facultatif)
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.reset() >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.tilt(45) >>> turtle.tiltangle() 45.0
-
turtle.
shapetransform
(t11=None, t12=None, t21=None, t22=None)¶ - Paramètres
t11 -- un nombre (facultatif)
t12 -- un nombre (facultatif)
t21 -- un nombre (facultatif)
t12 -- un nombre (facultatif)
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 = Turtle() >>> turtle.shape("square") >>> turtle.shapesize(4,2) >>> turtle.shearfactor(-0.5) >>> turtle.shapetransform() (4.0, -1.0, -0.0, 2.0)
-
turtle.
get_shapepoly
()¶ Return the current shape polygon as tuple of coordinate pairs. This can be used to define a new shape or components of a compound shape.
>>> turtle.shape("square") >>> turtle.shapetransform(4, -1, 0, 2) >>> turtle.get_shapepoly() ((50, -20), (30, 20), (-50, 20), (-30, -20))
Utilisation des événements¶
-
turtle.
onclick
(fun, btn=1, add=None)¶ - Paramètres
fun -- une fonction à deux arguments qui sera appelée avec les coordonnées du point cliqué sur le canevas
btn -- number of the mouse-button, defaults to 1 (left mouse button)
add --
True
orFalse
-- ifTrue
, a new binding will be added, otherwise it will replace a former binding
Bind fun to mouse-click events on this turtle. If fun is
None
, existing bindings are removed. Example for the anonymous turtle, i.e. the procedural way:>>> def turn(x, y): ... left(180) ... >>> onclick(turn) # Now clicking into the turtle will turn it. >>> onclick(None) # event-binding will be removed
-
turtle.
onrelease
(fun, btn=1, add=None)¶ - Paramètres
fun -- une fonction à deux arguments qui sera appelée avec les coordonnées du point cliqué sur le canevas
btn -- number of the mouse-button, defaults to 1 (left mouse button)
add --
True
orFalse
-- ifTrue
, a new binding will be added, otherwise it will replace a former binding
Bind fun to mouse-button-release events on this turtle. If fun is
None
, existing bindings are removed.>>> class MyTurtle(Turtle): ... def glow(self,x,y): ... self.fillcolor("red") ... def unglow(self,x,y): ... self.fillcolor("") ... >>> turtle = MyTurtle() >>> turtle.onclick(turtle.glow) # clicking on turtle turns fillcolor red, >>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
-
turtle.
ondrag
(fun, btn=1, add=None)¶ - Paramètres
fun -- une fonction à deux arguments qui sera appelée avec les coordonnées du point cliqué sur le canevas
btn -- number of the mouse-button, defaults to 1 (left mouse button)
add --
True
orFalse
-- ifTrue
, 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.
>>> turtle.ondrag(turtle.goto)
Subsequently, clicking and dragging the Turtle will move it across the screen thereby producing handdrawings (if pen is down).
Méthodes spéciales de la tortue¶
-
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
()¶ Renvoie le dernier polygone sauvegardé.
>>> 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)
-
turtle.
clone
()¶ Create and return a clone of the turtle with same position, heading and turtle properties.
>>> mick = Turtle() >>> joe = mick.clone()
-
turtle.
getturtle
()¶ -
turtle.
getpen
()¶ Return the Turtle object itself. Only reasonable use: as a function to return the "anonymous turtle":
>>> pet = getturtle() >>> pet.fd(50) >>> pet <turtle.Turtle object at 0x...>
-
turtle.
getscreen
()¶ Return the
TurtleScreen
object the turtle is drawing on. TurtleScreen methods can then be called for that object.>>> ts = turtle.getscreen() >>> ts <turtle._Screen object at 0x...> >>> ts.bgcolor("pink")
-
turtle.
setundobuffer
(size)¶ - Paramètres
size -- un entier ou
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 isNone
, the undobuffer is disabled.>>> turtle.setundobuffer(42)
-
turtle.
undobufferentries
()¶ Return number of entries in the undobuffer.
>>> while undobufferentries(): ... undo()
Formes composées¶
To use compound turtle shapes, which consist of several polygons of different
color, you must use the helper class Shape
explicitly as described
below:
Create an empty Shape object of type "compound".
Add as many components to this object as desired, using the
addcomponent()
method.Par exemple :
>>> 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")
Now add the Shape to the Screen's shapelist and use it:
>>> register_shape("myshape", s) >>> shape("myshape")
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!
Methods of TurtleScreen/Screen and corresponding functions¶
Most of the examples in this section refer to a TurtleScreen instance called
screen
.
Réglage de la fenêtre¶
-
turtle.
bgcolor
(*args)¶ - Paramètres
args -- a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers
Définit ou renvoie la couleur de fond de l'écran de la tortue (TurtleScreen en anglais).
>>> screen.bgcolor("orange") >>> screen.bgcolor() 'orange' >>> screen.bgcolor("#800080") >>> screen.bgcolor() (128.0, 0.0, 128.0)
-
turtle.
bgpic
(picname=None)¶ - Paramètres
picname -- une chaîne de caractères, le nom d'un fichier gif, ou
"nopic"
, ouNone
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 isNone
, return the filename of the current backgroundimage.>>> screen.bgpic() 'nopic' >>> screen.bgpic("landscape.gif") >>> screen.bgpic() "landscape.gif"
-
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 functionclear
is a different one derived from the Turtle methodclear
.
-
turtle.
reset
() -
turtle.
resetscreen
()¶ Remet toutes les tortues à l'écran dans leur état initial.
Note
This TurtleScreen method is available as a global function only under the name
resetscreen
. The global functionreset
is another one derived from the Turtle methodreset
.
-
turtle.
screensize
(canvwidth=None, canvheight=None, bg=None)¶ - Paramètres
canvwidth -- nombre entier positif, nouvelle largeur du canevas (zone sur laquelle se déplace la tortue), en pixels
canvheight -- nombre entier positif, nouvelle hauteur du canevas, en pixels
bg -- chaîne de caractères indiquant la couleur ou n-uplet de couleurs, nouvelle couleur de fond
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.
>>> screen.screensize() (400, 300) >>> screen.screensize(2000,1500) >>> screen.screensize() (2000, 1500)
par exemple, chercher une tortue échappée de manière erronée
-
turtle.
setworldcoordinates
(llx, lly, urx, ury)¶ - Paramètres
llx -- un nombre, coordonnée x du coin inférieur gauche du canevas
lly -- un nombre, la coordonnée y du coin inférieur gauche du canevas
urx -- un nombre, la coordonnée x du coin supérieur droit du canevas
ury -- un nombre, la coordonnée y du coin supérieur droit du canevas
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 : dans les systèmes de coordonnées définis par l'utilisateur, les angles peuvent apparaître déformés.
>>> 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
Réglage de l'animation¶
-
turtle.
delay
(delay=None)¶ - Paramètres
delay -- entier positif
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.
Argument facultatif :
>>> screen.delay() 10 >>> screen.delay(5) >>> screen.delay() 5
-
turtle.
tracer
(n=None, delay=None)¶ - Paramètres
n -- entier non-négatif
delay -- entier non-négatif
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.tracer(8, 25) >>> dist = 2 >>> for i in range(200): ... fd(dist) ... rt(90) ... dist += 2
-
turtle.
update
()¶ Effectue une mise à jour de TurtleScreen. À utiliser lorsque le traceur est désactivé.
Voir aussi la méthode speed()
de RawTurtle/Turtle.
Utilisation des événements concernant l'écran¶
-
turtle.
listen
(xdummy=None, ydummy=None)¶ Donne le focus à TurtleScreen (afin de collecter les événements clés). Des arguments factices sont fournis afin de pouvoir passer
listen()
à la méthode onclick.
-
turtle.
onkey
(fun, key)¶ -
turtle.
onkeyrelease
(fun, key)¶ - Paramètres
fun -- une fonction sans arguments ou
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 methodlisten()
.)>>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkey(f, "Up") >>> screen.listen()
-
turtle.
onkeypress
(fun, key=None)¶ - Paramètres
fun -- une fonction sans arguments ou
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()
.)>>> def f(): ... fd(50) ... >>> screen.onkey(f, "Up") >>> screen.listen()
-
turtle.
onclick
(fun, btn=1, add=None) -
turtle.
onscreenclick
(fun, btn=1, add=None)¶ - Paramètres
fun -- une fonction à deux arguments qui sera appelée avec les coordonnées du point cliqué sur le canevas
btn -- number of the mouse-button, defaults to 1 (left mouse button)
add --
True
orFalse
-- ifTrue
, a new binding will be added, otherwise it will replace a former binding
Bind fun to mouse-click events on this screen. If fun is
None
, existing bindings are removed.Example for a TurtleScreen instance named
screen
and a Turtle instance named turtle:>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will >>> # make the turtle move to the clicked point. >>> screen.onclick(None) # remove event binding again
Note
This TurtleScreen method is available as a global function only under the name
onscreenclick
. The global functiononclick
is another one derived from the Turtle methodonclick
.
-
turtle.
ontimer
(fun, t=0)¶ - Paramètres
fun -- une fonction sans arguments
t -- un nombre supérieur ou égal à 0
Install a timer that calls fun after t milliseconds.
>>> running = True >>> def f(): ... if running: ... fd(50) ... lt(60) ... screen.ontimer(f, 250) >>> f() ### makes the turtle march around >>> running = False
Méthodes de saisie¶
-
turtle.
textinput
(title, prompt)¶ - Paramètres
title -- string
prompt -- string
Pop up a dialog window for input of a string. Parameter title is the title of the dialog window, prompt is a text mostly describing what information to input. Return the string input. If the dialog is canceled, return
None
.>>> screen.textinput("NIM", "Name of first player:")
-
turtle.
numinput
(title, prompt, default=None, minval=None, maxval=None)¶ - Paramètres
title -- string
prompt -- string
default -- un nombre (facultatif)
minval -- un nombre (facultatif)
maxval -- un nombre (facultatif)
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 input, 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
.>>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
Paramétrages et méthodes spéciales¶
-
turtle.
mode
(mode=None)¶ - Paramètres
mode -- l'une des chaînes de caractères : "standard", "logo" ou "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 ifx/y
unit-ratio doesn't equal 1.Mode
Orientation initiale de la tortue
angles positifs
"standard"
vers la droite (vers l'Est)
dans le sens inverse des aiguilles d'une montre
"logo"
vers le haut (vers le Nord)
dans le sens des aiguilles d'une montre
>>> mode("logo") # resets turtle heading to north >>> mode() 'logo'
-
turtle.
colormode
(cmode=None)¶ - Paramètres
cmode -- l'une des valeurs suivantes : 1.0 ou 255
Return the colormode or set it to 1.0 or 255. Subsequently r, g, b values of color triples have to be in the range 0..cmode.
>>> screen.colormode(1) >>> 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)
-
turtle.
getcanvas
()¶ Return the Canvas of this TurtleScreen. Useful for insiders who know what to do with a Tkinter Canvas.
>>> cv = screen.getcanvas() >>> cv <turtle.ScrolledCanvas object ...>
-
turtle.
getshapes
()¶ Return a list of names of all currently available turtle shapes.
>>> screen.getshapes() ['arrow', 'blank', 'circle', ..., 'turtle']
-
turtle.
register_shape
(name, shape=None)¶ -
turtle.
addshape
(name, shape=None)¶ There are three different ways to call this function:
name is the name of a gif-file and shape is
None
: Install the corresponding image shape.>>> screen.register_shape("turtle.gif")
Note
Image shapes do not rotate when turning the turtle, so they do not display the heading of the turtle!
name is an arbitrary string and shape is a tuple of pairs of coordinates: Install the corresponding polygon shape.
>>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-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
()¶ Renvoie la liste des tortues présentes sur l'écran.
>>> for turtle in screen.turtles(): ... turtle.color("red")
-
turtle.
window_height
()¶ Return the height of the turtle window.
>>> screen.window_height() 480
-
turtle.
window_width
()¶ Return the width of the turtle window.
>>> screen.window_width() 640
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 toTrue
inturtle.cfg
. In this case IDLE's own mainloop is active also for the client script.
-
turtle.
setup
(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])¶ Définit la taille et la position de la fenêtre principale. Les valeurs par défaut des arguments sont stockées dans le dictionnaire de configuration et peuvent être modifiées via un fichier
turtle.cfg
.- Paramètres
width -- s'il s'agit d'un nombre entier, une taille en pixels, s'il s'agit d'un nombre flottant, une fraction de l'écran ; la valeur par défaut est de 50 % de l'écran
height -- s'il s'agit d'un nombre entier, la hauteur en pixels, s'il s'agit d'un nombre flottant, une fraction de l'écran ; la valeur par défaut est 75 % de l'écran
startx -- s'il s'agit d'un nombre positif, position de départ en pixels à partir du bord gauche de l'écran, s'il s'agit d'un nombre négatif, position de départ en pixels à partir du bord droit, si c'est
None
, centre la fenêtre horizontalementstarty -- if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if
None
, center window vertically
>>> 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
-
turtle.
title
(titlestring)¶ - Paramètres
titlestring -- chaîne de caractères affichée dans la barre de titre de la fenêtre graphique de la tortue
Set title of turtle window to titlestring.
>>> screen.title("Welcome to the turtle zoo!")
Classes publiques¶
-
class
turtle.
RawTurtle
(canvas)¶ -
class
turtle.
RawPen
(canvas)¶ - Paramètres
canvas -- un
tkinter.Canvas
, unScrolledCanvas
ou unTurtleScreen
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)¶ - Paramètres
cv -- un
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)¶ - Paramètres
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)¶ - Paramètres
type_ -- l'une des chaînes suivantes : "polygon", "image" ou "compound"
Formes de modélisation de la structure des données. La paire
(type_, data)
doit suivre cette spécification :type_
data
"polygon"
un polygone n-uplet, c'est-à-dire un n-uplet constitué de paires (chaque paire définissant des coordonnées)
"image"
une image (utilisée uniquement en interne sous ce format !)
"compound"
None
(une forme composée doit être construite en utilisant la méthodeaddcomponent()
)-
addcomponent
(poly, fill, outline=None)¶ - Paramètres
poly -- un polygone, c.-à-d. un n-uplet de paires de nombres
fill -- a color the poly will be filled with
outline -- une couleur pour le contour du polygone (si elle est donnée)
Exemple :
>>> 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()
Voir Formes composées.
-
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!
Provides (for a, b vectors, k number):
a + b
addition de vecteursa - b
soustraction de deux vecteursa * b
produit scalairek * a
eta * k
multiplication avec un scalaireabs(a)
valeur absolue de aa.rotate(angle)
rotation
Aide et configuration¶
Utilisation de l'aide¶
Les méthodes publiques des classes Screen et Turtle sont largement documentées dans les docstrings. Elles peuvent donc être utilisées comme aide en ligne via les fonctions d'aide de Python :
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()
The docstrings of the functions which are derived from methods have a modified form:
>>> help(bgcolor) Help on function bgcolor in module turtle: bgcolor(*args) Set or return backgroundcolor of the TurtleScreen. Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. Example:: >>> bgcolor("orange") >>> bgcolor() "orange" >>> bgcolor(0.5,0,0.5) >>> bgcolor() "#800080" >>> help(penup) Help on function penup in module turtle: penup() Pull the pen up -- no drawing when moving. Aliases: penup | pu | up No argument Example: >>> penup()
Ces chaînes de documents modifiées sont créées automatiquement avec les définitions de fonctions qui sont dérivées des méthodes au moment de l'importation.
Traduction de chaînes de documents en différentes langues¶
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")¶ - Paramètres
filename -- une chaîne de caractères, utilisée en tant que nom de fichier
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
. 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 glingl@aon.at.)
Comment configurer Screen et Turtle¶
The built-in default configuration mimics the appearance and behaviour of the old turtle module in order to retain best possible compatibility with it.
If you want to use a different configuration which better reflects the features
of this module or which better fits to your needs, e.g. for use in a classroom,
you can prepare a configuration file turtle.cfg
which will be read at import
time and modify the configuration according to its settings.
The built in configuration would correspond to the following turtle.cfg:
width = 0.5
height = 0.75
leftright = None
topbottom = None
canvwidth = 400
canvheight = 300
mode = standard
colormode = 1.0
delay = 10
undobuffersize = 1000
shape = classic
pencolor = black
fillcolor = black
resizemode = noresize
visible = True
language = english
exampleturtle = turtle
examplescreen = screen
title = Python Turtle Graphics
using_IDLE = False
Brève explication des entrées sélectionnées :
The first four lines correspond to the arguments of the
Screen.setup()
method.Les lignes 5 et 6 correspondent aux arguments de la méthode
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).Si vous voulez refléter l'état de la tortue, vous devez utiliser
resizemode = auto
.If you set e.g.
language = italian
the docstringdictturtle_docstringdict_italian.py
will be loaded at import time (if present on the import path, e.g. in the same directory asturtle
.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 preventexitonclick()
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).
turtledemo
— Scripts de démonstration¶
The turtledemo
package includes a set of demo scripts. These
scripts can be run and viewed using the supplied demo viewer as follows:
python -m turtledemo
Alternatively, you can run the demo scripts individually. For example,
python -m turtledemo.bytedesign
Le paquet turtledemo
contient :
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.
Les scripts de démonstration sont :
Nom |
Description |
Caractéristiques |
---|---|---|
bytedesign |
motif complexe de la tortue graphique classique |
|
chaos |
graphs Verhulst dynamics, shows that computer's computations can generate results sometimes against the common sense expectations |
world coordinates |
clock |
horloge analogique indiquant l'heure de votre ordinateur |
tortues sous forme des aiguilles d'horloge, sur minuterie |
colormixer (mélangeur de couleurs) |
des expériences en rouge, vert, bleu |
|
forest (forêt) |
3 breadth-first trees |
randomization (répartition aléatoire) |
fractalcurves |
Courbes de Hilbert et de Koch |
récursivité |
lindenmayer |
ethnomathématiques (kolams indiens) |
L-Système |
minimal_hanoi |
Tours de Hanoï |
Des tortues rectangulaires à la place des disques (shape, shapesize) |
nim |
play the classical nim game with three heaps of sticks against the computer. |
turtles as nimsticks, event driven (mouse, keyboard) |
paint (peinture) |
programme de dessin extra minimaliste |
|
peace (paix) |
basique |
tortue : apparence et animation |
penrose |
tuiles apériodiques avec cerfs-volants et fléchettes |
|
planet_and_moon (planète et lune) |
simulation d'un système gravitationnel |
formes composées, |
round_dance |
tortues dansantes tournant par paires en sens inverse |
compound shapes, clone shapesize, tilt, get_shapepoly, update |
sorting_animate |
démonstration visuelle des différentes méthodes de classement |
alignement simple, répartition aléatoire |
tree (arbre) |
a (graphical) breadth first tree (using generators) |
|
two_canvases (deux toiles) |
design simple |
tortues sur deux canevas |
wikipedia |
un motif issu de l'article de wikipedia sur la tortue graphique |
|
yinyang |
un autre exemple élémentaire |
|
Amusez-vous !
Modifications depuis Python 2.6¶
The methods
Turtle.tracer()
,Turtle.window_width()
andTurtle.window_height()
have been eliminated. Methods with these names and functionality are now available only as methods ofScreen
. The functions derived from these remain available. (In fact already in Python 2.6 these methods were merely duplications of the correspondingTurtleScreen
/Screen
-methods.)The method
Turtle.fill()
has been eliminated. The behaviour ofbegin_fill()
andend_fill()
have changed slightly: now every filling-process must be completed with anend_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 afill()
call without arguments in Python 2.6.
Modifications depuis Python 3.0¶
The methods
Turtle.shearfactor()
,Turtle.shapetransform()
andTurtle.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 toScreen.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 additionally importmainloop()
anymore.Two input methods has been added
Screen.textinput()
andScreen.numinput()
. These popup input dialogs and return strings and numbers respectively.Deux exemples de scripts
tdemo_nim.py
ettdemo_round_dance.py
ont été ajoutés au répertoireLib/turtledemo
.