turtle — Turtle graphics

소스 코드: Lib/turtle.py


Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise.

Turtle graphics is an implementation of the drawing tools introduced in Logo in 1967. It was created as an educational tool, and its instant, visible feedback makes it an effective way for learners to encounter programming concepts. It is also a convenient way to produce simple graphical output without bringing in external libraries.

This document includes four main sections:

  • Tutorial teaches the basics of turtle drawing.

  • Reference describes the functions, methods and classes this module defines.

  • How-to guides detail how to handle specific tasks.

  • Explanation provides background on the object-oriented interface.

참고

Turtle graphics requires the tkinter optional module. The python.org installers for Windows and macOS include it, but some Linux distributions and other platforms may package it separately. If import turtle fails with an error mentioning _tkinter, look for documentation from your distributor (that is, whoever provided Python to you). Check this in advance if you’re planning to use turtle graphics with a learner.

Tutorial

New users should start here. In this tutorial we’ll explore some of the basics of turtle drawing.

거북이 환경 시작하기

In a Python shell, import all the objects of the turtle module:

from turtle import *

If you run into a Standard library module '_tkinter' was not found error, you’ll have to install the Tk interface package on your system.

Nothing appears yet. To open the turtle window, make the turtle visible:

showturtle()

A new window opens, with the turtle in the middle, shown as an arrow heading East.

Basic drawing

Send the turtle forward 100 steps:

forward(100)

You should see a line drawn by the turtle, heading East. Change the direction of the turtle, so that it turns 120 degrees left (anti-clockwise):

left(120)

Let’s continue by drawing a triangle:

forward(100)
left(120)
forward(100)

Notice how the turtle, represented by an arrow, points in different directions as you steer it.

Experiment with those commands, and also with backward() and right(). Many commands also have shorter aliases, such as fd() for forward().

펜 제어

Try changing the color - for example, color('blue') - and width of the line - for example, width(3) - and then drawing again.

You can also move the turtle around without drawing, by lifting up the pen: up() before moving. To start drawing again, use down().

거북이의 위치

Send your turtle back to its starting-point (useful if it has disappeared off-screen):

home()

The home position is at the center of the turtle’s screen. If you ever need to know them, get the turtle’s x-y coordinates with:

pos()

Home is at (0, 0).

And after a while, it will probably help to clear the window so we can start anew:

clearscreen()

Making algorithmic patterns

Using loops, it’s possible to build up geometric patterns:

for steps in range(100):
    for c in ('blue', 'red', 'green'):
        color(c)
        forward(steps)
        right(30)

- which of course, are limited only by the imagination!

Let’s draw the star shape at the top of this page. We want red lines, filled in with yellow:

color('red')
fillcolor('yellow')

Just as up() and down() determine whether lines will be drawn, filling can be turned on and off:

begin_fill()

Next we’ll create a loop:

start = pos()

while True:
    forward(200)
    left(170)
    if distance(start) < 1:
        break

distance(start) < 1 is a good way to know when the turtle is back at its start position.

Finally, complete the filling:

end_fill()

(Note that filling only actually takes place when you give the end_fill() command.)

Reference

Turtle methods and functions

이 섹션의 대부분의 예제는 turtle이라는 Turtle 인스턴스를 참조합니다.

이동과 그리기

turtle.forward(distance)
turtle.fd(distance)
매개변수:

distance – 숫자

거북이가 향한 방향으로, 지정된 distance만큼 거북이를 앞으로 움직입니다.

>>> 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)
매개변수:

distance – 숫자

Move the turtle backward by distance, opposite to the direction the turtle is headed. The turtle’s heading does not change.

>>> turtle.position()
(0.00,0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00,0.00)
turtle.right(angle)
turtle.rt(angle)
매개변수:

angle – 숫자

Turn the turtle right by the specified angle. The angle is measured in degrees by default; the unit can be changed with degrees() or radians(). How the heading is measured depends on the turtle mode, see mode().

>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0
turtle.left(angle)
turtle.lt(angle)
매개변수:

angle – 숫자

Turn the turtle left by the specified angle. The angle is measured in degrees by default; the unit can be changed with degrees() or radians(). How the heading is measured depends on the turtle mode, see mode().

>>> 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)
매개변수:
  • x – 숫자나 숫자의 쌍/벡터

  • y – 숫자나 None

Move the turtle to an absolute position. If y is None, x must be a pair of coordinates or a Vec2D, for example as returned by pos(). 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)
매개변수:
  • x – 숫자나 None

  • y – 숫자나 None

  • fill_gap – a boolean

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=True to keep filling one shape instead. The teleport then counts as an edge of the shape, as it would with goto().

>>> 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)

Added in version 3.12.

turtle.setx(x)
매개변수:

x – 숫자

Set the turtle’s x coordinate to x. The y coordinate is unchanged.

>>> turtle.position()
(0.00,240.00)
>>> turtle.setx(10)
>>> turtle.position()
(10.00,240.00)
turtle.sety(y)
매개변수:

y – 숫자

Set the turtle’s y coordinate to y. The x coordinate is unchanged.

>>> turtle.position()
(0.00,40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00,-10.00)
turtle.setheading(to_angle)
turtle.seth(to_angle)
매개변수:

to_angle – 숫자

