turtle — 터틀 그래픽

소스 코드: Lib/turtle.py


소개

Turtle graphics is an implementation of the popular geometric drawing tools introduced in Logo, developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.

In Python, turtle graphics provides a representation of a physical “turtle” (a little robot with a pen) that draws on a sheet of paper on the floor.

It’s an effective and well-proven way for learners to encounter programming concepts and interaction with software, as it provides instant, visible feedback. It also provides convenient access to graphical output in general.

Turtle drawing was originally created as an educational tool, to be used by teachers in the classroom. For the programmer who needs to produce some graphical output it can be a way to do that without the overhead of introducing more complex or external libraries into their work.

Tutorial

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

Starting a turtle environment

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

from turtle import *

If you run into a No module named '_tkinter' error, you’ll have to install the Tk interface package on your system.

Basic drawing

Send the turtle forward 100 steps:

forward(100)

You should see (most likely, in a new window on your display) 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().

펜 제어

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

The turtle’s position

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 co-ordinates 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:

while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break

abs(pos()) < 1 is a good way to know when the turtle is back at its home position.

Finally, complete the filling:

end_fill()

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

How to…

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

Get started as quickly as possible

One of the joys of turtle graphics is the immediate, visual feedback that’s available from simple commands - it’s an excellent way to introduce children to programming ideas, with a minimum of overhead (not just children, of course).

The turtle module makes this possible by exposing all its basic functionality as functions, available with from turtle import *. The turtle graphics tutorial covers this approach.

It’s worth noting that many of the turtle commands also have even more terse equivalents, such as fd() for forward(). These are especially useful when working with learners for whom typing is not a skill.

You’ll need to have the Tk interface package installed on your system for turtle graphics to work. Be warned that this is not always straightforward, so check this in advance if you’re planning to use turtle graphics with a learner.

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

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.

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

Turtle graphics reference

참고

다음 설명서에서 함수의 인자 목록이 제공됩니다. 물론 메서드에는 추가의 첫 번째 인자 self가 있으며 여기서는 생략합니다.

Turtle 메서드

거북이 움직임
이동과 그리기
거북이의 상태 보고
설정과 측정
펜 제어
그리기 상태
색상 제어
채우기
더 많은 그리기 제어
거북이 상태
가시성
외관
이벤트 사용하기
특수 Turtle 메서드

TurtleScreen/Screen의 메서드

창 제어
애니메이션 제어
화면 이벤트 사용하기
설정과 특수 메서드
입력 메서드
Screen 특정 메서드

RawTurtle/Turtl의 메서드와 해당 함수

이 섹션의 대부분의 예제는 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 – 숫자

거북이가 향한 반대 방향으로, distance만큼 거북이를 뒤로 움직입니다. 거북이의 방향을 바꾸지 않습니다.

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

angle – 숫자 (정수나 실수)

angle 단위만큼 거북이를 오른쪽으로 회전합니다. (단위는 기본적으로 도(degree)이지만, degrees()radians() 함수를 통해 설정할 수 있습니다.) 각도 방향은 거북이 모드에 따라 다릅니다, mode()를 참조하십시오.

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

angle – 숫자 (정수나 실수)

angle 단위만큼 거북이를 왼쪽으로 회전합니다. (단위는 기본적으로 도(degree)이지만, degrees()radians() 함수를 통해 설정할 수 있습니다.) 각도 방향은 거북이 모드에 따라 다릅니다, 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

yNone이면, x는 좌표 쌍이거나 Vec2D여야 합니다 (예를 들어 pos()에서 반환된 것과 같은).

거북이를 절대 위치로 움직입니다. 펜이 내려져 있으면, 선을 그립니다. 거북이의 방향을 바꾸지 않습니다.

>>> tp = turtle.pos()
>>> tp
(0.00,0.00)
>>> turtle.setpos(60,30)
>>> turtle.pos()
(60.00,30.00)
>>> turtle.setpos((20,80))
>>> turtle.pos()
(20.00,80.00)
>>> turtle.setpos(tp)
>>> turtle.pos()
(0.00,0.00)
turtle.teleport(x, y=None, *, fill_gap=False)
매개변수:
  • x – 숫자나 None

  • y – 숫자나 None

  • fill_gap – a boolean

Move turtle to an absolute position. Unlike goto(x, y), a line will not be drawn. The turtle’s orientation does not change. If currently filling, the polygon(s) teleported from will be filled after leaving, and filling will begin again after teleporting. This can be disabled with fill_gap=True, which makes the imaginary line traveled during teleporting act as a fill barrier like in goto(x, y).

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

버전 3.12에 추가.

turtle.setx(x)
매개변수:

x – 숫자 (정수나 실수)

거북이의 첫 번째 좌표를 x로 설정하고, 두 번째 좌표는 변경하지 않습니다.

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

y – 숫자 (정수나 실수)

거북이의 두 번째 좌표를 y로 설정하고, 첫 번째 좌표는 변경하지 않습니다.

>>> 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 – 숫자 (정수나 실수)

거북이의 방향을 to_angle로 설정합니다. 다음은 몇 가지 일반적인 도(degree)로 나타낸 방향입니다:

표준 모드

로고 모드

0 - 동

0 - 북

90 - 북

90 - 동

180 - 서

180 - 남

270 - 남

270 - 서

>>> turtle.setheading(90)
>>> turtle.heading()
90.0
turtle.home()

거북이를 원점 – 좌표 (0,0) – 으로 이동하고 방향을 시작 방향으로 설정합니다 (모드에 따라 다릅니다, 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)

주어진 반지름(radius)으로 원을 그립니다. 중심은 거북이 왼쪽으로 radius 단위입니다; extent – 각도 – 는 원의 어느 부분이 그려지는지를 결정합니다. extent가 주어지지 않으면, 전체 원을 그립니다. extent가 완전한 원이 아니면, 호의 한 끝점이 현재 펜 위치입니다. radius가 양수면 시계 반대 방향으로, 그렇지 않으면 시계 방향으로 호를 그립니다. 마지막으로 거북이의 방향이 extent만큼 변경됩니다.

원은 내접하는 정다각형으로 근사되므로, steps가 사용할 단계 수를 결정합니다. 제공하지 않으면, 자동으로 계산됩니다. 정다각형을 그리는 데 사용할 수 있습니다.

>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(50)
>>> turtle.position()
(-0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(120, 180)  # draw a semicircle
>>> turtle.position()
(0.00,240.00)
>>> turtle.heading()
180.0
turtle.dot(size=None, *color)
매개변수:
  • size – 정수 >= 1 (주어지면)

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

color를 사용하여 지름이 size인 원형 점을 그립니다. size가 제공되지 않으면, pensize+4와 2*pensize 중 큰 값이 사용됩니다.

>>> 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_id를 반환하는데, clearstamp(stamp_id)를 호출하여 스탬프를 삭제하는 데 사용할 수 있습니다.

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

stampid – 정수, 이전 stamp() 호출의 반환 값이어야 합니다

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

n – 정수 (또는 None)

거북이 스탬프의 전부나 처음/마지막 n 개를 삭제합니다. nNone이면, 모든 스탬프를 삭제합니다, n > 0 이면 처음 n 스탬프를 삭제하고, n < 0 이면 마지막 n 스탬프를 삭제합니다.

>>> 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 – 0..10 범위의 정수나 속도 문자열 (아래를 참조하십시오)

거북이의 속도를 0..10 범위의 정숫값으로 설정합니다. 인자가 없으면, 현재 속도를 반환합니다.

입력이 10보다 크거나 0.5보다 작은 숫자면, 속도는 0으로 설정됩니다. 속도 문자열은 다음과 같이 속도 값에 매핑됩니다:

  • “fastest”: 0

  • “fast”: 10

  • “normal”: 6

  • “slow”: 3

  • “slowest”: 1

1에서 10까지의 속도는 선 그리기와 거북이 회전의 애니메이션이 점점 더 빨라집니다.

주의: speed = 0 은 애니메이션이 발생하지 않음을 의미합니다. forward/back은 거북이가 점프하게 만들고 마찬가지로 left/right는 거북이가 순간적으로 방향을 바꾸게 만듭니다.

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

거북이의 상태 보고

turtle.position()
turtle.pos()

거북이의 현재 위치 (x, y)를 (Vec2D 벡터로) 반환합니다.

>>> turtle.pos()
(440.00,-0.00)
turtle.towards(x, y=None)
매개변수:
  • x – 숫자 또는 숫자 쌍/벡터 또는 거북이 인스턴스

  • yx가 숫자면 숫자, 그렇지 않으면 None

거북이 위치에서 (x, y), 벡터 또는 다른 거북이로 지정된 위치로의 선과의 각도를 반환합니다. 이것은 거북이의 시작 방향에 따라 다른데, 이는 모드에 따라 다릅니다 - “standard”/”world” 또는 “logo”.

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

거북이의 현재 방향을 반환합니다 (값은 거북이 모드에 따라 다릅니다. mode()를 참조하십시오).

>>> turtle.home()
>>> turtle.left(67)
>>> turtle.heading()
67.0
turtle.distance(x, y=None)
매개변수:
  • x – 숫자 또는 숫자 쌍/벡터 또는 거북이 인스턴스

  • yx가 숫자면 숫자, 그렇지 않으면 None

거북이에서 (x, y), 주어진 벡터 또는 주어진 다른 거북이까지의 거리를 거북이 단계 단위로 반환합니다.

>>> 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 – 숫자

각도 측정 단위를 설정합니다, 즉 전체 원에 대한 “도(degrees)”의 수를 설정합니다. 기본값은 360도입니다.

>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0

Change angle measurement unit to grad (also known as gon,
grade, or gradian and equals 1/100-th of the right angle.)
>>> turtle.degrees(400.0)
>>> turtle.heading()
100.0
>>> turtle.degrees(360)
>>> turtle.heading()
90.0
turtle.radians()

각도 측정 단위를 라디안으로 설정합니다. 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()

펜을 내립니다 – 움직일 때 그립니다.

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

펜을 올립니다 – 움직일 때 그리지 않습니다.

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

width – 양수

선 두께를 width로 설정하거나 반환합니다. 크기 조정 모드(resizemode)가 “auto”로 설정되고 거북이 모양(shape)이 다각형이면, 해당 다각형은 같은 선 두께로 그려집니다. 인자가 없으면, 현재 펜 크기가 반환됩니다.

>>> turtle.pensize()
1
>>> turtle.pensize(10)   # from here on lines of width 10 are drawn
turtle.pen(pen=None, **pendict)
매개변수:
  • pen – 아래 나열된 키 중 일부나 전부가 포함된 딕셔너리

  • pendict – 아래에 나열된 키를 키워드로 사용하는 하나 이상의 키워드 인자

다음 키/값 쌍으로 “펜 딕셔너리”에 있는 펜의 속성을 반환하거나 설정합니다:

  • “shown”: True/False

  • “pendown”: True/False

  • “pencolor”: 색상 문자열이나 색상 튜플

  • “fillcolor”: 색상 문자열이나 색상 튜플

  • “pensize”: 양수

  • “speed”: 0..10 범위의 숫자

  • “resizemode”: “auto” 또는 “user” 또는 “noresize”

  • “stretchfactor”: (양수, 양수)

  • “outline”: 양수

  • “tilt”: 숫자

이 딕셔너리는 이전 펜 상태를 복원하기 위해 pen()의 후속 호출에 대한 인자로 사용될 수 있습니다. 또한 이러한 속성 중 하나 이상을 키워드 인자로 제공할 수 있습니다. 하나의 문장에서 여러 펜 속성을 설정하는 데 사용할 수 있습니다.

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

펜이 내려가 있으면 True를, 올라가 있으면 False를 반환합니다.

>>> turtle.penup()
>>> turtle.isdown()
False
>>> turtle.pendown()
>>> turtle.isdown()
True

색상 제어

turtle.pencolor(*args)

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

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

pencolor()

현재 펜 색상을 색상 지정 문자열이나 튜플로 반환합니다 (예를 참조하십시오). 다른 color/pencolor/fillcolor 호출에 대한 입력으로 사용될 수 있습니다.

pencolor(colorstring)

펜 색상을 "red", "yellow" 또는 "#33cc8c"와 같은 Tk 색상 지정 문자열인 colorstring으로 설정합니다.

pencolor((r, g, b))

펜 색상을 r, gb의 튜플로 표현되는 RGB 색상으로 설정합니다. r, gb 각각은 0..colormode 범위에 있어야 합니다. 여기서 colormode는 1.0이나 255입니다 (colormode()를 참조하십시오).

pencolor(r, g, b)

펜 색상을 r, gb로 표현되는 RGB 색상으로 설정합니다. r, gb는 각각 0..colormode 범위에 있어야 합니다.

거북이 모양이 다각형이면, 해당 다각형의 외곽선은 새로 설정된 펜 색상으로 그려집니다.

>>> colormode()
1.0
>>> turtle.pencolor()
'red'
>>> turtle.pencolor("brown")
>>> turtle.pencolor()
'brown'
>>> tup = (0.2, 0.8, 0.55)
>>> turtle.pencolor(tup)
>>> turtle.pencolor()
(0.2, 0.8, 0.5490196078431373)
>>> colormode(255)
>>> turtle.pencolor()
(51.0, 204.0, 140.0)
>>> turtle.pencolor('#32c18f')
>>> turtle.pencolor()
(50.0, 193.0, 143.0)
turtle.fillcolor(*args)

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

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

fillcolor()

현재 채우기 색상을 색상 지정 문자열로 (튜플 형식으로도 가능합니다) 반환합니다 (예를 참조하십시오). 다른 color/pencolor/fillcolor 호출에 대한 입력으로 사용될 수 있습니다.

fillcolor(colorstring)

채우기 색상을 "red", "yellow" 또는 "#33cc8c"와 같은 Tk 색상 지정 문자열인 colorstring으로 설정합니다.

fillcolor((r, g, b))

채우기 색상을 r, gb의 튜플로 표현되는 RGB 색상으로 설정합니다. r, gb 각각은 0..colormode 범위에 있어야 합니다. 여기서 colormode는 1.0이나 255입니다 (colormode()를 참조하십시오).

fillcolor(r, g, b)

채우기 색상을 r, gb로 표현되는 RGB 색상으로 설정합니다. r, gb는 각각 0..colormode 범위에 있어야 합니다.

거북이 모양이 다각형이면, 해당 다각형의 내부는 새로 설정된 채우기 색상으로 그려집니다.

>>> turtle.fillcolor("violet")
>>> turtle.fillcolor()
'violet'
>>> turtle.pencolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor((50, 193, 143))  # Integers, not floats
>>> turtle.fillcolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor('#ffffff')
>>> turtle.fillcolor()
(255.0, 255.0, 255.0)
turtle.color(*args)

펜 색상과 채우기 색상을 반환하거나 설정합니다.

몇 가지 입력 형식이 허용됩니다. 다음과 같이 0에서 3개의 인자를 사용합니다:

color()

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

color(colorstring), color((r,g,b)), color(r,g,b)

pencolor()에서와 같은 입력, 채우기 색상과 펜 색상을 모두 주어진 값으로 설정합니다.

color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2))

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

