turtle — Grafika żółwia¶
Kod źródłowy: Lib/turtle.py
Wyobraźmy sobie żółwia-robota rozpoczynającego ruch w punkcie (0, 0) na płaszczyźnie x-y. Po import turtle, wydaj polecenie turtle.forward(15), a przesunie się (na ekranie!) o 15 pikseli w kierunku, w którym jest zwrócony, rysując linię podczas ruchu. Wydaj polecenie turtle.right(25), a obróci się w miejscu o 25 stopni zgodnie z ruchem wskazówek zegara.
Grafika żółwia to implementacja narzędzi do rysowania wprowadzonych w języku Logo w 1967 roku. Została stworzona jako narzędzie edukacyjne, a dzięki natychmiastowej, widocznej informacji zwrotnej stanowi dla uczniów skuteczny sposób zapoznania się z koncepcjami programowania. Jest to również wygodny sposób na tworzenie prostych grafik bez konieczności korzystania z zewnętrznych bibliotek.
Niniejszy dokument składa się z czterech głównych części:
Tutorial uczy podstaw rysowania.
Dokumentacja opisuje funkcje, metody oraz klasy zdefiniowane przez ten moduł.
How-to guides szczegółowo opisuje, jak wykonać konkretne zadania.
Wytłumaczenie zawiera informacje na temat interfejsu obiektowego.
Informacja
Grafika żółwia wymaga opcjonalnego modułu tkinter. Instalatory python.org dla systemów Windows i macOS zawierają go, ale niektóre dystrybucje Linuksa i inne platformy mogą wymagać pobrania osobnego pakietu. Jeśli polecenie import turtle zakończy się niepowodzeniem z błędem wskazującym na _tkinter, należy zapoznać się z dokumentacją dostawcy (czyli podmiotu, który udostępnia Pythona). Sprawdź to z wyprzedzeniem, jeśli planujesz korzystać z grafiki żółwia z uczniem.
Tutorial¶
Nowi użytkownicy powinni zacząć tutaj. W tym tutorialu poznamy niektóre z podstaw rysowania żółwi.
Uruchamianie środowiska żółwia¶
W powłoce Pythona zaimportuj wszystkie obiekty z modułu turtle:
from turtle import *
Jeśli napotkasz błąd Standard library module '_tkinter' was not found, będziesz musiał zainstalować pakiet interfejsu Tk w swoim systemie.
Na razie nic się nie wyświetla. Aby otworzyć okno z żółwiem, wywołaj:
showturtle()
Otworzy się nowe okno, pośrodku którego znajduje się żółw przedstawiony jako strzałka skierowana na wschód.
Podstawowe rysowanie¶
Wyślij żółwia do przodu o 100 kroków:
forward(100)
Powinieneś zobaczyć linię narysowaną przez żółwia w kierunku wschodnim. Zmień kierunek żółwia, tak aby obrócił się o 120 stopni w lewo (przeciwnie do ruchu wskazówek zegara):
left(120)
Kontynuujmy, rysując trójkąt:
forward(100)
left(120)
forward(100)
Zwróć uwagę, jak żółw, reprezentowany przez strzałkę, kieruje się w różnych kierunkach.
Poeksperymentuj z tymi komendami, a także z backward() i right(). Wiele komend ma również krótsze aliasy, na przykład fd() dla forward().
Kontrola pióra¶
Spróbuj zmienić kolor – na przykład color('blue') – i szerokość linii – na przykład width(3) – a następnie narysuj ponownie.
Żółwia można także przesuwać bez rysowania, podnosząc pióro: up() przed wykonaniem ruchu. Aby ponownie rozpocząć rysowanie, użyj down().
Pozycja żółwia¶
Wyślij żółwia z powrotem do punktu początkowego (przydatne, jeśli zniknął poza ekranem):
home()
Pozycja wyjściowa znajduje się na środku ekranu żółwia. Jeśli kiedykolwiek będziesz chciał(a) je poznać, uzyskaj współrzędne x-y żółwia za pomocą:
pos()
Pozycja wyjściowa znajduje się pod (0, 0).
A po pewnym czasie prawdopodobnie przyda się wyczyścić okno, abyśmy mogli zacząć od nowa:
clearscreen()
Tworzenie wzorców algorytmicznych¶
Za pomocą pętli można tworzyć geometryczne wzory:
for steps in range(100):
for c in ('blue', 'red', 'green'):
color(c)
forward(steps)
right(30)
– które oczywiście ogranicza tylko wyobraźnia!
Narysujmy kształt gwiazdy z góry tej strony. Potrzebujemy czerwonych linii, wypełnionych kolorem żółtym:
color('red')
fillcolor('yellow')
Podobnie jak up() i down() określają, czy linie będą rysowane, wypełnianie można włączać i wyłączać:
begin_fill()
Następnie utworzymy pętlę:
start = pos()
while True:
forward(200)
left(170)
if distance(start) < 1:
break
distance(start) < 1 to dobry sposób, aby dowiedzieć się, kiedy żółw powróci do pozycji startowej.
Na koniec uzupełnij wypełnienie:
end_fill()
(Należy pamiętać, że wypełnianie odbywa się tylko po wydaniu polecenia end_fill().)
Dokumentacja¶
Metody i funkcje żółwia¶
Większość przykładów w tej sekcji odnosi się do instancji klasy Turtle o nazwie turtle.
Przesuwanie i rysowanie¶
- turtle.forward(distance)¶
- turtle.fd(distance)¶
- Parametry:
distance – liczba
Przesuwa żółwia do przodu o określony dystans, w kierunku, w którym żółw jest skierowany.
>>> 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)¶
- Parametry:
distance – liczba
Przesuwa żółwia do tyłu o dystans, w kierunku przeciwnym do kierunku, w którym żółw jest skierowany. Kierunek żółwia nie zmienia się.
>>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)
- turtle.right(angle)¶
- turtle.rt(angle)¶
- Parametry:
angle – liczba
Turn the turtle right by the specified angle. The angle is measured in degrees by default; the unit can be changed with
degrees()orradians(). How the heading is measured depends on the turtle mode, seemode().>>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.0
- turtle.left(angle)¶
- turtle.lt(angle)¶
- Parametry:
angle – liczba
Turn the turtle left by the specified angle. The angle is measured in degrees by default; the unit can be changed with
degrees()orradians(). How the heading is measured depends on the turtle mode, seemode().>>> 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)¶
- Parametry:
x – liczba lub para/wektor liczb
y – liczba lub
None
Move the turtle to an absolute position. If y is
None, x must be a pair of coordinates or aVec2D, for example as returned bypos(). If the pen is down, a line is drawn. The turtle’s heading does not change.>>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.goto(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.goto((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.goto(tp) >>> turtle.pos() (0.00,0.00)
- turtle.teleport(x=None, y=None, *, fill_gap=False)¶
- Parametry:
x – liczba lub
Noney – liczba lub
Nonefill_gap – wartość logiczna
Teleport, or instantly move, the turtle to an absolute position. Unlike
goto(), no line is drawn. If x or y is not given, that coordinate is kept as it is. The turtle’s heading does not change.If the turtle is filling a shape, the shape drawn so far is finished and filled before teleporting, and filling starts again at the new position. Pass
fill_gap=Trueto keep filling one shape instead. The teleport then counts as an edge of the shape, as it would withgoto().>>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.teleport(60) >>> turtle.pos() (60.00,0.00) >>> turtle.teleport(y=10) >>> turtle.pos() (60.00,10.00) >>> turtle.teleport(20, 30) >>> turtle.pos() (20.00,30.00)
Dodane w wersji 3.12.
- turtle.setx(x)¶
- Parametry:
x – liczba
Ustawia współrzędną x żółwia na x, pozostawiając współrzędną y bez zmian.
>>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)
- turtle.sety(y)¶
- Parametry:
y – liczba
Ustawia współrzędną y żółwia na y, pozostawiając współrzędną x bez zmian.
>>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)
- turtle.setheading(to_angle)¶
- turtle.seth(to_angle)¶
- Parametry:
to_angle – liczba
Set the turtle’s heading to to_angle. Here are some common directions in degrees:
tryb standardowy
tryb logo
0 – wschód
0 – północ
90 – północ
90 – wschód
180 – zachód
180 – południe
270 – południe
270 – zachód
>>> turtle.setheading(90) >>> turtle.heading() 90.0
- turtle.home()¶
Move the turtle to the origin, coordinates (0,0). The turtle’s heading is set to its start orientation, which depends on the turtle mode, see
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)¶
- Parametry:
radius – liczba
extent – liczba lub
Nonesteps – liczba całkowita lub
None
Draw a circle with the given radius. The center is radius units left of the turtle; extent, an angle, determines which part of the circle is drawn. If extent is not given, draw the entire circle. If extent is not a full circle, one endpoint of the arc is the current pen position. Draw the arc in counterclockwise direction if radius is positive, otherwise in clockwise direction. Finally, the turtle’s heading is changed by extent.
As the circle is approximated by an inscribed regular polygon, steps determines the number of steps to use. If not given, it will be calculated automatically. May be used to draw regular polygons.
>>> turtle.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) # narysuj półkole >>> turtle.position() (0.00,240.00) >>> turtle.heading() 180.0
- turtle.dot()¶
- turtle.dot(size)
- turtle.dot(color, /)
- turtle.dot(size, color, /)
- turtle.dot(size, r, g, b, /)
- Parametry:
size – a positive integer or
Nonecolor – colorstring lub numeryczna krotka koloru
Draw a circular dot with diameter size, using color. If size is not given, the larger of
pensize + 4and2 * pensizeis used. If color is not given, the current pencolor is used.>>> 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()¶
Stempluje kopię kształtu żółwia na płótnie w bieżącej pozycji żółwia. Zwraca stamp_id dla tego stempla, który może być użyty do usunięcia go przez wywołanie
clearstamp(stamp_id).>>> turtle.color("blue") >>> stamp_id = turtle.stamp() >>> turtle.fd(50)
- turtle.clearstamp(stampid)¶
- Parametry:
stampid – liczba całkowita, musi być wartością zwróconą przez wywołanie poprzedniego
stamp()
Usunięcie stempla z podanym 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)¶
- Parametry:
n – liczba całkowita (lub
None)
Usuwa wszystkie lub pierwsze/ostatnie n stempli żółwia. Jeśli n to
None, usuwa wszystkie stemple, jeśli n > 0 usuwa pierwsze n stempli, inaczej jeśli n < 0 usuwa ostatnie n stempli.>>> for i in range(8): ... unused_stamp_id = turtle.stamp() ... turtle.fd(30) >>> turtle.clearstamps(2) >>> turtle.clearstamps(-2) >>> turtle.clearstamps()
- turtle.undo()¶
Cofa (wielokrotnie) ostatnią akcję (akcje) żółwia. Liczba dostępnych cofnięć zależy od rozmiaru bufora cofania.
>>> for i in range(4): ... turtle.fd(50); turtle.lt(80) ... >>> for i in range(8): ... turtle.undo()
- turtle.speed(speed=None)¶
- Parametry:
speed – an integer, a string or
None
Return or set the turtle’s speed. If speed is not given, return the current speed. Otherwise set the turtle’s speed to an integer from 0 to 10. If speed is a number greater than 10 or smaller than 0.5, the speed is set to 0. You can also use these names instead of numbers:
„fastest”: 0
„fast”: 10
„normal”: 6
„slow”: 3
„slowest”: 1
Speeds from 1 to 10 give increasingly faster animation of line drawing and turtle turning. A speed of 0 means that no animation takes place:
forward()andback()make the turtle jump, and likewiseleft()andright()make the turtle turn instantly.>>> turtle.speed() 3 >>> turtle.speed('normal') >>> turtle.speed() 6 >>> turtle.speed(9) >>> turtle.speed() 9
Pobieranie stanu żółwia¶
- turtle.position()¶
- turtle.pos()¶
Return the turtle’s current location (x,y) as a
Vec2Dvector.>>> turtle.pos() (440.00,-0.00)
- turtle.towards(x, y=None)¶
- Parametry:
x – liczba lub para/wektor liczb lub instancja żółwia
y – liczba, jeśli x jest liczbą, w przeciwnym razie
None
Return the angle of the line from the turtle’s position to (x,y). If y is
None, x must be a pair of coordinates, aVec2D, for example as returned bypos(), or another turtle. The angle is measured from the turtle’s start orientation, which depends on the turtle mode, seemode().>>> turtle.goto(10, 10) >>> turtle.towards(0,0) 225.0
- turtle.xcor()¶
Zwraca współrzędną x żółwia.
>>> turtle.home() >>> turtle.left(50) >>> turtle.forward(100) >>> turtle.pos() (64.28,76.60) >>> print(round(turtle.xcor(), 5)) 64.27876
- turtle.ycor()¶
Zwraca współrzędną y żółwia.
>>> turtle.home() >>> turtle.left(60) >>> turtle.forward(100) >>> print(turtle.pos()) (50.00,86.60) >>> print(round(turtle.ycor(), 5)) 86.60254
- turtle.heading()¶
Return the turtle’s current heading. The value depends on the turtle mode, see
mode().>>> turtle.home() >>> turtle.left(67) >>> turtle.heading() 67.0
- turtle.distance(x, y=None)¶
- Parametry:
x – liczba lub para/wektor liczb lub instancja żółwia
y – liczba, jeśli x jest liczbą, w przeciwnym razie
None
Return the distance from the turtle to (x,y) in turtle step units. If y is
None, x must be a pair of coordinates, aVec2D, for example as returned bypos(), or another turtle.>>> turtle.home() >>> turtle.distance(30,40) 50.0 >>> turtle.distance((30,40)) 50.0 >>> joe = Turtle() >>> joe.forward(77) >>> turtle.distance(joe) 77.0
Ustawienia pomiarowe¶
- turtle.degrees(fullcircle=360.0)¶
- Parametry:
fullcircle – liczba
Set the angle measurement units to degrees. The number of degrees in a full circle is set to fullcircle, which defaults to 360.
>>> turtle.home() >>> turtle.left(90) >>> turtle.heading() 90.0 >>> # Zmień jednostkę miary kąta na grad (inaczej gon >>> # lub gradus; jest on równy 1/100 kąta prostego). >>> turtle.degrees(400.0) >>> turtle.heading() 100.0 >>> turtle.degrees(360) >>> turtle.heading() 90.0
- turtle.radians()¶
Set the angle measurement units to radians. Equivalent to
degrees(2 * math.pi).>>> turtle.home() >>> turtle.left(90) >>> turtle.heading() 90.0 >>> turtle.radians() >>> turtle.heading() 1.5707963267948966
Kontrola pióra¶
Stan rysowania¶
- turtle.pensize(width=None)¶
- turtle.width(width=None)¶
- Parametry:
width – a positive number or
None
Return or set the line thickness. If width is not given, return the current pensize. If resizemode is set to „auto” and the turtle shape is a polygon, that polygon is drawn with the same line thickness.
>>> turtle.pensize() 1 >>> turtle.pensize(10) # od tego momentu rysowane są linie o szerokości 10
- turtle.pen(pen=None, **pendict)¶
- Parametry:
pen – słownik z niektórymi lub wszystkimi z poniższych kluczy
pendict – jedno lub więcej argumentów nazwanych z poniższymi kluczami jako nazwami
Zwraca lub ustawia atrybuty pióra w „pióro-słowniku” z następującymi parami klucz/wartość:
„shown”: True/False
„pendown”: True/False
„pencolor”: nazwa koloru (color-string) lub kolor-krotka
„fillcolor”: nazwa koloru (color-string) lub kolor-krotka
„pensize”: liczba dodatnia
„speed”: liczba z przedziału 0..10
„resizemode”: „auto” lub „user” lub „noresize”
„stretchfactor”: (liczba dodatnia, liczba dodatnia)
„outline”: liczba dodatnia
„tilt”: liczba
Ten słownik może być użyty jako argument dla kolejnego wywołania
pen()w celu przywrócenia poprzedniego stanu pióra. Co więcej, jeden lub więcej z tych atrybutów może być przekazany jako argument nazwany. Można to wykorzystać do ustawienia kilku atrybutów pióra w jednej instrukcji.>>> 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()¶
Return
Trueif the pen is down,Falseif it’s up.>>> turtle.penup() >>> turtle.isdown() False >>> turtle.pendown() >>> turtle.isdown() True
Kontrola koloru¶
- turtle.pencolor()¶
- turtle.pencolor(color, /)
- turtle.pencolor(r, g, b, /)
Zwraca lub ustawia kolor pióra.
Dozwolone są cztery formaty wejściowe:
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()orbgcolor()call.pencolor(colorstring)Set the pencolor to colorstring, which is a Tk color specification string, such as
"red","yellow", or"#33cc8c".pencolor((r, g, b))Set the pencolor to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be between 0 and colormode, where colormode is either 1.0 or 255 (see
colormode()).pencolor(r, g, b)Set the pencolor to the RGB color represented by r, g, and b. Each of r, g, and b must be between 0 and colormode.
If the turtle shape is a polygon, the outline of that polygon is drawn with the newly set pencolor.
>>> 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()¶
- turtle.fillcolor(color, /)
- turtle.fillcolor(r, g, b, /)
Zwraca lub ustawia kolor wypełnienia.
Dozwolone są cztery formaty wejściowe:
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()orbgcolor()call.fillcolor(colorstring)Set the fillcolor to colorstring, which is a Tk color specification string, such as
"red","yellow", or"#33cc8c".fillcolor((r, g, b))Set the fillcolor to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be between 0 and colormode, where colormode is either 1.0 or 255 (see
colormode()).fillcolor(r, g, b)Set the fillcolor to the RGB color represented by r, g, and b. Each of r, g, and b must be between 0 and colormode.
If the turtle shape 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)) # całkowite, nie zmiennoprzecinkowe >>> turtle.fillcolor() (50.0, 193.0, 143.0) >>> turtle.fillcolor('#ffffff') >>> turtle.fillcolor() (255.0, 255.0, 255.0)
- turtle.color()¶
- turtle.color(color, /)
- turtle.color(r, g, b, /)
- turtle.color(pencolor, fillcolor, /)
Return or set the pencolor and fillcolor.
Several input formats are allowed. They use 0 to 3 arguments as follows:
color()Zwraca bieżący kolor pióra i bieżący kolor wypełnienia jako parę ciągów specyfikacji kolorów lub krotek zwracanych przez
pencolor()ifillcolor().color(colorstring),color((r,g,b)),color(r,g,b)Inputs as in
pencolor(). Set both the pencolor and the fillcolor to the given value.color(colorstring1, colorstring2),color((r1,g1,b1), (r2,g2,b2))Odpowiednik dla
pencolor(colorstring1)ifillcolor(colorstring2)oraz analogicznie, jeśli używany jest inny format wejścia.
If the turtle shape is a polygon, the outline and interior of that polygon are drawn with the newly set colors.
>>> turtle.color("red", "green") >>> turtle.color() ('red', 'green') >>> color("#285078", "#a0c8f0") >>> color() ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))
Zobacz także: Metoda klasy Screen colormode().
Wypełnienie¶
- turtle.filling()¶
Return
Trueif the turtle is filling,Falseotherwise.>>> turtle.begin_fill() >>> if turtle.filling(): ... turtle.pensize(5) ... else: ... turtle.pensize(3)
- turtle.fill()¶
Wypełnij kształt narysowany w bloku
with turtle.fill():.>>> turtle.color("black", "red") >>> with turtle.fill(): ... turtle.circle(80)
Użycie
fill()jest równoznaczne z dodaniembegin_fill()przed blokiem wypełnienia iend_fill()po bloku wypełnienia:>>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(80) >>> turtle.end_fill()
Dodane w wersji 3.14.
- turtle.begin_fill()¶
Do wywołania tuż przed rysowaniem kształtu do wypełnienia.
- turtle.end_fill()¶
Wypełnia kształt narysowany po ostatnim wywołaniu
begin_fill().To, czy obszary nakładania się przecinających się wielokątów lub wielu kształtów są wypełnione, zależy od grafiki systemu operacyjnego, typu nakładania się i liczby nakładających się obszarów. Na przykład żółwiowa gwiazda na górze rozdziału może być cała żółta lub mieć kilka białych obszarów.
>>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(80) >>> turtle.end_fill()
Więcej kontroli rysowania¶
- turtle.reset()¶
Delete the turtle’s drawings and re-center the turtle. The turtle’s settings are restored to their default values.
>>> 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()¶
Delete the turtle’s drawings from the screen. The state and position of the turtle as well as the drawings of other turtles are not affected.
- turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal'))¶
- Parametry:
arg – obiekt, który ma zostać zapisany na TurtleScreen
move – True/False
align – jedna z wartości „left”, „center” lub „right”
font – trójka wartości (fontname, fontsize, fonttype)
Pisze tekst – reprezentację obiektu arg – w bieżącej pozycji żółwia zgodnie z align („left”, „center” lub „right”) i z podaną czcionką. Jeśli move to
True, pióro jest przesuwane do prawego dolnego rogu tekstu. Domyślnie move ma wartośćFalse.>>> turtle.write("początek = ", True, align="center") >>> turtle.write((0,0), True)
Stan żółwia¶
Widoczność¶
- turtle.hideturtle()¶
- turtle.ht()¶
Make the turtle invisible. If the pen is down, movement still draws.
- turtle.isvisible()¶
Return
Trueif the turtle is visible,Falseif it’s hidden.>>> turtle.hideturtle() >>> turtle.isvisible() False >>> turtle.showturtle() >>> turtle.isvisible() True
Wygląd¶
- turtle.shape(name=None)¶
- Parametry:
name – a string or
None
Set the turtle shape to the named shape. If name is not given, return the name of the current shape. The shape must exist in the
TurtleScreen’s shape dictionary. Initially there are the following shapes: „arrow”, „turtle”, „circle”, „square”, „triangle” and „classic”. To add shapes, see theScreenmethodregister_shape().>>> turtle.shape() 'classic' >>> turtle.shape("turtle") >>> turtle.shape() 'turtle'
- turtle.resizemode(rmode=None)¶
- Parametry:
rmode – a string or
None
Set the resizemode to „auto”, „user” or „noresize”. If rmode is not given, return the current resizemode. The different resizemodes have the following effects:
„auto”: the turtle is resized according to the value of
pensize().„user”: the turtle is resized according to the stretch factors and outline width, which are set by
shapesize().„noresize”: the turtle is not resized.
resizemode("user")jest wywoływana przezshapesize(), gdy jest użyte z argumentami.>>> 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)¶
- Parametry:
stretch_wid – a positive number or
Nonestretch_len – a positive number or
Noneoutline – a positive number or
None
Return or set the turtle’s stretch factors and outline width. If no arguments are given, return the current values. Otherwise set resizemode to „user”, so that the turtle is displayed stretched according to its stretch factors:
stretch_wid: the stretch factor perpendicular to the turtle’s heading
stretch_len: the stretch factor in the direction of the turtle’s heading
outline: the width of the shape’s outline
For example,
shapesize(2, 1)makes the turtle twice as wide without changing its length. If only stretch_wid is given, stretch_len is set to the same value.>>> 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)¶
- Parametry:
shear – liczba (opcjonalna)
Ustawia lub zwraca bieżący współczynnik odchylenia. Odchyla kształt żółwia zgodnie z podanym współczynnikiem, który jest tangensem kąta odchylenia. Nie zmienia kursu żółwia (kierunku ruchu). Jeśli nie podano współczynnika: zwraca aktualny współczynnik odchylenia, tj. tangens kąta odchylenia, o który odchylają się linie równoległe do kierunku ruchu żółwia.
>>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.shearfactor(0.5) >>> turtle.shearfactor() 0.5
- turtle.tilt(angle)¶
- Parametry:
angle – liczba
Obraca żółwia o kąt w stosunku do jego aktualnego kąta nachylenia, ale nie zmienia jego kursu (kierunku ruchu).
>>> turtle.reset() >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.tilt(30) >>> turtle.fd(50) >>> turtle.tilt(30) >>> turtle.fd(50)
- turtle.tiltangle(angle=None)¶
- Parametry:
angle – liczba (opcjonalna)
Ustawia lub zwraca bieżący kąt nachylenia. Jeśli podano kąt, obraca żółwia tak, aby wskazywał kierunek określony przez kąt, niezależnie od jego aktualnego kąta nachylenia. Nie zmienia kierunku żółwia (kierunku ruchu). Jeśli nie podano kąta: zwraca aktualny kąt nachylenia, tj. kąt między orientacją kształtu żółwia a jego kursem (kierunkiem ruchu).
>>> 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)¶
- Parametry:
t11 – liczba (opcjonalna)
t12 – liczba (opcjonalna)
t21 – liczba (opcjonalna)
t12 – liczba (opcjonalna)
Ustawia lub zwraca bieżącą macierz transformacji kształtu żółwia.
Jeśli nie podano żadnego z elementów macierzy, zwraca macierz transformacji jako krotkę 4 elementów. W przeciwnym razie ustawia podane elementy i przekształca kształt żółwia zgodnie z macierzą składającą się z pierwszego wiersza t11, t12 i drugiego wiersza t21, t22. Wyznacznik t11 * t22 - t12 * t21 nie może być równy zero, w przeciwnym razie zostanie rzucony błąd. Modyfikuje stretchfactor, shearfactor i tiltangle zgodnie z podaną macierzą.
>>> 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()¶
Zwraca bieżący wielokąt kształtu jako krotkę par współrzędnych. Może to być wykorzystane do zdefiniowania nowego kształtu lub komponentów kształtu złożonego.
>>> turtle.shape("square") >>> turtle.shapetransform(4, -1, 0, 2) >>> turtle.get_shapepoly() ((50, -20), (30, 20), (-50, 20), (-30, -20))
Korzystanie ze zdarzeń¶
- turtle.onclick(fun, btn=1, add=None)
- Parametry:
fun – a function with two arguments or
Nonebtn – an integer
add – a boolean or
None
Bind fun to mouse-click events on this turtle. fun is called with the coordinates of the clicked point on the canvas. If fun is
None, existing bindings are removed. btn is the number of the mouse button and defaults to 1, the left mouse button. If add isTrue, a new binding is added, otherwise it replaces a former binding. Example for the anonymous turtle, that is, the procedural way:>>> def turn(x, y): ... left(180) ... >>> onclick(turn) # Teraz kliknięcie w żółwia spowoduje jego obrócenie. >>> onclick(None) # powiązanie zdarzenia zostanie usunięte
- turtle.onrelease(fun, btn=1, add=None)¶
- Parametry:
fun – funkcja z dwoma argumentami, która zostanie wywołana ze współrzędnymi klikniętego punktu na płótnie
btn – numer przycisku myszy, domyślnie 1 (lewy przycisk myszy)
add –
TruelubFalse– jeśliTrue, zostanie dodane nowe powiązanie, w przeciwnym razie zastąpi poprzednie powiązanie
Wiąże fun ze zdarzeniami zwolnienia przycisku myszy na tym żółwiu. Jeśli fun to
None, istniejące powiązania są usuwane.>>> class MyTurtle(Turtle): ... def glow(self,x,y): ... self.fillcolor("red") ... def unglow(self,x,y): ... self.fillcolor("") ... >>> turtle = MyTurtle() >>> turtle.onclick(turtle.glow) # kliknięcie na żółwia zmienia fillcolor na czerwony, >>> turtle.onrelease(turtle.unglow) # zwolnienie zmienia kolor na przezroczysty.
- turtle.ondrag(fun, btn=1, add=None)¶
- Parametry:
fun – funkcja z dwoma argumentami, która zostanie wywołana ze współrzędnymi klikniętego punktu na płótnie
btn – numer przycisku myszy, domyślnie 1 (lewy przycisk myszy)
add –
TruelubFalse– jeśliTrue, zostanie dodane nowe powiązanie, w przeciwnym razie zastąpi poprzednie powiązanie
Wiąże fun ze zdarzeniami ruchu myszy na tym żółwiu. Jeśli fun to
None, istniejące powiązania są usuwane.Uwaga: Każda sekwencja zdarzeń ruchu myszą na żółwiu jest poprzedzona zdarzeniem kliknięcia myszą na tym żółwiu.
>>> turtle.ondrag(turtle.goto)
Następnie kliknięcie i przeciągnięcie żółwia spowoduje przesunięcie go po ekranie, tworząc rysunki odręczne (jeśli pióro jest opuszczone).
Specjalne metody żółwi¶
- turtle.poly()¶
Zapisuje wierzchołki wielokąta narysowanego w bloku
with turtle.poly():. Pierwszy i ostatni wierzchołek będą połączone.>>> with turtle.poly(): ... turtle.forward(100) ... turtle.right(60) ... turtle.forward(100)
Dodane w wersji 3.14.
- turtle.begin_poly()¶
Start recording the vertices of a polygon. The current turtle position is the first vertex of the polygon.
- turtle.end_poly()¶
Stop recording the vertices of a polygon. The current turtle position is the last vertex of the polygon. This will be connected with the first vertex.
- turtle.get_poly()¶
Zwraca ostatni zarejestrowany wielokąt.
>>> 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("mójUlubionyKształt", p)
- turtle.clone()¶
Create and return a clone of the turtle. The clone has the same position, heading and turtle properties.
>>> leonel = Turtle() >>> marco = leonel.clone()
- turtle.getturtle()¶
- turtle.getpen()¶
Return the Turtle object itself.
Call
getturtle()to get the turtle used by functions such asforward()andleft():>>> pet = getturtle() >>> pet.fd(50) >>> pet <turtle.Turtle object at 0x...>
- turtle.getscreen()¶
Zwraca obiekt
TurtleScreen, na którym żółw rysuje. Następnie można wywoływać metody TurtleScreen na tym obiekcie.>>> ts = turtle.getscreen() >>> ts <turtle._Screen object at 0x...> >>> ts.bgcolor("pink")
- turtle.setundobuffer(size)¶
- Parametry:
size – liczba całkowita lub
None
Set or disable the undo buffer. If size is an integer, an empty undo buffer of the given size is installed. size is the maximum number of turtle actions that can be undone by
undo(). If size isNone, the undo buffer is disabled.>>> turtle.setundobuffer(42)
- turtle.undobufferentries()¶
Return the number of entries in the undo buffer.
>>> while undobufferentries(): ... undo()
Screen methods and functions¶
Większość przykładów w tej sekcji odnosi się do instancji TurtleScreen o nazwie screen.
Kontrola okna¶
- turtle.bgcolor()¶
- turtle.bgcolor(color, /)
- turtle.bgcolor(r, g, b, /)
Zwraca lub ustawia kolor tła TurtleScreen.
Dozwolone są cztery formaty wejściowe:
bgcolor()Return the current background color as a color specification string or as a tuple (see example). May be used as input to another
color(),pencolor(),fillcolor()orbgcolor()call.bgcolor(colorstring)Ustawia kolor tła na colorstring – jest to specyfikacja koloru w formacie napisu Tk, na przykład
"red","yellow"lub"#33cc8c".bgcolor((r, g, b))Set the background color to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be between 0 and colormode, where colormode is either 1.0 or 255 (see
colormode()).bgcolor(r, g, b)Set the background color to the RGB color represented by r, g, and b. Each of r, g, and b must be between 0 and colormode.
>>> screen.bgcolor("orange") >>> screen.bgcolor() 'orange' >>> screen.bgcolor("#800080") >>> screen.bgcolor() (128.0, 0.0, 128.0)
- turtle.bgpic(picname=None)¶
- Parametry:
picname – ciąg znaków, nazwa pliku graficznego (PNG, GIF, PGM i PPM) lub
"nopic", alboNone
Ustawia obraz tła lub zwraca nazwę bieżącego obrazu tła. Jeśli picname jest nazwą pliku, ustawia odpowiedni obraz jako tło. Jeśli picname to
"nopic", usuwa obraz tła, o ile istnieje. Jeśli picname toNone, zwraca nazwę pliku bieżącego obrazu tła.>>> screen.bgpic() 'nopic' >>> screen.bgpic("landscape.gif") >>> screen.bgpic() "landscape.gif"
- turtle.clear()
Informacja
Ta metoda klasy TurtleScreen jest dostępna jako globalna funkcja wyłącznie pod nazwą
clearscreen. Globalna funkcjaclearjest inną funkcją, wywodzącą się z metodyclearklasy Turtle.
- turtle.clearscreen()¶
Usuwa wszystkie rysunki i wszystkie żółwie z ekranu TurtleScreen. Przywraca pusty ekran TurtleScreen do stanu początkowego: białe tło, brak obrazu tła, brak powiązań ze zdarzeniami oraz włączone automatyczne odświeżanie ekranu.
- turtle.reset()
Informacja
Ta metoda klasy TurtleScreen jest dostępna jako globalna funkcja wyłącznie pod nazwą
resetscreen. Globalna funkcjaresetjest inną funkcją, wywodzącą się z metodyresetklasy Turtle.
- turtle.resetscreen()¶
Reset all turtles on the screen to their initial state.
- turtle.screensize(canvwidth=None, canvheight=None, bg=None)¶
- Parametry:
canvwidth – dodatnia liczba całkowita, nowa szerokość płótna w pikselach
canvheight – dodatnia liczba całkowita, nowa wysokość płótna w pikselach
bg – colorstring lub color-krotka, nowy kolor tła
Jeśli nie podano argumentów, zwraca aktualne (szerokość płótna, wysokość płótna). W przeciwnym razie zmienia rozmiar płótna, na którym rysują żółwie. Nie zmienia okna rysowania. Aby obejrzeć ukryte części obszaru rysowania, należy użyć pasków przewijania. Za pomocą tej metody można uwidocznić te części rysunku, które wcześniej znajdowały się poza obszarem płótna.
>>> screen.screensize() (400, 300) >>> screen.screensize(2000,1500) >>> screen.screensize() (2000, 1500)
np. aby poszukać żółwia, który przypadkiem uciekł ;-)
- turtle.setworldcoordinates(llx, lly, urx, ury)¶
- Parametry:
llx – liczba
lly – liczba
urx – liczba
ury – liczba
Set up a user-defined coordinate system. llx and lly are the x and y coordinates of the lower left corner of the canvas. urx and ury are the x and y coordinates of the upper right corner. Switch to mode „world” if necessary, which performs a reset. If mode „world” is already active, all drawings are redrawn according to the new coordinates. In user-defined coordinate systems, angles may appear distorted, see
mode().>>> screen.reset() >>> screen.setworldcoordinates(-50,-7.5,50,7.5) >>> for _ in range(72): ... left(10) ... >>> for _ in range(8): ... left(45); fd(2) # ośmiokąt foremny
Kontrola animacji¶
- turtle.no_animation()¶
Temporarily turn off turtle animation. The code inside the
withblock is not animated. Once the block is exited, the drawing appears. This is useful for drawing complex shapes where even the fastest speed setting is too slow.>>> with screen.no_animation(): ... for dist in range(2, 400, 2): ... fd(dist) ... rt(90)
Dodane w wersji 3.14.
- turtle.delay(delay=None)¶
- Parametry:
delay – a nonnegative integer or
None
Return or set 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.
>>> screen.delay() 10 >>> screen.delay(5) >>> screen.delay() 5
- turtle.tracer(n=None, delay=None)¶
- Parametry:
n – a nonnegative integer or
Nonedelay – a nonnegative integer or
None
Turn turtle animation on or off and set the drawing delay. If n is given, only every n-th regular screen update is performed, which can be used to speed up the drawing of complex graphics. If n is 0, animation is turned off and the screen is only updated by calling
update(). If delay is given, it sets the drawing delay, seedelay(). When called without arguments, return the current value of n.>>> screen.tracer(8, 25) >>> dist = 2 >>> for i in range(200): ... fd(dist) ... rt(90) ... dist += 2
- turtle.update()¶
Wykonuje aktualizację ekranu TurtleScreen. Do użycia, gdy automatyczne odświeżanie ekranu (tracer) jest wyłączone.
Zobacz również metodę speed() klasy RawTurtle/Turtle.
Korzystanie ze zdarzeń ekranowych¶
- turtle.listen(xdummy=None, ydummy=None)¶
Ustawia fokus na TurtleScreen, aby umożliwić odbieranie zdarzeń klawiatury. Funkcja przyjmuje dodatkowe, nieużywane argumenty, dzięki czemu funkcję
listen()można przekazać do metody onclick.
- turtle.onkey(fun, key)¶
- turtle.onkeyrelease(fun, key)¶
- Parametry:
fun – funkcja bez argumentów lub
Nonekey – ciąg znaków: klawisz (np. „a”) lub symbol klawisza (np. „space”)
Wiąże funkcję fun ze zdarzeniem zwolnienia klawisza. Jeśli fun ma wartość
None, metoda usuwa istniejące powiązania zdarzeń. Uwaga: aby można było rejestrować zdarzenia klawiatury, TurtleScreen musi mieć fokus. (Zobacz metodęlisten().)>>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkey(f, "Up") >>> screen.listen()
- turtle.onkeypress(fun, key=None)¶
- Parametry:
fun – funkcja bez argumentów lub
Nonekey – ciąg znaków: klawisz (np. „a”) lub symbol klawisza (np. „space”)
Wiąże funkcję fun ze zdarzeniem naciśnięcia podanego klawisza albo ze zdarzeniem naciśnięcia dowolnego klawisza, jeśli klawisz nie został podany. Uwaga: aby można było rejestrować zdarzenia klawiatury, TurtleScreen musi mieć fokus. (Zobacz metodę
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)¶
- Parametry:
fun – a function with two arguments or
Nonebtn – an integer
add – a boolean or
None
Bind fun to mouse-click events on this screen. fun is called with the coordinates of the clicked point on the canvas. If fun is
None, existing bindings are removed. btn is the number of the mouse button and defaults to 1, the left mouse button. If add isTrue, a new binding is added, otherwise it replaces a former binding.Przykład dla obiektu TurtleScreen przypisanego do zmiennej
screenoraz obiektu Turtle przypisanego do zmiennejturtle:>>> screen.onclick(turtle.goto) # Od tej chwili kliknięcie na ekranie TurtleScreen >>> # przesunie żółwia do klikniętego punktu. >>> screen.onclick(None) # ponownie usuń powiązanie zdarzenia
Informacja
Ta metoda TurtleScreen jest dostępna jako globalna funkcja wyłącznie pod nazwą
onscreenclick. Globalna funkcjaonclickjest inną funkcją, wywodzącą się z metodyonclickklasy Turtle.
- turtle.ontimer(fun, t=0)¶
- Parametry:
fun – funkcja bez argumentów
t – liczba >= 0
Ustaw czasomierz, który wywoła funkcję fun po upływie t milisekund.
>>> running = True >>> def f(): ... if running: ... fd(50) ... lt(60) ... screen.ontimer(f, 250) >>> f() ### wprawia żółwia w ruch po okręgu >>> running = False
- turtle.mainloop()¶
- turtle.done()¶
Start the event loop by calling Tkinter’s
mainloop()method. Must be the last statement in a turtle graphics program. Must not be used if a script is run from within IDLE in -n mode (see Running without a subprocess).
Metody wprowadzania danych¶
- turtle.textinput(title, prompt)¶
- Parametry:
title – a string
prompt – a string
Pop up a dialog window for input of a string. title is the title of the dialog window and prompt is a text describing what information to input. Return the string entered. If the dialog is canceled, return
None.>>> screen.textinput("NIM", "Imię pierwszego gracza:")
- turtle.numinput(title, prompt, default=None, minval=None, maxval=None)¶
- Parametry:
title – a string
prompt – a string
default – liczba lub
Noneminval – liczba lub
Nonemaxval – liczba lub
None
Pop up a dialog window for input of a number. title is the title of the dialog window and prompt is a text describing what numerical information to input. default is the default value, minval and maxval are the minimum and maximum values for input. If these are given, the number entered must be between minval and maxval. If not, a hint is issued and the dialog remains open for correction. Return the number entered. If the dialog is canceled, return
None.>>> screen.numinput("Poker", "Twoje stawki:", 1000, minval=10, maxval=10000)
Ustawienia i metody specjalne¶
- turtle.mode(mode=None)¶
- Parametry:
mode – a string or
None
Set the turtle mode and perform a reset. mode is one of the strings „standard”, „logo” or „world”. If mode is not given, return the current mode.
Mode „standard” is compatible with the old
turtlemodule. Mode „logo” is compatible with most Logo turtle graphics. Mode „world” uses user-defined world coordinates, seesetworldcoordinates(). In this mode, angles appear distorted if the x and y units are not of equal length.tryb
początkowy kierunek żółwia
kąty dodatnie
„standard”
w prawo (na wschód)
przeciwnie do ruchu wskazówek zegara
„logo”
w górę (na północ)
zgodnie z ruchem wskazówek zegara
>>> mode("logo") # resets turtle heading to north >>> mode() 'logo'
- turtle.colormode(cmode=None)¶
- Parametry:
cmode – liczba lub
None
Return the colormode or set it to 1.0 or 255. After setting it, the r, g and b values of color triples have to be between 0 and 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)¶
- Parametry:
name – a string
shape – a string, a tuple of pairs of numbers, a
Shapeobject orNone
Add a turtle shape to the TurtleScreen’s shape list. It can be called in four different ways:
name is the name of an image file (PNG, GIF, PGM, and PPM) and shape is
None: Install the corresponding image shape.>>> screen.register_shape("turtle.gif")
name is an arbitrary string and shape is the name of an image file (PNG, GIF, PGM, and PPM): Install the corresponding image shape.
>>> screen.register_shape("turtle", "turtle.gif")
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)
Shapeobject: Install the corresponding compound shape.
Image shapes do not rotate when turning the turtle, so they do not display the heading of the turtle. To use a registered shape, call
shape()with its name.Zmienione w wersji 3.14: Added support for PNG, PGM, and PPM image formats. Both a shape name and an image file name can be specified.
- turtle.turtles()¶
Return the list of turtles on the screen.
>>> 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
Screen-only methods¶
- turtle.bye()¶
Close the turtle graphics 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-nswitch (no subprocess) is used, this value should be set toTrueinturtle.cfg. In this case IDLE’s own mainloop is active also for the client script.
- turtle.save(filename, overwrite=False)¶
Save the current turtle drawing (and turtles) as a PostScript file.
- Parametry:
filename – the path of the saved PostScript file
overwrite – if
Falseand there already exists a file with the given filename, then the function will raise aFileExistsError. If it isTrue, the file will be overwritten.
>>> screen.save("my_drawing.ps") >>> screen.save("my_drawing.ps", overwrite=True)
Dodane w wersji 3.14.
- turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom'])¶
Set the size and position of the main window. Default values of arguments are stored in the configuration dictionary and can be changed via a
turtle.cfgfile.- Parametry:
width – if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen
height – if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen
startx – if positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if
None, center window horizontallystarty – 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)¶
- Parametry:
titlestring – a string
Set the title of the turtle window to titlestring. The title is shown in the title bar of the turtle graphics window.
>>> screen.title("Welcome to the turtle zoo!")
Public classes¶
- class turtle.RawTurtle(canvas)¶
- class turtle.RawPen(canvas)¶
- Parametry:
canvas – a
tkinter.Canvas, aScrolledCanvasor aTurtleScreen
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
Screenobject created automatically when needed for the first time.
- class turtle.TurtleScreen(cv)¶
- Parametry:
cv – a
tkinter.Canvas
Provides screen oriented methods like
bgcolor()etc. that are described above.
- class turtle.Screen¶
Subclass of
TurtleScreen, with four methods added. CallingScreen()returns the single screen object. If it does not exist yet, it is created. Otherwise the existing one is returned.
- class turtle.ScrolledCanvas(master)¶
- Parametry:
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)¶
- Parametry:
type_ – a string
data – depends on type_
Data structure modeling shapes. type_ is one of the strings „polygon”, „image” or „compound”. What data must be depends on type_: for „polygon” a tuple of pairs of coordinates, for „image” an image (only used internally), and for „compound”
None, as a compound shape is built up using theaddcomponent()method.- addcomponent(poly, fill, outline=None)¶
- Parametry:
poly – a tuple of pairs of numbers
fill – a color
outline – a color or
None
Add a component to a shape of type „compound”. poly is a polygon, a tuple of pairs of numbers. fill is the color the polygon is filled with and outline is the color of its outline. If outline is not given, fill is used for it as well.
Przykład:
>>> 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()
- 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 + bvector additiona - bvector subtractiona * binner productk * aanda * kmultiplication with scalarabs(a)absolute value of aa.rotate(angle)rotation
Wyjątki¶
The turtle module defines the following exception:
- exception turtle.TurtleGraphicsError¶
Raised for invalid arguments or operations. For example, a malformed color string:
>>> turtle.color("blau") Traceback (most recent call last): ... turtle.TurtleGraphicsError: bad color string: blau
How-to guides¶
Ta sekcja omawia niektóre typowe przypadki użycia i koncepcje.
How to automatically begin and end filling¶
Począwszy od Pythona 3.14, można użyć menedżera kontekstu fill() zamiast begin_fill() i end_fill(), aby automatycznie rozpocząć i zakończyć wypełnianie. Oto przykład:
with fill():
for i in range(4):
forward(100)
right(90)
forward(200)
Powyższy kod jest równoważny poniższemu:
begin_fill()
for i in range(4):
forward(100)
right(90)
end_fill()
forward(200)
How to use compound shapes¶
Aby korzystać ze złożonych kształtów żółwia, składających się z kilku wielokątów o różnych kolorach, należy jawnie użyć klasy pomocniczej Shape, zgodnie z poniższym opisem:
Create an empty
Shapeobject of type „compound”.Dodaj do tego obiektu dowolną liczbę komponentów, korzystając z metody
addcomponent().Na przykład:
>>> 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")
Teraz dodaj obiekt Shape do listy kształtów obiektu Screen i użyj go:
>>> register_shape("myshape", s) >>> shape("myshape")
How to use the turtle module namespace¶
Korzystanie z from turtle import * jest wygodne – ale należy pamiętać, że importuje dość dużą kolekcję obiektów, a jeśli robisz cokolwiek innego niż grafika żółwia, ryzykujesz konflikt nazw (staje się to jeszcze większym problemem, jeśli używasz grafiki żółwia w skrypcie, w którym mogą być importowane inne moduły).
Rozwiązaniem jest użycie import turtle – fd() staje się turtle.fd(), width() staje się turtle.width() i tak dalej. (Jeśli wpisywanie „turtle” w kółko staje się uciążliwe, użyj na przykład import turtle as t.)
How to use turtle graphics in a script¶
Zaleca się korzystanie z przestrzeni nazw modułu turtle, jak opisano bezpośrednio powyżej, na przykład:
import turtle as t
from random import random
for i in range(100):
steps = int(random() * 100)
angle = int(random() * 360)
t.right(angle)
t.fd(steps)
Wymagany jest jednak jeszcze jeden krok – gdy tylko skrypt się zakończy, Python zamknie również okno żółwia. Dodaj:
t.mainloop()
na końcu skryptu. Skrypt będzie teraz czekał na zwolnienie i nie wyjdzie, dopóki nie zostanie zakończony, na przykład przez zamknięcie okna graficznego żółwia.
How to use object-oriented turtle graphics¶
Zobacz także
Poza bardzo podstawowymi celami wprowadzającymi lub do wypróbowania rzeczy tak szybko, jak to możliwe, bardziej typowe i znacznie bardziej wydajne jest użycie podejścia obiektowego do grafiki żółwia. Pozwala to na przykład na jednoczesne wyświetlanie wielu żółwi na ekranie.
W tym podejściu różne komendy żółwia są metodami obiektów (głównie obiektów Turtle). Można używać podejścia obiektowego w powłoce, ale byłoby to bardziej typowe w pythonowym skrypcie.
Przykład powyżej staje się wtedy:
from turtle import Turtle
from random import random
t = Turtle()
for i in range(100):
steps = int(random() * 100)
angle = int(random() * 360)
t.right(angle)
t.fd(steps)
t.screen.mainloop()
Zwróć uwagę na ostatnią linię. t.screen to instancja Screen, na której istnieje instancja Turtle; jest ona tworzona automatycznie wraz z żółwiem.
Ekran żółwia można dostosować, na przykład:
t.screen.title('Demo żółwia zorientowanego obiektowo')
t.screen.bgcolor("orange")
How to use help()¶
The public methods of the Screen and Turtle classes are documented extensively via docstrings. So these can be used as online-help via the Python help facilities:
When using IDLE, tooltips show the signatures and first lines of the docstrings of typed in function-/method calls.
Calling
help()on methods or functions displays the docstrings:>>> help(Screen.bgcolor) Help on method bgcolor in module turtle: bgcolor(self, *args) unbound turtle.Screen method Set or return backgroundcolor of the TurtleScreen. Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. >>> screen.bgcolor("orange") >>> screen.bgcolor() "orange" >>> screen.bgcolor(0.5,0,0.5) >>> screen.bgcolor() "#800080" >>> help(Turtle.penup) Help on method penup in module turtle: penup(self) unbound turtle.Turtle method Pull the pen up -- no drawing when moving. Aliases: penup | pu | up No argument >>> turtle.penup()
The docstrings of the functions which are derived from methods have a modified form:
>>> help(bgcolor) Help on function bgcolor in module turtle: bgcolor(*args) Set or return backgroundcolor of the TurtleScreen. Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. Example:: >>> bgcolor("orange") >>> bgcolor() "orange" >>> bgcolor(0.5,0,0.5) >>> bgcolor() "#800080" >>> help(penup) Help on function penup in module turtle: penup() Pull the pen up -- no drawing when moving. Aliases: penup | pu | up No argument Example: >>> penup()
These modified docstrings are created automatically together with the function definitions that are derived from the methods at import time.
Translation of docstrings into different languages¶
The docstrings of the public methods of the Screen and Turtle classes, and of
the corresponding functions, can be replaced with translations, so that
help() and IDE tooltips are shown in another language. However, only the help
text is translated, the names of the functions and methods stay the same.
Translations are distributed on PyPI in the turtle-translations
package. To use them, install the package with pip and select the
language with the PYTHON_TURTLE_LANG environment variable. For
example, to show the help text in Spanish:
$ python -m pip install turtle-translations
$ PYTHON_TURTLE_LANG=es python
>>> import turtle
>>> help(turtle.forward)
The language can also be set permanently with the language entry of the
turtle.cfg file (see How to configure Screen and Turtles). If no translation
is found for the selected language, the English docstrings are kept.
To add a new language or improve an existing translation, see the contribution instructions in the turtle-translations project.
A translation is a docstring dictionary. It is a top-level module named
turtle_docstringdict_language.py on sys.path defining a
dictionary named docsdict, the keys of which are method names such as
Turtle.forward and the values of which are the translated docstrings. It is
read in at import time. Entries naming a method which does not exist in the
running version are ignored.
Zmienione w wersji 3.16: Entries naming an unknown method are ignored instead of reported.
- PYTHON_TURTLE_LANG¶
The name of the language to read the translation for. It takes precedence over the language entry of the
turtle.cfgfile.Dodane w wersji 3.16.
- turtle.write_docstringdict(filename='turtle_docstringdict')¶
- Parametry:
filename – a string, used as filename
Create and write docstring-dictionary to a Python script with the given filename. This function has to be called explicitly (it is not used by the turtle graphics classes). The docstring dictionary will be written to the Python script
filename.py. It is intended to serve as a template for translation of the docstrings into different languages.
How to configure Screen and Turtles¶
The built-in default configuration mimics the appearance and behaviour of the old turtle module in order to retain best possible compatibility with it.
If you want to use a different configuration which better reflects the features
of this module or which better fits to your needs, e.g. for use in a classroom,
you can prepare a configuration file turtle.cfg which will be read at import
time and modify the configuration according to its settings.
The built in configuration would correspond to the following turtle.cfg:
width = 0.5
height = 0.75
leftright = None
topbottom = None
canvwidth = 400
canvheight = 300
mode = standard
colormode = 1.0
delay = 10
undobuffersize = 1000
shape = classic
pencolor = black
fillcolor = black
resizemode = noresize
visible = True
language = english
exampleturtle = turtle
examplescreen = screen
title = Python Turtle Graphics
using_IDLE = False
Short explanation of selected entries:
The first four lines correspond to the arguments of the
Screen.setupmethod.Line 5 and 6 correspond to the arguments of the method
Screen.screensize.shape can be any of the built-in shapes, e.g: arrow, turtle, etc. For more info try
help(shape).If you want to use no fill color (i.e. make the turtle transparent), you have to write
fillcolor = ""(but all nonempty strings must not have quotes in the cfg file).If you want to reflect the turtle its state, you have to use
resizemode = auto.The language entry selects the language of the docstrings, unless the
PYTHON_TURTLE_LANGenvironment variable is set. See Translation of docstrings into different languages for more information.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
Trueif you regularly work with IDLE and its-nswitch („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).
Wytłumaczenie¶
A turtle object draws on a screen object, and there a number of key classes in the turtle object-oriented interface that can be used to create them and relate them to each other.
A Turtle instance will automatically create a Screen
instance if one is not already present.
Turtle is a subclass of RawTurtle, which doesn’t automatically
create a drawing surface - a canvas will need to be provided or created for
it. The canvas can be a tkinter.Canvas, ScrolledCanvas
or TurtleScreen.
TurtleScreen is the basic drawing surface for a
turtle. Screen is a subclass of TurtleScreen, and
includes some additional methods for managing its
appearance (including size and title) and behaviour. TurtleScreen’s
constructor needs a tkinter.Canvas or a
ScrolledCanvas as an argument.
The functional interface for turtle graphics uses the various methods of
Turtle and TurtleScreen/Screen. Behind the scenes, a screen
object is automatically created whenever a function derived from a Screen
method is called. Similarly, a turtle object is automatically created
whenever any of the functions derived from a Turtle method is called.
To use multiple turtles on a screen, the object-oriented interface must be used.
turtledemo — Demo scripts¶
The turtledemo package includes a set of demo scripts. These
scripts can be run and viewed using the supplied demo viewer as follows:
python -m turtledemo
Alternatively, you can run the demo scripts individually. For example,
python -m turtledemo.bytedesign
The turtledemo package directory contains:
A demo viewer
__main__.pywhich can be used to view the sourcecode of the scripts and run them at the same time.Multiple scripts demonstrating different features of the
turtlemodule. Examples can be accessed via the Examples menu. They can also be run standalone.A
turtle.cfgfile which serves as an example of how to write and use such files.
The demo scripts are:
Nazwa |
Opis |
Features |
|---|---|---|
|
complex classical turtle graphics pattern |
|
|
graphs Verhulst dynamics, shows that computer’s computations can generate results sometimes against the common sense expectations |
world coordinates |
|
analog clock showing time of your computer |
turtles as clock’s
hands, |
|
experiment with r, g, b |
|
|
3 breadth-first trees |
randomization |
|
Hilbert & Koch curves |
recursion |
|
ethnomathematics (indian kolams) |
L-System |
|
Towers of Hanoi |
Rectangular Turtles
as Hanoi discs
( |
|
play the classical nim game with three heaps of sticks against the computer. |
turtles as nimsticks, event driven (mouse, keyboard) |
|
super minimalistic drawing program |
|
|
elementary |
turtle: appearance and animation |
|
aperiodic tiling with kites and darts |
|
|
simulation of gravitational system |
compound shapes,
|
|
a pattern from the wikipedia article on turtle graphics |
|
|
dancing turtles rotating pairwise in opposite direction |
compound shapes, |
|
visual demonstration of different sorting methods |
simple alignment, randomization |
|
a (graphical) breadth first tree (using generators) |
|
|
simple design |
turtles on two canvases |
|
another elementary example |
Have fun!