Set the turtle’s heading to to_angle. Here are some common directions in degrees:

표준 모드

로고 모드

0 - 동

0 - 북

90 - 북

90 - 동

180 - 서

180 - 남

270 - 남

270 - 서

>>> 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)
매개변수:
  • radius – 숫자

  • extent – 숫자나 None

  • steps – 정수나 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)  # 반원을 그립니다
>>> 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, /)
매개변수:
  • size – a positive integer or None

  • color – 색상 문자열이나 숫자 색상 튜플

Draw a circular dot with diameter size, using color. If size is not given, the larger of pensize + 4 and 2 * pensize is 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()

Stamp a copy of the turtle shape onto the canvas and return its id. The stamp is placed at the current turtle position. The returned id can be used to delete the stamp with clearstamp().

>>> turtle.color("blue")
>>> stamp_id = turtle.stamp()
>>> turtle.fd(50)
turtle.clearstamp(stampid)
매개변수:

stampid – an integer

Delete the stamp with the given stampid. stampid must be the return value of a previous stamp() call.

>>> 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)
매개변수:

n – 정수나 None

Delete all or the first or last n of the turtle’s stamps. If n is not given, delete all stamps. If n is positive, delete the first n stamps. If n is negative, delete the last n stamps, so -2 deletes the last two.

>>> for i in range(8):
...     unused_stamp_id = turtle.stamp()
...     turtle.fd(30)
>>> turtle.clearstamps(2)
>>> turtle.clearstamps(-2)
>>> turtle.clearstamps()
turtle.undo()

마지막 거북이의 행동을 (반복적으로) 되돌립니다. 되돌릴 수 있는 행동의 수는 언두버퍼(undobuffer)의 크기에 따라 결정됩니다.

>>> for i in range(4):
...     turtle.fd(50); turtle.lt(80)
...
>>> for i in range(8):
...     turtle.undo()
turtle.speed(speed=None)
매개변수:

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() and back() make the turtle jump, and likewise left() and right() make the turtle turn instantly.

>>> turtle.speed()
3
>>> turtle.speed('normal')
>>> turtle.speed()
6
>>> turtle.speed(9)
>>> turtle.speed()
9

거북이의 상태 보고

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)
매개변수:
  • x – 숫자 또는 숫자 쌍/벡터 또는 거북이 인스턴스

  • y – x가 숫자면 숫자, 그렇지 않으면 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, a Vec2D, for example as returned by pos(), or another turtle. The angle is measured from the turtle’s start orientation, which depends on the turtle mode, see mode().

>>> turtle.goto(10, 10)
>>> turtle.towards(0,0)
225.0
turtle.xcor()

거북이의 x 좌표를 반환합니다.

>>> turtle.home()
>>> turtle.left(50)
>>> turtle.forward(100)
>>> turtle.pos()
(64.28,76.60)
>>> print(round(turtle.xcor(), 5))
64.27876
turtle.ycor()

거북이의 y 좌표를 반환합니다.

>>> 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)
매개변수:
  • x – 숫자 또는 숫자 쌍/벡터 또는 거북이 인스턴스

  • y – x가 숫자면 숫자, 그렇지 않으면 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, a Vec2D, for example as returned by pos(), 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

측정 설정

turtle.degrees(fullcircle=360.0)
매개변수:

fullcircle – 숫자

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

>>> # 각도 측정 단위를 그레이드(grad)로 변경합니다 (곤(gon),
>>> # grade, 그라디안(gradian)이라고도 하며 직각의 1/100 에 해당합니다.)
>>> 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

펜 제어

그리기 상태
turtle.pendown()
turtle.pd()
turtle.down()

Lower the pen. The turtle draws a line when it moves.

turtle.penup()
turtle.pu()
turtle.up()

Lift the pen. The turtle does not draw when it moves.

turtle.pensize(width=None)
turtle.width(width=None)
매개변수:

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)   # 여기서부터 두께가 10인 선이 그려집니다
turtle.pen(pen=None, **pendict)
매개변수:
  • pen – a dictionary or None

  • pendict – keyword arguments with the keys below

Return or set the pen’s attributes. The attributes are returned as a dictionary with the following keys and values:

  • “shown”: True or False

  • “pendown”: True or False

  • “pencolor”: a color string or a color tuple

  • “fillcolor”: a color string or a color tuple

  • “pensize”: a positive number

  • “speed”: a number from 0 to 10

  • “resizemode”: “auto”, “user” or “noresize”

  • “stretchfactor”: a pair of positive numbers

  • “shearfactor”: a number

  • “outline”: a positive number

  • “tilt”: a number

Such a dictionary can be passed as pen to restore a former pen state. The attributes can also be given as keyword arguments, which can be used to set several of them in one statement.

>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
>>> turtle.pen()
{'shown': True, 'pendown': True, 'pencolor': 'red', 'fillcolor': 'black',
 'pensize': 10, 'speed': 9, 'resizemode': 'noresize',
 'stretchfactor': (1.0, 1.0), 'shearfactor': 0.0, 'outline': 1,
 'tilt': 0.0}