거북이 모양이 다각형이면, 해당 다각형의 외곽선과 내부가 새로 설정된 색상으로 그려집니다.

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

채우기 상태(fillstate)를 반환합니다 (채우면 True, 그렇지 않으면 False).

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

채울 모양을 그리기 직전에 호출됩니다.

turtle.end_fill()

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

스스로 교차하는 다각형이나 여러 도형의 겹치는 영역이 채워지는지는 운영 체제 그래픽, 겹침의 유형 및 겹침의 수에 따라 다릅니다. 예를 들어, 위의 거북이 별은 모두 노란색이거나 일부 흰색 영역이 있을 수 있습니다.

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

더 많은 그리기 제어

turtle.reset()

화면에서 거북이의 그림을 삭제하고, 거북이를 다시 중심으로 옮기고, 변수를 기본값으로 설정합니다.

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

화면에서 거북이 그림을 삭제합니다. 거북이를 움직이지 않습니다. 다른 거북이의 그림뿐만 아니라 거북이의 상태와 위치는 영향을 받지 않습니다.

turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal'))
매개변수:
  • arg – TurtleScreen에 기록될 객체

  • move – True/False

  • align – “left”, “center” 또는 “right” 문자열 중 하나

  • font – 3-튜플 (fontname, fontsize, fonttype)