>>> penstate = turtle.pen()
>>> turtle.color("yellow", "")
>>> turtle.penup()
>>> turtle.pen()["pencolor"]
'yellow'
>>> # restore the saved pen state, but with a green fill
>>> turtle.pen(penstate, fillcolor="green")
>>> turtle.pen()["pencolor"]
'red'
>>> turtle.pen()["fillcolor"]
'green'
turtle.isdown()

Return True if the pen is down, False if it’s up.

>>> turtle.penup()
>>> turtle.isdown()
False
>>> turtle.pendown()
>>> turtle.isdown()
True
색상 제어
turtle.pencolor()
turtle.pencolor(color, /)
turtle.pencolor(r, g, b, /)

펜 색상(pencolor)을 반환하거나 설정합니다.

네 가지 입력 형식이 허용됩니다:

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() or bgcolor() 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, /)

채우기 색상(fillcolor)을 반환하거나 설정합니다.

네 가지 입력 형식이 허용됩니다:

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() or bgcolor() 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))  # 정수입니다, 실수가 아닙니다
>>> 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()

pencolor()와 fillcolor()에 의해 반환된 현재 펜 색상과 현재 채우기 색상을 한 쌍의 색 지정 문자열이나 튜플로 반환합니다.

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))

pencolor(colorstring1)과 fillcolor(colorstring2)와 동등하며 다른 입력 형식을 사용하는 경우도 유사합니다.

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))

참조: Screen 메서드 colormode().

채우기
turtle.filling()

Return True if the turtle is filling, False otherwise.

>>> turtle.begin_fill()
>>> if turtle.filling():
...    turtle.pensize(5)
... else:
...    turtle.pensize(3)
turtle.fill()

Fill the shape drawn in the with block.

>>> turtle.color("black", "red")
>>> with turtle.fill():
...     turtle.circle(80)

fill() is a context manager, so using it is the same as calling begin_fill() before the block and end_fill() after it:

>>> turtle.color("black", "red")
>>> turtle.begin_fill()
>>> turtle.circle(80)
>>> turtle.end_fill()

Added in version 3.14.

turtle.begin_fill()

Call just before drawing a shape to be filled. The shape is filled by the next call to end_fill().

turtle.end_fill()

begin_fill()을 마지막으로 호출한 후 그린 모양을 채웁니다.

If the shape crosses itself or several shapes overlap, whether the overlapping parts are filled depends on the operating system, the type of overlap and how many there are. 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()
더 많은 그리기 제어
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'))
매개변수:
  • arg – an object

  • move – a boolean

  • align – a string

  • font – a tuple of a string, an integer and a string

Write text at the current turtle position. The text is the string representation of arg. align is one of the strings “left”, “center” or “right” and says how the text is placed relative to the turtle position. font is a triple of font name, font size and font type. If move is True, the pen is moved to the bottom-right corner of the text.

>>> turtle.write("Home = ", True, align="center")
>>> turtle.write((0,0), True)

거북이 상태

가시성
turtle.hideturtle()
turtle.ht()

Make the turtle invisible. If the pen is down, movement still draws.

turtle.showturtle()
turtle.st()

거북이가 보이게 합니다.

turtle.isvisible()

Return True if the turtle is visible, False if it’s hidden.

>>> turtle.hideturtle()
>>> turtle.isvisible()
False
>>> turtle.showturtle()
>>> turtle.isvisible()
True
외관
turtle.shape(name=None)
매개변수:

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 the Screen method register_shape().

>>> turtle.shape()
'classic'
>>> turtle.shape("turtle")
>>> turtle.shape()
'turtle'
turtle.resizemode(rmode=None)
매개변수:

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.

shapesize()에 인자를 사용하면 resizemode("user") 를 호출합니다.

>>> 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)
매개변수:
  • stretch_wid – a positive number or None

  • stretch_len – a positive number or None

  • outline – 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)
매개변수:

shear – 숫자나 None

Return or set the current shear factor. Shearing slants the turtle shape, like the slant of italic letters. The shear factor says how much it is slanted: 0 is not slanted at all, and the larger the number, the stronger the slant. Negative numbers slant the other way. If shear is not given, return the current shear factor. Otherwise slant the turtle shape accordingly and set resizemode to “user”. The turtle’s heading does not change. Precisely, the shear factor is the tangent of the shear angle.

>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.shearfactor(0.5)
>>> turtle.shearfactor()
0.5
turtle.tilt(angle)
매개변수:

angle – 숫자

Turn the turtle shape by angle from its current tilt angle. The turtle’s heading does not change, so the turtle keeps moving in the same direction. See tiltangle().

>>> 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)
매개변수:

angle – 숫자나 None

Return or set the current tilt angle. The tilt angle is the angle between the direction the turtle shape points in and the direction the turtle moves in. Normally the shape points in the direction of movement, so the tilt angle is 0. If angle is given, turn the turtle shape to that tilt angle, no matter what it was before, and set resizemode to “user”. The turtle’s heading does not change. If angle is not given, return the current tilt angle.

>>> 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)
매개변수:
  • t11 – 숫자나 None

  • t12 – 숫자나 None

  • t21 – 숫자나 None

  • t22 – 숫자나 None

Return or set the transformation matrix of the turtle shape. The matrix combines the stretch factors, the shear factor and the tilt angle of the turtle shape into four numbers: t11 and t12 form its first row, t21 and t22 its second. If none of them are given, return the current matrix as a tuple of four numbers. Otherwise set the given elements and update the stretch factors, shear factor and tilt angle accordingly. t11 * t22 - t12 * t21 must not be zero, otherwise an error is raised.

>>> 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 points that form the outline of the current turtle shape as a tuple of (x, y) coordinate pairs. These points can be used to define a new shape or parts of a compound shape

>>> turtle.shape("square")
>>> turtle.shapetransform(4, -1, 0, 2)
>>> turtle.get_shapepoly()
((50, -20), (30, 20), (-50, 20), (-30, -20))

이벤트 사용하기

turtle.onclick(fun, btn=1, add=None)
매개변수:
  • fun – a function with two arguments or None

  • btn – 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 is True, 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)  # 이제 거북이를 클릭하면 회전합니다.
>>> onclick(None)  # 이벤트 연결을 제거합니다
turtle.onrelease(fun, btn=1, add=None)
매개변수:
  • fun – 캔버스에서 클릭한 점의 좌표로 호출되는 두 개의 인자가 있는 함수

  • btn – 마우스 버튼 수, 기본값은 1 (마우스 왼쪽 버튼)

  • add – True 또는 False – True이면, 새 연결이 추가되고, 그렇지 않으면 이전 연결을 대체합니다

이 거북이의 마우스 버튼 해제 이벤트에 fun을 연결합니다. fun이 None이면 기존 연결이 제거됩니다.

>>> class MyTurtle(Turtle):
...     def glow(self,x,y):
...         self.fillcolor("red")
...     def unglow(self,x,y):
...         self.fillcolor("")
...
>>> turtle = MyTurtle()
>>> turtle.onclick(turtle.glow)     # 거북이를 클릭하면 붉은색으로 채웁니다,
>>> turtle.onrelease(turtle.unglow) # 버튼 해제하면 투명하게 만듭니다.
turtle.ondrag(fun, btn=1, add=None)
매개변수:
  • fun – 캔버스에서 클릭한 점의 좌표로 호출되는 두 개의 인자가 있는 함수

  • btn – 마우스 버튼 수, 기본값은 1 (마우스 왼쪽 버튼)

  • add – True 또는 False – True이면, 새 연결이 추가되고, 그렇지 않으면 이전 연결을 대체합니다

이 거북이의 마우스 이동 이벤트에 fun을 연결합니다. fun이 None이면 기존 연결이 제거됩니다.

참고: 거북이의 모든 마우스 이동 이벤트에 앞서 해당 거북이의 마우스 클릭 이벤트가 선행합니다.

>>> turtle.ondrag(turtle.goto)

그 후, 거북이를 클릭하고 드래그하면 화면을 가로질러 거북이가 움직여 손 그림을 생성합니다 (펜이 내려가 있다면).

특수 Turtle 메서드

turtle.poly()

Record the vertices of a polygon drawn in the with block. The first and last vertices will be connected.

>>> with turtle.poly():
...     turtle.forward(100)
...     turtle.right(60)
...     turtle.forward(100)

poly() is a context manager, so using it is the same as calling begin_poly() before the block and end_poly() after it:

>>> turtle.begin_poly()
>>> turtle.forward(100)
>>> turtle.right(60)
>>> turtle.forward(100)
>>> turtle.end_poly()

Added in version 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()

마지막으로 기록된 다각형을 반환합니다.

>>> 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. 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 as forward() and left():

>>> pet = getturtle()
>>> pet.fd(50)
>>> pet
<turtle.Turtle object at 0x...>
turtle.getscreen()

거북이가 그리는 TurtleScreen 객체를 반환합니다. 그런 다음 해당 객체에 대해 TurtleScreen 메서드를 호출할 수 있습니다.

>>> ts = turtle.getscreen()
>>> ts
<turtle._Screen object at 0x...>
>>> ts.bgcolor("pink")
turtle.setundobuffer(size)
매개변수:

size – 정수나 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 is None, 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

이 섹션의 대부분의 예제는 screen이라는 TurtleScreen 인스턴스를 참조합니다.

창 제어

turtle.bgcolor()
turtle.bgcolor(color, /)
turtle.bgcolor(r, g, b, /)

Return or set the background color of the TurtleScreen.

네 가지 입력 형식이 허용됩니다:

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() or bgcolor() call.

bgcolor(colorstring)

Set the background color to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#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)
매개변수:

picname – a string or None

Set the background image or return the name of the current one. If picname is the name of an image file (PNG, GIF, PGM, and PPM), set that image as the background. If picname is "nopic", delete the background image, if present. If picname is None, return the filename of the current background image.

>>> screen.bgpic()
'nopic'
>>> screen.bgpic("landscape.gif")
>>> screen.bgpic()
'landscape.gif'
turtle.clear()

참고

이 TurtleScreen 메서드는 clearscreen이라는 이름으로만 전역 함수로 사용할 수 있습니다. 전역 함수 clear는 Turtle 메서드 clear에서 파생된 다른 것입니다.

turtle.clearscreen()

TurtleScreen에서 모든 그림과 모든 거북이를 삭제합니다. 이제 비어있는 TurtleScreen을 초기 상태로 재설정합니다: 흰색 배경, 배경 이미지 없음, 이벤트 연결과 추적 없음.

turtle.reset()

참고