align(“left”, “center” 또는 “right”)에 따라 현재 거북이 위치에서 주어진 글꼴(font)로 텍스트 - arg의 문자열 표현 - 를 기록합니다. move가 참이면, 펜이 텍스트의 오른쪽 아래 모서리로 이동합니다. 기본적으로, moveFalse입니다.

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

거북이 상태

가시성

turtle.hideturtle()
turtle.ht()

거북이를 보이지 않게 합니다. 거북이를 숨기면 그리기 속도가 눈에 띄게 빨라지므로, 복잡한 그리기를 하는 동안 이렇게 하는 것이 좋습니다.

>>> turtle.hideturtle()
turtle.showturtle()
turtle.st()

거북이가 보이게 합니다.

>>> turtle.showturtle()
turtle.isvisible()

거북이가 보이면 True를, 숨겨져 있으면 False를 반환합니다.

>>> turtle.hideturtle()
>>> turtle.isvisible()
False
>>> turtle.showturtle()
>>> turtle.isvisible()
True

외관

turtle.shape(name=None)
매개변수:

name – 유효한 모양 이름(shapename)인 문자열

주어진 name의 모양으로 거북이 모양을 설정하거나, 이름이 없으면 현재 모양의 이름을 반환합니다. name의 모양은 TurtleScreen의 모양 딕셔너리에 있어야 합니다. 처음에는 다음과 같은 다각형 모양이 있습니다: “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”. 모양을 다루는 방법에 대한 자세한 내용은 Screen 메서드 register_shape()을 참조하십시오.

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

rmode – 문자열 “auto”, “user”, “noresize” 중 하나

크기 조정 모드(resizemode)를 다음 값 중 하나로 설정합니다: “auto”, “user”, “noresize”. rmode가 제공되지 않으면, 현재 크기 조정 모드를 반환합니다. 각 크기 조정 모드는 다음과 같은 효과가 있습니다:

  • “auto”: 펜 크기(pensize)의 값에 맞춰 거북이의 외관을 조정합니다.

  • “user”: shapesize()로 설정된 stretchfactor와 outlinewidth (outline) 값에 따라 거북이의 외관을 조정합니다.

  • “noresize”: 거북이의 외관 조정이 일어나지 않습니다.

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 – 양수

  • stretch_len – 양수

  • outline – 양수

Return or set the pen’s attributes x/y-stretchfactors and/or outline. Set resizemode to “user”. If and only if resizemode is set to “user”, the turtle will be displayed stretched according to its stretchfactors: stretch_wid is stretchfactor perpendicular to its orientation, stretch_len is stretchfactor in direction of its orientation, outline determines the width of the shape’s outline.

>>> turtle.shapesize()
(1.0, 1.0, 1)
>>> turtle.resizemode("user")
>>> turtle.shapesize(5, 5, 12)
>>> turtle.shapesize()
(5, 5, 12)
>>> turtle.shapesize(outline=8)
>>> turtle.shapesize()
(5, 5, 8)
turtle.shearfactor(shear=None)
매개변수:

shear – 숫자 (선택 사항)

기울기 계수(shearfactor)를 설정하거나 반환합니다. 주어진 기울기 계수 shear(기울기 각의 탄젠트입니다)에 따라 거북이 모양을 기울입니다. 거북이의 방향(이동 방향)을 변경하지 않습니다. shear가 제공되지 않으면: 현재 기울기 계수(shearfactor)를, 즉 기울기 각도의 탄젠트를 반환합니다. 기울기 각도는 거북이의 방향에 평행한 직선이 기울어진 각도입니다.

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

angle – 숫자

현재 틸트 각도(tilt-angle)에서 거북이 모양을 angle만큼 회전합니다. 그러나 거북이의 방향(이동 방향)을 변경하지 않습니다.