이 TurtleScreen 메서드는 resetscreen이라는 이름으로만 전역 함수로 사용할 수 있습니다. 전역 함수 reset은 Turtle 메서드 reset에서 파생된 또 다른 함수입니다.

turtle.resetscreen()

Reset all turtles on the screen to their initial state.

turtle.screensize(canvwidth=None, canvheight=None, bg=None)
매개변수:
  • canvwidth – a positive integer or None

  • canvheight – a positive integer or None

  • bg – a colorstring or a color tuple or None

Resize the canvas the turtles are drawing on. canvwidth and canvheight are the new width and height of the canvas in pixels, and bg is the new background color. If no arguments are given, return the current canvas width and height.

The drawing window is not altered. To see hidden parts of the canvas, use the scrollbars. This can make visible those parts of a drawing which were outside the canvas before, for example to find a turtle that has wandered off the canvas.

>>> screen.screensize()
(400, 300)
>>> screen.screensize(2000,1500)
>>> screen.screensize()
(2000, 1500)
turtle.setworldcoordinates(llx, lly, urx, ury)
매개변수:
  • llx – 숫자

  • lly – 숫자

  • urx – 숫자

  • ury – 숫자

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)   # 정 팔각형

애니메이션 제어

turtle.no_animation()

Temporarily turn off turtle animation. The code inside the with block 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)

Added in version 3.14.

turtle.delay(delay=None)
매개변수:

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)
매개변수:
  • n – a nonnegative integer or None

  • delay – 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, see delay(). 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()

TurtleScreen 갱신을 수행합니다. tracer가 꺼져있을 때 사용됩니다.

RawTurtle/Turtle 메서드 speed()도 참조하십시오.

화면 이벤트 사용하기

turtle.listen(xdummy=None, ydummy=None)
매개변수:
  • xdummy – ignored

  • ydummy – ignored

Set focus on the TurtleScreen so that it receives key events. The two dummy arguments are only there so that listen() can be passed to onclick().

turtle.onkey(fun, key)
turtle.onkeyrelease(fun, key)
매개변수:
  • fun – 인자가 없는 함수나 None

  • key – a string

Bind fun to the key-release event of key. key is a key, such as “a”, or a key symbol, such as “space”. If fun is None, the event binding is removed. To be able to receive key events, the TurtleScreen must have focus, see listen().

>>> def f():
...     fd(50)
...     lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()

The turtle can then be moved by repeatedly pressing the up-arrow key, drawing a hexagon.

turtle.onkeypress(fun, key=None)
매개변수:
  • fun – 인자가 없는 함수나 None

  • key – a string or None

Bind fun to the key-press event of key. key is a key, such as “a”, or a key symbol, such as “space”. If key is not given, fun is bound to the key-press event of any key. If fun is None, the event binding is removed. To be able to receive key events, the TurtleScreen must have focus, see listen().

>>> def f():
...     fd(50)
...     lt(60)
...
>>> screen.onkeypress(f, "Up")
>>> screen.listen()

The turtle can then be moved by pressing or holding down the up-arrow key, drawing a hexagon.

turtle.onclick(fun, btn=1, add=None)
turtle.onscreenclick(fun, btn=1, add=None)
매개변수:
  • fun – a function with two arguments or None

  • btn – 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 is True, a new binding is added, otherwise it replaces a former binding.

이름이 screen인 TurtleScreen 인스턴스와 이름이 turtle인 거북이 인스턴스의 예:

>>> screen.onclick(turtle.goto) # 이후 TurtleScreen을 클릭하면 거북이가 클릭한 지점으로
>>>                             # 이동합니다.
>>> screen.onclick(None)        # 이벤트 연결을 다시 제거합니다

참고

이 TurtleScreen 메서드는 onscreenclick이라는 이름으로만 전역 함수로 사용할 수 있습니다. 전역 함수 onclick은 Turtle 메서드 onclick에서 파생된 또 다른 함수입니다.

turtle.ontimer(fun, t=0)
매개변수:
  • fun – 인자가 없는 함수

  • t – a nonnegative number

t 밀리초 후에 fun을 호출하는 타이머를 설치합니다.

>>> running = True
>>> def f():
...     if running:
...         fd(50)
...         lt(60)
...         screen.ontimer(f, 250)
>>> f()  # makes the turtle march around
>>> 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 서브 프로세스 없이 실행하기).

입력 메서드

turtle.textinput(title, prompt)
매개변수:
  • 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", "Name of first player:")
turtle.numinput(title, prompt, default=None, minval=None, maxval=None)
매개변수:
  • title – a string

  • prompt – a string

  • default – 숫자나 None

  • minval – 숫자나 None

  • maxval – 숫자나 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", "Your stakes:", 1000, minval=10, maxval=10000)

설정과 특수 메서드

turtle.mode(mode=None)
매개변수:

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 turtle module. Mode “logo” is compatible with most Logo turtle graphics. Mode “world” uses user-defined world coordinates, see setworldcoordinates(). In this mode, angles appear distorted if the x and y units are not of equal length.

모드

초기 거북이 방향

양의 각도

“standard”

오른쪽 (동)

시계 반대 방향

“logo”

위쪽 (북)

시계 방향