>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(30)
>>> turtle.fd(50)
>>> turtle.tilt(30)
>>> turtle.fd(50)
turtle.settiltangle(angle)
매개변수:

angle – 숫자

현재 틸트 각도(tilt-angle)와 관계없이 거북이 모양을 angle이 지정하는 방향을 가리키도록 회전합니다. 거북이의 방향(이동 방향)을 변경하지 않습니다.

>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.settiltangle(45)
>>> turtle.fd(50)
>>> turtle.settiltangle(-45)
>>> turtle.fd(50)

버전 3.1부터 폐지됨.

turtle.tiltangle(angle=None)
매개변수:

angle – 숫자 (선택 사항)

현재 틸트 각도(tilt-angle)를 설정하거나 반환합니다. angle이 주어지면, 현재 틸트 각도(tilt-angle)와 관계없이 거북이 모양을 angle이 지정하는 방향을 가리키도록 회전합니다. 거북이의 방향(이동 방향)을 변경하지 않습니다. 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 – 숫자 (선택 사항)

  • t12 – 숫자 (선택 사항)

  • t21 – 숫자 (선택 사항)

  • t12 – 숫자 (선택 사항)

거북이 모양의 현재 변환 행렬을 설정하거나 반환합니다.

행렬 요소가 아무것도 제공되지 않으면, 변환 행렬을 4개 요소의 튜플로 반환합니다. 그렇지 않으면, 주어진 요소를 설정하고 첫 번째 행 t11, t12와 두 번째 행 t21, t22로 구성된 행렬에 따라 거북이 모양을 변환합니다. 행렬식(determinant) t11 * t22 - t12 * t21은 0이 아니어야 합니다, 그렇지 않으면 에러가 발생합니다. 주어진 행렬에 따라 신축 계수(stretchfactor), 기울기 계수(shearfactor) 및 틸트 각도(tiltangle)를 수정합니다.

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

현재 모양 다각형을 좌표 쌍의 튜플로 반환합니다. 이것은 새로운 모양이나 복합 모양의 구성 요소를 정의하는 데 사용할 수 있습니다.

>>> 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 – 캔버스에서 클릭한 점의 좌표로 호출되는 두 개의 인자가 있는 함수

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

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

이 거북이의 마우스 클릭 이벤트에 fun을 연결합니다. funNone이면 기존 연결이 제거됩니다. 익명의 거북이, 즉 절차적 방법의 예:

>>> def turn(x, y):
...     left(180)
...
>>> onclick(turn)  # Now clicking into the turtle will turn it.
>>> onclick(None)  # event-binding will be removed
turtle.onrelease(fun, btn=1, add=None)
매개변수:
  • fun – 캔버스에서 클릭한 점의 좌표로 호출되는 두 개의 인자가 있는 함수

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

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

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

>>> class MyTurtle(Turtle):
...     def glow(self,x,y):
...         self.fillcolor("red")
...     def unglow(self,x,y):
...         self.fillcolor("")
...
>>> turtle = MyTurtle()
>>> turtle.onclick(turtle.glow)     # clicking on turtle turns fillcolor red,
>>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
turtle.ondrag(fun, btn=1, add=None)
매개변수:
  • fun – 캔버스에서 클릭한 점의 좌표로 호출되는 두 개의 인자가 있는 함수

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

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

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

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

>>> turtle.ondrag(turtle.goto)

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

특수 Turtle 메서드

turtle.begin_poly()

다각형의 꼭짓점 기록을 시작합니다. 현재 거북이 위치가 다각형의 첫 번째 꼭짓점입니다.

turtle.end_poly()

다각형의 꼭짓점 기록을 중지합니다. 현재 거북이 위치가 다각형의 마지막 꼭짓점입니다. 첫 번째 꼭짓점과 연결됩니다.

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

같은 위치, 방향 및 거북이 속성을 가진 거북이 복제본을 만들고 반환합니다.

>>> mick = Turtle()
>>> joe = mick.clone()
turtle.getturtle()
turtle.getpen()

거북이 객체 자체를 반환합니다. 합리적인 용도로만 사용하십시오: “익명 거북이”를 반환하는 함수로:

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

언두버퍼(undobuffer)를 설정하거나 비활성화합니다. size가 정수이면, 지정된 크기의 빈 언두버퍼가 설치됩니다. sizeundo() 메서드/함수로 취소할 수 있는 최대 거북이 액션 수를 제공합니다. sizeNone이면, 언두버퍼가 비활성화됩니다.

>>> turtle.setundobuffer(42)
turtle.undobufferentries()

언두버퍼에 있는 항목 수를 반환합니다.

>>> while undobufferentries():
...     undo()

복합 모양

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

  1. “compound” 유형의 빈 Shape 객체를 만듭니다.

  2. Add as many components to this object as desired, using the addcomponent() method.

    예를 들면:

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

참고

Shape 클래스는 register_shape() 메서드에 의해 내부적으로 다른 방식으로 사용됩니다. 응용 프로그램 프로그래머는 위와 같이 복합 모양을 사용할 때 Shape 클래스를 다뤄야 합니다!

TurtleScreen/Screen 메서드와 해당 함수

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

창 제어

turtle.bgcolor(*args)
매개변수:

args – 색상 문자열이나 0..colormode 범위의 3개의 숫자 또는 이러한 숫자의 3-튜플

TurtleScreen의 배경색을 설정하거나 반환합니다.

>>> screen.bgcolor("orange")
>>> screen.bgcolor()
'orange'
>>> screen.bgcolor("#800080")
>>> screen.bgcolor()
(128.0, 0.0, 128.0)
turtle.bgpic(picname=None)
매개변수:

picname – 문자열, gif 파일의 이름 또는 "nopic", 또는 None

배경 이미지를 설정하거나 현재 배경 이미지(backgroundimage)의 이름을 반환합니다. picname이 파일명이면, 해당 이미지를 배경으로 설정합니다. picname"nopic"이면, 배경 이미지가 있다면 삭제합니다. picnameNone이면, 현재 배경 이미지(backgroundimage)의 파일명을 반환합니다.

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

Screen의 모든 거북이를 초기 상태로 재설정합니다.

turtle.screensize(canvwidth=None, canvheight=None, bg=None)
매개변수:
  • canvwidth – 양의 정수, 픽셀 단위의 새 캔버스 너비

  • canvheight – 양의 정수, 픽셀 단위의 새 캔버스 높이

  • bg – 색상 문자열(colorstring)이나 색상 튜플, 새 배경색

인자가 제공되지 않으면, 현재 (canvaswidth, canvasheight)를 반환합니다. 그렇지 않으면 거북이가 그리는 캔버스의 크기를 조정합니다. 그리는 창을 변경하지 마십시오. 캔버스의 숨겨진 부분을 보려면, 스크롤 막대를 사용하십시오. 이 메서드를 사용하면, 이전에 캔버스 외부에 있던 그림의 부분을 볼 수 있습니다.

>>> screen.screensize()
(400, 300)
>>> screen.screensize(2000,1500)
>>> screen.screensize()
(2000, 1500)

예를 들어 잘못 탈출한 거북이를 찾기 위해 ;-)

turtle.setworldcoordinates(llx, lly, urx, ury)
매개변수:
  • llx – 숫자, 캔버스의 왼쪽 아래 모서리의 x-좌표

  • lly – 숫자, 캔버스의 왼쪽 아래 모서리의 y-좌표

  • urx – 숫자, 캔버스의 오른쪽 상단 모서리의 x-좌표

  • ury – 숫자, 캔버스의 오른쪽 상단 모서리의 y-좌표

사용자 정의 좌표계를 설정하고 필요하면 “world” 모드로 전환합니다. 이것은 screen.reset()을 수행합니다. “world” 모드가 이미 활성화되었으면, 모든 그림은 새 좌표에 따라 다시 그려집니다.

주의: 사용자 정의 좌표계에서 각도가 왜곡되어 나타날 수 있습니다.

>>> screen.reset()
>>> screen.setworldcoordinates(-50,-7.5,50,7.5)
>>> for _ in range(72):
...     left(10)
...
>>> for _ in range(8):
...     left(45); fd(2)   # a regular octagon

애니메이션 제어

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

delay – 양의 정수

그리기 지연(delay)을 밀리초 단위로 설정하거나 반환합니다. (이는 대략 두 개의 연속 캔버스 갱신 사이의 시간 간격입니다.) 그리기 지연이 길수록, 애니메이션이 느려집니다.

선택적 인자:

>>> screen.delay()
10
>>> screen.delay(5)
>>> screen.delay()
5
turtle.tracer(n=None, delay=None)
매개변수:
  • n – 음이 아닌 정수

  • delay – 음이 아닌 정수

거북이 애니메이션을 켜거나 끄고 그림 갱신 지연을 설정합니다. n이 제공되면, n 번째 정기 화면 갱신만 실제로 수행됩니다. (복잡한 그래픽의 그리기를 가속하는 데 사용할 수 있습니다.) 인자 없이 호출되면, 현재 저장된 n 값을 반환합니다. 두 번째 인자는 지연(delay) 값을 설정합니다 (delay()를 참조하십시오).

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

(키 이벤트를 수집하기 위해) TurtleScreen에 포커스를 설정합니다. listen()을 onclick 메서드에 전달할 수 있도록 더미 인자가 제공됩니다.

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

  • key – 문자열: 키 (예를 들어 “a”) 또는 키-기호 (예를 들어 “space”)

key의 키-릴리스 이벤트에 fun을 연결합니다. funNone이면, 이벤트 연결이 제거됩니다. 비고: 키 이벤트를 등록하려면, TurtleScreen에 포커스가 있어야 합니다. (메서드 listen()을 참조하십시오.)

>>> def f():
...     fd(50)
...     lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
turtle.onkeypress(fun, key=None)
매개변수:
  • fun – 인자가 없는 함수나 None

  • key – 문자열: 키 (예를 들어 “a”) 또는 키-기호 (예를 들어 “space”)

key가 제공되면 key의 키-누르기 이벤트에 또는 key를 제공하지 않으면 임의의 키 누르기 이벤트에 fun을 연결합니다. 비고: 키 이벤트를 등록하려면, TurtleScreen에 포커스가 있어야 합니다. (메서드 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)
매개변수:
  • fun – 캔버스에서 클릭한 점의 좌표로 호출되는 두 개의 인자가 있는 함수

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

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