>>> mode("logo")  # resets turtle heading to north
>>> mode()
'logo'
turtle.colormode(cmode=None)
매개변수:

cmode – 숫자나 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()

이 TurtleScreen의 캔버스를 반환합니다. Tkinter Canvas로 작업하는 법을 알고 있는 내부자에게 유용합니다.

>>> cv = screen.getcanvas()
>>> cv
<turtle.ScrolledCanvas object ...>
turtle.getshapes()

현재 사용 가능한 모든 거북이 모양의 이름 리스트를 반환합니다.

>>> screen.getshapes()
['arrow', 'blank', 'circle', ..., 'turtle']
turtle.register_shape(name, shape=None)
turtle.addshape(name, shape=None)
매개변수:
  • name – a string

  • shape – a string, a tuple of pairs of numbers, a Shape object or None

Add a turtle shape to the TurtleScreen’s shape list. It can be called in four different ways:

  1. 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")
    
  2. 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")
    
  3. name은 임의의 문자열이고 shape은 좌표 쌍의 튜플입니다: 해당 다각형 모양을 설치합니다.

    >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
    
  4. name은 임의의 문자열이고 shape은 (복합) 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.

버전 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()

화면에 있는 거북이의 리스트를 반환합니다.

>>> for turtle in screen.turtles():
...     turtle.color("red")
turtle.window_height()

거북이 창의 높이를 반환합니다.

>>> screen.window_height()
480
turtle.window_width()

거북이 창의 너비를 반환합니다.

>>> screen.window_width()
640

Screen-only methods

turtle.bye()

Close the turtle graphics window.

turtle.exitonclick()

bye() 메서드를 Screen에서의 마우스 클릭에 연결합니다.

구성 딕셔너리의 “using_IDLE” 값이 False(기본값)면, 에인 루프에 진입하기도 합니다. 비고: -n 스위치로 IDLE(서브 프로세스 없음)을 사용하면, 이 값은 turtle.cfg에서 True로 설정되어야 합니다. 이 경우 IDLE의 자체 메인 루프는 클라이언트 스크립트에서도 활성화됩니다.

turtle.save(filename, *, overwrite=False)
매개변수:
  • filename – a string

  • overwrite – a boolean

Save the current drawing and the turtles as a PostScript file. filename is the path of the file to create. It must end with ".ps" or ".eps". If a file with that name already exists, a FileExistsError is raised, unless overwrite is True. overwrite must be given by name, as in overwrite=True.

>>> screen.save("my_drawing.ps")
>>> screen.save("my_drawing.ps", overwrite=True)

Added in version 3.14.

turtle.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom'])

메인 창의 크기와 위치를 설정합니다. 인자의 기본값은 구성 딕셔너리에 저장되며 turtle.cfg 파일을 통해 변경할 수 있습니다.

매개변수:
  • width – 정수면 픽셀 단위의 크기, 실수면 화면의 비율; 기본값은 화면의 50%입니다

  • height – 정수면 픽셀 단위의 높이, 실수면 화면의 비율; 기본값은 화면의 75%입니다

  • startx – 양수이면 화면의 왼쪽 가장자리에서부터의 픽셀 단위의 시작 위치, 음수이면 오른쪽 가장자리에서부터, None이면 창을 가로로 가운데 정렬합니다

  • starty – 양수이면 화면 위쪽 가장자리에서부터의 픽셀 단위의 시작 위치, 음수이면 아래쪽 가장자리에서부터, None이면 창을 세로로 가운데 정렬합니다

>>> screen.setup (width=200, height=200, startx=0, starty=0)
>>>              # 창을 200x200 픽셀 크기로 화면 왼쪽 상단에 설정합니다
>>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
>>>              # 창을 화면 너비의 75%, 화면 높이의 50% 크기로 가운데에 설정합니다
turtle.title(titlestring)
매개변수:

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!")

공개 클래스

class turtle.RawTurtle(canvas)
class turtle.RawPen(canvas)
매개변수:

canvas – tkinter.Canvas, ScrolledCanvas나 TurtleScreen

거북이를 만듭니다. 거북이는 위에서 “Turtle/RawTurtle의 메서드”라고 언급한 모든 메서드를 갖습니다.

class turtle.Turtle

RawTurtle의 서브 클래스. 인터페이스는 같지만 처음 필요할 때 자동으로 생성된 기본 Screen 객체에 그립니다.

class turtle.TurtleScreen(cv)
매개변수:

cv – tkinter.Canvas

위에서 설명한 bgcolor() 등과 같은 화면 지향 메서드를 제공합니다.

class turtle.Screen

Subclass of TurtleScreen, with four methods added. Calling Screen() returns the single screen object. If it does not exist yet, it is created. Otherwise the existing one is returned.

class turtle.ScrolledCanvas(master)
매개변수:

master – ScrolledCanvas, 즉 스크롤 막대가 추가된 Tkinter-Canvas를 담을 어떤 Tkinter 위젯

클래스 Screen에서 사용되며, 거북 놀이터로 ScrolledCanvas를 자동으로 제공합니다.

class turtle.Shape(type_, data)
매개변수:
  • 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 the addcomponent() method.

addcomponent(poly, fill, outline=None)
매개변수:
  • 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.

예:

>>> 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()

How to use compound shapes을 참조하십시오.

class turtle.Vec2D(x, y)

2차원 벡터 클래스. 터틀 그래픽을 구현하기 위한 도우미 클래스로 사용됩니다. 터틀 그래픽 프로그램에도 유용할 수 있습니다. 튜플에서 파생되기 때문에, 벡터는 튜플입니다!

다음을 제공합니다 (a, b는 벡터, k는 번호):

  • a + b 벡터 덧셈

  • a - b 벡터 뺄셈

  • a * b 내적(inner product)

  • k * a와 a * k 스칼라를 사용한 곱셈

  • abs(a) a의 절댓값

  • a.rotate(angle) 회전

Exceptions

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

This section covers some typical turtle use-cases and approaches.

How to automatically begin and end filling

Starting with Python 3.14, you can use the fill() context manager instead of begin_fill() and end_fill() to automatically begin and end fill. Here is an example:

with fill():
    for i in range(4):
        forward(100)
        right(90)

forward(200)

The code above is equivalent to:

begin_fill()
for i in range(4):
    forward(100)
    right(90)
end_fill()

forward(200)

How to use compound shapes

다른 색상의 여러 다각형으로 구성된 복합 거북이 모양을 사용하려면, 아래 설명된 대로 도우미 클래스 Shape을 명시적으로 사용해야 합니다:

  1. Create an empty Shape object of type “compound”.

  2. addcomponent() 메서드를 사용하여, 원하는 만큼 이 객체에 구성 요소를 추가합니다.

    예를 들면:

    >>> s = Shape("compound")
    >>> poly1 = ((0,0), (10,-5), (0,10), (-10,-5))
    >>> s.addcomponent(poly1, "red", "blue")
    >>> poly2 = ((0,0), (10,-5), (-10,-5))
    >>> s.addcomponent(poly2, "blue", "red")
    
  3. 이제 Shape을 Screen의 모양 리스트(shapelist)에 추가하고 사용합니다:

    >>> register_shape("myshape", s)
    >>> shape("myshape")
    

How to use the turtle module namespace

Using from turtle import * is convenient - but be warned that it imports a rather large collection of objects, and if you’re doing anything but turtle graphics you run the risk of a name conflict (this becomes even more an issue if you’re using turtle graphics in a script where other modules might be imported).

The solution is to use import turtle - fd() becomes turtle.fd(), width() becomes turtle.width() and so on. (If typing “turtle” over and over again becomes tedious, use for example import turtle as t instead.)

How to use turtle graphics in a script

It’s recommended to use the turtle module namespace as described immediately above, for example:

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)

Another step is also required though - as soon as the script ends, Python will also close the turtle’s window. Add:

t.mainloop()

to the end of the script. The script will now wait to be dismissed and will not exit until it is terminated, for example by closing the turtle graphics window.

How to use object-oriented turtle graphics

Other than for very basic introductory purposes, or for trying things out as quickly as possible, it’s more usual and much more powerful to use the object-oriented approach to turtle graphics. For example, this allows multiple turtles on screen at once.

In this approach, the various turtle commands are methods of objects (mostly of Turtle objects). You can use the object-oriented approach in the shell, but it would be more typical in a Python script.

The example above then becomes:

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()

Note the last line. t.screen is an instance of the Screen that a Turtle instance exists on; it’s created automatically along with the turtle.

The turtle’s screen can be customised, for example:

t.screen.title('Object-oriented turtle demo')
t.screen.bgcolor("orange")

How to use help()

Screen과 Turtle 클래스의 공개 메서드는 독스트링을 통해 광범위하게 설명됩니다. 파이썬 도움말 기능을 통해 온라인 도움말로 사용할 수 있습니다:

  • IDLE을 사용할 때, 툴팁은 입력된 함수/메서드 호출의 서명과 독스트링의 첫 줄을 보여줍니다.

  • 메서드나 함수에 대해 help()를 호출하면 독스트링을 표시합니다:

    >>> 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()
    
  • 메서드에서 파생된 함수의 독스트링은 다음과 같이 수정된 형식을 갖습니다:

    >>> 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()
    

이러한 수정된 독스트링은 임포트 시점에 메서드에서 파생된 함수 정의와 함께 자동으로 만들어집니다.

독스트링을 다른 언어로 번역

키가 메서드 이름이고 값이 Screen과 Turtle 클래스의 공개 메서드의 독스트링인 딕셔너리를 만드는 유틸리티가 있습니다.

turtle.write_docstringdict(filename='turtle_docstringdict')
매개변수:

filename – 파일명으로 사용되는 문자열

주어진 파일명의 파이썬 스크립트에 독스트링-딕셔너리를 만들고 씁니다. 이 함수는 명시적으로 호출해야 합니다 (터틀 그래픽 클래스에서는 사용되지 않습니다). 독스트링 딕셔너리는 파이썬 스크립트 filename.py에 기록됩니다. 독스트링을 다른 언어로 번역하기 위한 템플릿으로 사용하려는 목적입니다.

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.

여러분의 turtle.cfg 파일에 적절한 항목이 있으면 임포트 시점에 이 딕셔너리를 읽고 원래 영어 독스트링을 대체합니다.

이 글을 쓰는 시점에는 독일어와 이탈리아어로 된 독스트링 딕셔너리가 있습니다. (glingl@aon.at 에 요청하십시오.)