이 화면의 마우스-클릭 이벤트에 fun을 연결합니다. funNone이면, 기존 연결이 제거됩니다.

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

>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>>                             # make the turtle move to the clicked point.
>>> screen.onclick(None)        # remove event binding again

참고

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

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

  • t – 숫자 >= 0

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

이벤트 루프를 시작합니다 - Tkinter의 mainloop 함수를 호출합니다. 터틀 그래픽 프로그램의 마지막 문장이어야 합니다. 터틀 그래픽을 대화식으로 사용하기 위해 -n 모드(서브 프로세스 없음)로 IDLE에서 스크립트를 실행할 때는 사용되지 않아야 합니다.

>>> screen.mainloop()

입력 메서드

turtle.textinput(title, prompt)
매개변수:
  • title – 문자열

  • prompt – 문자열

문자열 입력을 위한 대화 상자 창을 띄웁니다. 매개변수 title은 대화 상자 창의 제목이고, prompt는 주로 어떤 정보를 입력해야 하는지 설명하는 텍스트입니다. 문자열 입력을 반환합니다. 대화 상자가 취소되면, None을 반환합니다.

>>> screen.textinput("NIM", "Name of first player:")
turtle.numinput(title, prompt, default=None, minval=None, maxval=None)
매개변수:
  • title – 문자열

  • prompt – 문자열

  • default – 숫자 (선택 사항)

  • minval – 숫자 (선택 사항)

  • maxval – 숫자 (선택 사항)

Pop up a dialog window for input of a number. title is the title of the dialog window, prompt is a text mostly describing what numerical information to input. default: default value, minval: minimum value for input, maxval: maximum value for input. The number input must be in the range minval .. maxval if these are given. If not, a hint is issued and the dialog remains open for correction. Return the number input. If the dialog is canceled, return None.

>>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)

설정과 특수 메서드

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

mode – 문자열 “standard”, “logo” 또는 “world” 중 하나

거북이 모드(“standard”, “logo” 또는 “world”)를 설정하고 재설정을 수행합니다. mode가 제공되지 않으면, 현재 모드가 반환됩니다.

“standard” 모드는 이전 turtle과 호환됩니다. “logo” 모드는 대부분의 로고 터틀 그래픽과 호환됩니다. “world” 모드는 사용자 정의 “세계 좌표”를 사용합니다. 주의: 이 모드에서는 x/y 단위 비율이 1이 아니면 각도가 왜곡되어 나타납니다.

모드

초기 거북이 방향

양의 각도

“standard”

오른쪽 (동)

시계 반대 방향

“logo”

위쪽 (북)

시계 방향

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

cmode – 값 1.0이나 255중 하나

Return the colormode or set it to 1.0 or 255. Subsequently r, g, b values of color triples have to be in the range 0..*cmode*.

>>> screen.colormode(1)
>>> turtle.pencolor(240, 160, 80)
Traceback (most recent call last):
     ...
TurtleGraphicsError: bad color sequence: (240, 160, 80)
>>> screen.colormode()
1.0
>>> screen.colormode(255)
>>> screen.colormode()
255
>>> turtle.pencolor(240,160,80)
turtle.getcanvas()

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

이 함수를 호출하는 방법에는 세 가지가 있습니다:

  1. name은 gif 파일의 이름이고 shapeNone입니다: 해당 이미지 모양을 설치합니다.

    >>> screen.register_shape("turtle.gif")
    

    참고

    거북이를 회전할 때 이미지 모양은 회전하지 않아서, 거북이 방향을 표시하지 않습니다!

  2. name은 임의의 문자열이고 shape은 좌표 쌍의 튜플입니다: 해당 다각형 모양을 설치합니다.

    >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
    
  3. name is an arbitrary string and shape is a (compound) Shape object: Install the corresponding compound shape.

TurtleScreen의 모양 리스트(shapelist)에 거북이 모양을 추가합니다. shape(shapename) 명령을 실행하면 이처럼 등록된 모양만 사용할 수 있습니다.

turtle.turtles()

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

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

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

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

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

>>> screen.window_width()
640

TurtleScreen에서 상속되지 않은, Screen만의 메서드

turtle.bye()

터틀 그래픽 창을 닫습니다.

turtle.exitonclick()

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

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

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

titlestring – 터틀 그래픽 창의 제목 표시 줄에 표시되는 문자열

거북이 창의 제목을 titlestring으로 설정합니다.

>>> screen.title("Welcome to the turtle zoo!")

공개 클래스

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

canvas – a tkinter.Canvas, a ScrolledCanvas or a TurtleScreen

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

class turtle.Turtle

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

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

cv – a tkinter.Canvas

Provides screen oriented methods like bgcolor() etc. that are described above.

class turtle.Screen

TurtleScreen의 서브 클래스. 4개의 메서드가 추가되었습니다.

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

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

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

class turtle.Shape(type_, data)
매개변수:

type_ – 문자열 “polygon”, “image”, “compound” 중 하나

모양을 모델링하는 데이터 구조. 쌍 (type_, data)는 다음 명세를 따라야 합니다:

type_

data

“polygon”

다각형 튜플, 즉 좌표 쌍의 튜플

“image”

이미지 (이 형식은 내부적으로만 사용됩니다!)

“compound”

None (복합 모양을 addcomponent() 메서드를 사용하여 구성해야 합니다)

addcomponent(poly, fill, outline=None)
매개변수:
  • poly – 다각형, 즉 숫자 쌍의 튜플

  • fillpoly가 채워질 색상

  • outline – poly 외곽선의 색상 (제공되면)

예:

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

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

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

  • a + b 벡터 덧셈

  • a - b 벡터 뺄셈

  • a * b 내적(inner product)

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

  • abs(a) a의 절댓값

  • a.rotate(angle) 회전

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.

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.

도움말과 구성

도움말 사용법

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에 기록됩니다. 독스트링을 다른 언어로 번역하기 위한 템플릿으로 사용하려는 목적입니다.

여러분(또는 여러분의 학생)이 모국어로 된 온라인 도움말과 함께 turtle을 사용하려면, 독스트링을 번역하고 결과 파일을 예를 들어 turtle_docstringdict_german.py와 같은 파일로 저장해야 합니다.

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

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

Screen과 Turtle을 구성하는 방법

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

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

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

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

  • The first four lines correspond to the arguments of the Screen.setup method.

  • Line 5 and 6 correspond to the arguments of the method Screen.screensize.

  • shape은 내장 도형 중 하나일 수 있습니다, 예를 들어 arrow, turtle 등. 자세한 정보는 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).

  • 거북이의 상태를 반영하려면, 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).

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

  • using_IDLE: Set this to True if you regularly work with IDLE and its -n switch (“no subprocess”). This will prevent exitonclick() to enter the mainloop.

turtle이 저장된 디렉터리에 turtle.cfg 파일이 있고 현재 작업 디렉터리에도 추가 파일이 있을 수 있습니다. 후자가 첫 번째 설정을 재정의합니다.

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

turtledemo — 데모 스크립트

turtledemo 패키지에는 데모 스크립트 집합이 포함되어 있습니다. 이 스크립트는 다음과 같이 제공된 데모 뷰어를 사용하여 실행하고 볼 수 있습니다:

python -m turtledemo

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

python -m turtledemo.bytedesign

turtledemo 패키지 디렉터리는 다음과 같은 것들을 포함합니다:

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

  • turtle 모듈의 다른 기능을 보여주는 여러 스크립트. 예제는 Examples 메뉴를 통해 액세스할 수 있습니다. 독립형으로 실행할 수도 있습니다.

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

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

이름

설명

기능

bytedesign

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

tracer(), delay, update()

chaos

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

세계 좌표

clock

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

시곗바늘 거북이, ontimer

colormixer

r, g, b 실험

ondrag()

forest

3개의 너비 우선 나무

무작위화

fractalcurves

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

재귀

lindenmayer

민족 수학 (인도 콜람)

L-System

minimal_hanoi

하노이의 탑

하노이 디스크로 쓰는 직사각형 거북 (모양, 모양 크기)

nim

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

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

paint

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

onclick()

peace

기초

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

penrose

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

stamp()

planet_and_moon

중력 시스템 시뮬레이션

복합 모양, Vec2D

rosette

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

clone(), undo()

round_dance

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

복합 모양, 모양 크기 복제, tilt, get_shapepoly, update

sorting_animate

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

간단한 정렬, 무작위화

tree

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

clone()

two_canvases

간단한 디자인

두 캔버스의 거북이

yinyang

또 하나의 기초 예제

circle()

즐기세요!

파이썬 2.6 이후의 변화

  • The methods Turtle.tracer, Turtle.window_width and Turtle.window_height have been eliminated. Methods with these names and functionality are now available only as methods of Screen. The functions derived from these remain available. (In fact already in Python 2.6 these methods were merely duplications of the corresponding TurtleScreen/Screen methods.)

  • The method Turtle.fill() has been eliminated. The behaviour of begin_fill() and end_fill() have changed slightly: now every filling process must be completed with an end_fill() call.

  • A method Turtle.filling has been added. It returns a boolean value: True if a filling process is under way, False otherwise. This behaviour corresponds to a fill() call without arguments in Python 2.6.

파이썬 3.0 이후의 변화

  • The Turtle methods shearfactor(), shapetransform() and get_shapepoly() have been added. Thus the full range of regular linear transforms is now available for transforming turtle shapes. tiltangle() has been enhanced in functionality: it now can be used to get or set the tilt angle. settiltangle() has been deprecated.

  • The Screen method onkeypress() has been added as a complement to onkey(). As the latter binds actions to the key release event, an alias: onkeyrelease() was also added for it.

  • The method Screen.mainloop has been added, so there is no longer a need to use the standalone mainloop() function when working with Screen and Turtle objects.

  • Two input methods have been added: Screen.textinput and Screen.numinput. These pop up input dialogs and return strings and numbers respectively.

  • tdemo_nim.pytdemo_round_dance.py의 두 가지 예제 스크립트가 Lib/turtledemo 디렉터리에 추가되었습니다.