Screen과 Turtle을 구성하는 방법

내장된 기본 구성은 최상의 호환성을 유지하기 위해 기존 turtle 모듈의 외관과 동작을 모방합니다.

이 모듈의 기능을 더 잘 반영하거나 예를 들어 교실에서 사용하기 위해 필요에 더 잘 맞는 다른 구성을 사용하려면, 임포트 시점에 읽는 구성 파일 turtle.cfg를 준비하고 구성을 그 설정에 따라 수정할 수 있습니다.

내장 구성은 다음 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

선택된 항목에 대한 간단한 설명:

  • 처음 네 줄은 Screen.setup 메서드의 인자에 해당합니다.

  • 줄 5와 6은 Screen.screensize 메서드의 인자에 해당합니다.

  • shape은 내장 도형 중 하나일 수 있습니다, 예를 들어 arrow, turtle 등. 자세한 정보는 help(shape)을 시도해 보십시오.

  • 아무런 채우기 색상(fill color)도 사용하지 않으려면 (즉, 거북이를 투명하게 만들려면), fillcolor = ""라고 작성해야 합니다 (그러나 비어 있지 않은 모든 문자열은 cfg 파일에서 따옴표가 없어야 합니다).

  • 거북이의 상태를 반영하려면, resizemode = auto를 사용해야 합니다.

  • If you set e.g. language = italian the docstringdict turtle_docstringdict_italian.py will be loaded at import time (if present on the import path, e.g. in the same directory as turtle).

  • exampleturtle과 examplescreen 항목은 독스트링에서 등장하는 이러한 객체들의 이름을 정의합니다. 메서드 독스트링을 함수 독스트링으로 변환하면 이러한 이름이 독스트링에서 삭제됩니다.

  • using_IDLE: IDLE과 그것의 -n 스위치( “서브 프로세스 없음”)를 정기적으로 사용하면 이 값을 True로 설정하십시오. 이것은 exitonclick()이 메인 루프에 들어가지 못하게 합니다.

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.

Lib/turtledemo 디렉터리는 turtle.cfg 파일을 포함합니다. 예제로 공부하고 데모를 실행할 때 그 효과를 볼 수 있습니다 (바람직하게는 데모 뷰어 내에서는 아닙니다).

Explanation

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.

거북이 그래픽의 함수적 인터페이스는 Turtle과 TurtleScreen/Screen의 다양한 메서드를 사용합니다. 내부적으로, Screen 객체는 Screen 메서드에서 파생된 함수가 호출될 때마다 자동으로 만들어집니다. 마찬가지로, Turtle 메서드에서 파생된 함수가 호출될 때마다 Turtle 객체가 자동으로 생성됩니다.

화면에 여러 거북을 사용하려면, 객체 지향 인터페이스를 사용해야 합니다.

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

또는, 데모 스크립트를 개별적으로 실행할 수 있습니다. 예를 들면,

python -m turtledemo.bytedesign

The turtledemo package directory contains:

  • 스크립트의 소스 코드를 보고 동시에 실행하는 데 사용할 수 있는 데모 뷰어 __main__.py.

  • Multiple scripts demonstrating different features of the turtle module. Examples can be accessed via the Examples menu. They can also be run standalone.

  • 구성 파일을 작성하고 사용하는 방법의 예인 turtle.cfg 파일.

데모 스크립트는 다음과 같습니다:

이름

설명

기능

bytedesign

복잡한 클래식 터틀 그래픽 패턴

tracer(), delay(), update()

chaos

베르홀스트(Verhulst) 동역학의 그래프를 그립니다, 컴퓨터의 계산이 때때로 상식적인 기대에 반하는 결과를 생 할 수 있음을 보여줍니다

세계 좌표

clock

컴퓨터의 시간을 보여주는 아날로그 시계

turtles as clock’s hands, ontimer()

colormixer

r, g, b 실험

ondrag()

forest

3개의 너비 우선 나무

무작위화

fractalcurves

힐버트(Hilbert)와 코흐(Koch) 곡선

재귀

lindenmayer

민족 수학 (인도 콜람)

L-System

minimal_hanoi

하노이의 탑

Rectangular Turtles as Hanoi discs (shape(), shapesize())

nim

3개의 막대 더미로 컴퓨터와 고전적인 님 게임을 합니다.

님 막대로 쓰는 거북, 이벤트 구동 (마우스, 키보드)

paint

극도로 단순한 그리기 프로그램

onclick()

peace

기초

거북이: 외관과 애니메이션

penrose

연과 다트가 있는 비주기적 타일링

stamp()

planet_and_moon

중력 시스템 시뮬레이션

복합 모양, Vec2D

rosette

터틀 그래픽에 관한 위키피디아 기사의 패턴

clone(), undo()

round_dance

반대 방향으로 쌍으로 회전하는 춤추는 거북이

compound shapes, clone() shapesize(), tilt(), get_shapepoly(), update()

sorting_animate

여러 정렬 방법의 시각적 데모

간단한 정렬, 무작위화

tree

(그래픽) 너비 우선 나무 (제너레이터 사용)

clone()

two_canvases

간단한 디자인

두 캔버스의 거북이

yinyang

또 하나의 기초 예제

circle()

즐기세요!