turtle --- 海龜繪圖?

源碼: Lib/turtle.py


概述?

海龜繪圖很適合用來(lái)引導孩子學(xué)習編程。 最初來(lái)自于 Wally Feurzeig, Seymour Papert 和 Cynthia Solomon 于 1967 年所創(chuàng )造的 Logo 編程語(yǔ)言。

請想象繪圖區有一只機器海龜,起始位置在 x-y 平面的 (0, 0) 點(diǎn)。先執行 import turtle,再執行 turtle.forward(15),它將(在屏幕上)朝所面對的 x 軸正方向前進(jìn) 15 像素,隨著(zhù)它的移動(dòng)畫(huà)出一條線(xiàn)段。再執行 turtle.right(25),它將原地右轉 25 度。

通過(guò)組合使用此類(lèi)命令,可以輕松地繪制出精美的形狀和圖案。

turtle 模塊是基于 Python 標準發(fā)行版 2.5 以來(lái)的同名模塊重新編寫(xiě)并進(jìn)行了功能擴展。

新模塊盡量保持了原模塊的特點(diǎn),并且(幾乎)100%與其兼容。這就意味著(zhù)初學(xué)編程者能夠以交互方式使用模塊的所有命令、類(lèi)和方法——運行 IDLE 時(shí)注意加 -n 參數。

turtle 模塊提供面向對象和面向過(guò)程兩種形式的海龜繪圖基本組件。由于它使用 tkinter 實(shí)現基本圖形界面,因此需要安裝了 Tk 支持的 Python 版本。

面向對象的接口主要使用“2+2”個(gè)類(lèi):

  1. TurtleScreen 類(lèi)定義圖形窗口作為繪圖海龜的運動(dòng)場(chǎng)。它的構造器需要一個(gè) tkinter.CanvasScrolledCanvas 作為參數。應在 turtle 作為某個(gè)程序的一部分的時(shí)候使用。

    Screen() 函數返回一個(gè) TurtleScreen 子類(lèi)的單例對象。此函數應在 turtle 作為獨立繪圖工具時(shí)使用。作為一個(gè)單例對象,其所屬的類(lèi)是不可被繼承的。

    TurtleScreen/Screen 的所有方法還存在對應的函數,即作為面向過(guò)程的接口組成部分。

  2. RawTurtle (別名: RawPen) 類(lèi)定義海龜對象在 TurtleScreen 上繪圖。它的構造器需要一個(gè) Canvas, ScrolledCanvas 或 TurtleScreen 作為參數,以指定 RawTurtle 對象在哪里繪圖。

    從 RawTurtle 派生出子類(lèi) Turtle (別名: Pen),該類(lèi)對象在 Screen 實(shí)例上繪圖,如果實(shí)例不存在則會(huì )自動(dòng)創(chuàng )建。

    RawTurtle/Turtle 的所有方法也存在對應的函數,即作為面向過(guò)程的接口組成部分。

過(guò)程式接口提供與 ScreenTurtle 類(lèi)的方法相對應的函數。函數名與對應的方法名相同。當 Screen 類(lèi)的方法對應函數被調用時(shí)會(huì )自動(dòng)創(chuàng )建一個(gè) Screen 對象。當 Turtle 類(lèi)的方法對應函數被調用時(shí)會(huì )自動(dòng)創(chuàng )建一個(gè) (匿名的) Turtle 對象。

如果屏幕上需要有多個(gè)海龜,就必須使用面向對象的接口。

備注

以下文檔給出了函數的參數列表。對于方法來(lái)說(shuō)當然還有額外的第一個(gè)參數 self,這里省略了。

可用的 Turtle 和 Screen 方法概覽?

Turtle 方法?

海龜動(dòng)作
移動(dòng)和繪制
forward() | fd() 前進(jìn)
right() | rt() 右轉
left() | lt() 左轉
goto() | setpos() | setposition() 前往/定位
setx() 設置x坐標
sety() 設置y坐標
setheading() | seth() 設置朝向
home() 返回原點(diǎn)
circle() 畫(huà)圓
dot() 畫(huà)點(diǎn)
stamp() 印章
clearstamp() 清除印章
clearstamps() 清除多個(gè)印章
undo() 撤消
speed() 速度
獲取海龜的狀態(tài)
position() | pos() 位置
towards() 目標方向
xcor() x坐標
ycor() y坐標
heading() 朝向
distance() 距離
設置與度量單位
degrees() 角度
radians() 弧度
畫(huà)筆控制
繪圖狀態(tài)
pendown() | pd() | down() 畫(huà)筆落下
penup() | pu() | up() 畫(huà)筆抬起
pensize() | width() 畫(huà)筆粗細
pen() 畫(huà)筆
isdown() 畫(huà)筆是否落下
顏色控制
color() 顏色
pencolor() 畫(huà)筆顏色
fillcolor() 填充顏色
填充
filling() 是否填充
begin_fill() 開(kāi)始填充
end_fill() 結束填充
更多繪圖控制
reset() 重置
clear() 清空
write() 書(shū)寫(xiě)
海龜狀態(tài)
可見(jiàn)性
showturtle() | st() 顯示海龜
hideturtle() | ht() 隱藏海龜
isvisible() 是否可見(jiàn)
外觀(guān)
shape() 形狀
resizemode() 大小調整模式
shapesize() | turtlesize() 形狀大小
shearfactor() 剪切因子
settiltangle() 設置傾角
tilt() 傾斜
get_shapepoly() 獲取形狀多邊形
使用事件
onclick() 當鼠標點(diǎn)擊
onrelease() 當鼠標釋放
ondrag() 當鼠標拖動(dòng)
特殊海龜方法
begin_poly() 開(kāi)始記錄多邊形
end_poly() 結束記錄多邊形
get_poly() 獲取多邊形
clone() 克隆
getturtle() | getpen() 獲取海龜畫(huà)筆
getscreen() 獲取屏幕
setundobuffer() 設置撤消緩沖區
undobufferentries() 撤消緩沖區條目數

TurtleScreen/Screen 方法?

窗口控制
bgcolor() 背景顏色
bgpic() 背景圖片
screensize() 屏幕大小
setworldcoordinates() 設置世界坐標系
動(dòng)畫(huà)控制
delay() 延遲
tracer() 追蹤
update() 更新
使用屏幕事件
listen() 監聽(tīng)
onkey() | onkeyrelease() 當鍵盤(pán)按下并釋放
onkeypress() 當鍵盤(pán)按下
onclick() | onscreenclick() 當點(diǎn)擊屏幕
ontimer() 當達到定時(shí)
mainloop() | done() 主循環(huán)
設置與特殊方法
colormode() 顏色模式
getcanvas() 獲取畫(huà)布
getshapes() 獲取形狀
turtles() 所有海龜
window_height() 窗口高度
window_width() 窗口寬度
輸入方法
textinput() 文本輸入
numinput() 數字輸入
Screen 專(zhuān)有方法
bye() 退出
exitonclick() 當點(diǎn)擊時(shí)退出
setup() 設置
title() 標題

RawTurtle/Turtle 方法和對應函數?

本節中的大部分示例都使用 Turtle 類(lèi)的一個(gè)實(shí)例,命名為 turtle。

海龜動(dòng)作?

turtle.forward(distance)?
turtle.fd(distance)?
參數

distance -- 一個(gè)數值 (整型或浮點(diǎn)型)

海龜前進(jìn) 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 -- 一個(gè)數值

海龜后退 distance 指定的距離,方向與海龜的朝向相反。不改變海龜的朝向。

>>>
>>> turtle.position()
(0.00,0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00,0.00)
turtle.right(angle)?
turtle.rt(angle)?
參數

angle -- 一個(gè)數值 (整型或浮點(diǎn)型)

海龜右轉 angle 個(gè)單位。(單位默認為角度,但可通過(guò) degrees()radians() 函數改變設置。) 角度的正負由海龜模式確定,參見(jiàn) mode()。

>>>
>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0
turtle.left(angle)?
turtle.lt(angle)?
參數

angle -- 一個(gè)數值 (整型或浮點(diǎn)型)

海龜左轉 angle 個(gè)單位。(單位默認為角度,但可通過(guò) degrees()radians() 函數改變設置。) 角度的正負由海龜模式確定,參見(jiàn) 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 -- 一個(gè)數值或數值對/向量

  • y -- 一個(gè)數值或 None

如果 yNone,x 應為一個(gè)表示坐標的數值對或 Vec2D 類(lèi)對象 (例如 pos() 返回的對象).

海龜移動(dòng)到一個(gè)絕對坐標。如果畫(huà)筆已落下將會(huì )畫(huà)線(xiàn)。不改變海龜的朝向。

 >>> tp = turtle.pos()
 >>> tp
 (0.00,0.00)
 >>> turtle.setpos(60,30)
 >>> turtle.pos()
 (60.00,30.00)
 >>> turtle.setpos((20,80))
 >>> turtle.pos()
 (20.00,80.00)
 >>> turtle.setpos(tp)
 >>> turtle.pos()
 (0.00,0.00)
turtle.setx(x)?
參數

x -- 一個(gè)數值 (整型或浮點(diǎn)型)

設置海龜的橫坐標為 x,縱坐標保持不變。

>>>
>>> turtle.position()
(0.00,240.00)
>>> turtle.setx(10)
>>> turtle.position()
(10.00,240.00)
turtle.sety(y)?
參數

y -- 一個(gè)數值 (整型或浮點(diǎn)型)

設置海龜的縱坐標為 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 -- 一個(gè)數值 (整型或浮點(diǎn)型)

設置海龜的朝向為 to_angle。以下是以角度表示的幾個(gè)常用方向:

標準模式

logo 模式

0 - 東

0 - 北

90 - 北

90 - 東

180 - 西

180 - 南

270 - 南

270 - 西

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

海龜移至初始坐標 (0,0),并設置朝向為初始方向 (由海龜模式確定,參見(jiàn) 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 -- 一個(gè)數值

  • extent -- 一個(gè)數值 (或 None)

  • steps -- 一個(gè)整型數 (或 None)

繪制一個(gè) radius 指定半徑的圓。圓心在海龜左邊 radius 個(gè)單位;extent 為一個(gè)夾角,用來(lái)決定繪制圓的一部分。如未指定 extent*則繪制整個(gè)圓。如果 *extent 不是完整圓周,則以當前畫(huà)筆位置為一個(gè)端點(diǎn)繪制圓弧。如果 radius 為正值則朝逆時(shí)針?lè )较蚶L制圓弧,否則朝順時(shí)針?lè )较?。最終海龜的朝向會(huì )依據 extent 的值而改變。

圓實(shí)際是以其內切正多邊形來(lái)近似表示的,其邊的數量由 steps 指定。如果未指定邊數則會(huì )自動(dòng)確定。此方法也可用來(lái)繪制正多邊形。

>>>
>>> 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 -- 一個(gè)整型數 >= 1 (如果指定)

  • color -- 一個(gè)顏色字符串或顏色數值元組

繪制一個(gè)直徑為 size,顏色為 color 的圓點(diǎn)。如果 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()?

在海龜當前位置印制一個(gè)海龜形狀。返回該印章的 stamp_id,印章可以通過(guò)調用 clearstamp(stamp_id) 來(lái)刪除。

>>>
>>> turtle.color("blue")
>>> turtle.stamp()
11
>>> turtle.fd(50)
turtle.clearstamp(stampid)?
參數

stampid -- 一個(gè)整型數,必須是之前 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 -- 一個(gè)整型數 (或 None)

刪除全部或前/后 n 個(gè)海龜印章。如果 nNone 則刪除全部印章,如果 n > 0 則刪除前 n 個(gè)印章,否則如果 n < 0 則刪除后 n 個(gè)印章。

>>>
>>> for i in range(8):
...     turtle.stamp(); turtle.fd(30)
13
14
15
16
17
18
19
20
>>> turtle.clearstamps(2)
>>> turtle.clearstamps(-2)
>>> turtle.clearstamps()
turtle.undo()?

撤消 (或連續撤消) 最近的一個(gè) (或多個(gè)) 海龜動(dòng)作??沙废拇螖涤沙废彌_區的大小決定。

>>>
>>> for i in range(4):
...     turtle.fd(50); turtle.lt(80)
...
>>> for i in range(8):
...     turtle.undo()
turtle.speed(speed=None)?
參數

speed -- 一個(gè) 0..10 范圍內的整型數或速度字符串 (見(jiàn)下)

設置海龜移動(dòng)的速度為 0..10 表示的整型數值。如未指定參數則返回當前速度。

如果輸入數值大于 10 或小于 0.5 則速度設為 0。速度字符串與速度值的對應關(guān)系如下:

  • "fastest": 0 最快

  • "fast": 10 快

  • "normal": 6 正常

  • "slow": 3 慢

  • "slowest": 1 最慢

速度值從 1 到 10,畫(huà)線(xiàn)和海龜轉向的動(dòng)畫(huà)效果逐級加快。

注意: speed = 0 表示 沒(méi)有 動(dòng)畫(huà)效果。forward/back 將使海龜向前/向后跳躍,同樣的 left/right 將使海龜立即改變朝向。

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

獲取海龜的狀態(tài)?

turtle.position()?
turtle.pos()?

返回海龜當前的坐標 (x,y) (為 Vec2D 矢量類(lèi)對象)。

>>>
>>> turtle.pos()
(440.00,-0.00)
turtle.towards(x, y=None)?
參數
  • x -- 一個(gè)數值或數值對/矢量,或一個(gè)海龜實(shí)例

  • y -- 一個(gè)數值——如果 x 是一個(gè)數值,否則為 None

返回從海龜位置到由 (x,y)、矢量或另一海龜所確定位置的連線(xiàn)的夾角。 此數值依賴(lài)于海龜的初始朝向,這又取決于 "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()?

返回海龜當前的朝向 (數值依賴(lài)于海龜模式參見(jiàn) mode())。

>>>
>>> turtle.home()
>>> turtle.left(67)
>>> turtle.heading()
67.0
turtle.distance(x, y=None)?
參數
  • x -- 一個(gè)數值或數值對/矢量,或一個(gè)海龜實(shí)例

  • y -- 一個(gè)數值——如果 x 是一個(gè)數值,否則為 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 -- 一個(gè)數值

設置角度的度量單位,即設置一個(gè)圓周為多少 "度"。默認值為 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

畫(huà)筆控制?

繪圖狀態(tài)?

turtle.pendown()?
turtle.pd()?
turtle.down()?

畫(huà)筆落下 -- 移動(dòng)時(shí)將畫(huà)線(xiàn)。

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

畫(huà)筆抬起 -- 移動(dòng)時(shí)不畫(huà)線(xiàn)。

turtle.pensize(width=None)?
turtle.width(width=None)?
參數

width -- 一個(gè)正數值

設置線(xiàn)條的粗細為 width 或返回該值。如果 resizemode 設為 "auto" 并且 turtleshape 為多邊形,該多邊形也以同樣組細的線(xiàn)條繪制。如未指定參數,則返回當前的 pensize。

>>>
>>> turtle.pensize()
1
>>> turtle.pensize(10)   # from here on lines of width 10 are drawn
turtle.pen(pen=None, **pendict)?
參數
  • pen -- 一個(gè)包含部分或全部下列鍵的字典

  • pendict -- 一個(gè)或多個(gè)以下列鍵為關(guān)鍵字的關(guān)鍵字參數

返回或設置畫(huà)筆的屬性,以一個(gè)包含以下鍵值對的 "畫(huà)筆字典" 表示:

  • "shown": True/False

  • "pendown": True/False

  • "pencolor": 顏色字符串或顏色元組

  • "fillcolor": 顏色字符串或顏色元組

  • "pensize": 正數值

  • "speed": 0..10 范圍內的數值

  • "resizemode": "auto" 或 "user" 或 "noresize"

  • "stretchfactor": (正數值, 正數值)

  • "outline": 正數值

  • "tilt": 數值

此字典可作為后續調用 pen() 時(shí)的參數,以恢復之前的畫(huà)筆狀態(tài)。另外還可將這些屬性作為關(guān)鍵詞參數提交。使用此方式可以用一條語(yǔ)句設置畫(huà)筆的多個(gè)屬性。

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

如果畫(huà)筆落下返回 True,如果畫(huà)筆抬起返回 False。

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

顏色控制?

turtle.pencolor(*args)?

返回或設置畫(huà)筆顏色。

允許以下四種輸入格式:

pencolor()

返回以顏色描述字符串或元組 (見(jiàn)示例) 表示的當前畫(huà)筆顏色??捎米髌渌?color/pencolor/fillcolor 調用的輸入。

pencolor(colorstring)

設置畫(huà)筆顏色為 colorstring 指定的 Tk 顏色描述字符串,例如 "red"、"yellow""#33cc8c"。

pencolor((r, g, b))

設置畫(huà)筆顏色為以 r, g, b 元組表示的 RGB 顏色。r, g, b 的取值范圍應為 0..colormode,colormode 的值為 1.0 或 255 (參見(jiàn) colormode())。

pencolor(r, g, b)

設置畫(huà)筆顏色為以 r, g, b 表示的 RGB 顏色。r, g, b 的取值范圍應為 0..colormode。

如果 turtleshape 為多邊形,該多邊形輪廓也以新設置的畫(huà)筆顏色繪制。

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

返回以顏色描述字符串或元組 (見(jiàn)示例) 表示的當前填充顏色??捎米髌渌?color/pencolor/fillcolor 調用的輸入。

fillcolor(colorstring)

設置填充顏色為 colorstring 指定的 Tk 顏色描述字符串,例如 "red"、"yellow""#33cc8c"。

fillcolor((r, g, b))

設置填充顏色為以 r, g, b 元組表示的 RGB 顏色。r, g, b 的取值范圍應為 0..colormode,colormode 的值為 1.0 或 255 (參見(jiàn) colormode())。

fillcolor(r, g, b)

設置填充顏色為 r, g, b 表示的 RGB 顏色。r, g, b 的取值范圍應為 0..colormode。

如果 turtleshape 為多邊形,該多邊形內部也以新設置的填充顏色填充。

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

返回或設置畫(huà)筆顏色和填充顏色。

允許多種輸入格式。使用如下 0 至 3 個(gè)參數:

color()

返回以一對顏色描述字符串或元組表示的當前畫(huà)筆顏色和填充顏色,兩者可分別由 pencolor()fillcolor() 返回。

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

輸入格式與 pencolor() 相同,同時(shí)設置填充顏色和畫(huà)筆顏色為指定的值。

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

相當于 pencolor(colorstring1)fillcolor(colorstring2),使用其他輸入格式的方法也與之類(lèi)似。

如果 turtleshape 為多邊形,該多邊形輪廓與填充也使用新設置的顏色。

 >>> turtle.color("red", "green")
 >>> turtle.color()
 ('red', 'green')
 >>> color("#285078", "#a0c8f0")
 >>> color()
 ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))

另參見(jiàn): Screen 方法 colormode()。

填充?

turtle.filling()?

返回填充狀態(tài) (填充為 True,否則為 False)。

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

在繪制要填充的形狀之前調用。

turtle.end_fill()?

填充上次調用 begin_fill() 之后繪制的形狀。

自相交多邊形或多個(gè)形狀間的重疊區域是否填充取決于操作系統的圖形引擎、重疊的類(lèi)型以及重疊的層數。 例如上面的 Turtle 多芒星可能會(huì )全部填充為黃色,也可能會(huì )有一些白色區域。

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

更多繪圖控制?

turtle.reset()?

從屏幕中刪除海龜的繪圖,海龜回到原點(diǎn)并設置所有變量為默認值。

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

從屏幕中刪除指定海龜的繪圖。不移動(dòng)海龜。海龜的狀態(tài)和位置以及其他海龜的繪圖不受影響。

turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal'))?
參數
  • arg -- 要書(shū)寫(xiě)到 TurtleScreen 的對象

  • move -- True/False

  • align -- 字符串 "left", "center" 或 "right"

  • font -- 一個(gè)三元組 (fontname, fontsize, fonttype)

基于 align ("left", "center" 或 "right") 并使用給定的字體將文本 —— arg 的字符串表示形式 —— 寫(xiě)到當前海龜位置。 如果 move 為真值,畫(huà)筆會(huì )移至文本的右下角。 默認情況下 moveFalse。

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

海龜狀態(tài)?

可見(jiàn)性?

turtle.hideturtle()?
turtle.ht()?

使海龜不可見(jiàn)。當你繪制復雜圖形時(shí)這是個(gè)好主意,因為隱藏海龜可顯著(zhù)加快繪制速度。

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

使海龜可見(jiàn)。

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

如果海龜顯示返回 True,如果海龜隱藏返回 False。

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

外觀(guān)?

turtle.shape(name=None)?
參數

name -- 一個(gè)有效的形狀名字符串

設置海龜形狀為 name 指定的形狀名,如未指定形狀名則返回當前的形狀名。name 指定的形狀名應存在于 TurtleScreen 的 shape 字典中。多邊形的形狀初始時(shí)有以下幾種: "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" 其中之一

設置大小調整模式為以下值之一: "auto", "user", "noresize"。如未指定 rmode 則返回當前的大小調整模式。不同的大小調整模式的效果如下:

  • "auto": 根據畫(huà)筆粗細值調整海龜的外觀(guān)。

  • "user": 根據拉伸因子和輪廓寬度 (outline) 值調整海龜的外觀(guān),兩者是由 shapesize() 設置的。

  • "noresize": 不調整海龜的外觀(guān)大小。

resizemode("user") 會(huì )由 shapesize() 帶參數使用時(shí)被調用。

>>>
>>> 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 -- 正數值

返回或設置畫(huà)筆的屬性 x/y-拉伸因子和/或輪廓。設置大小調整模式為 "user"。當且僅當大小調整模式設為 "user" 時(shí)海龜會(huì )基于其拉伸因子調整外觀(guān): stretch_wid 為垂直于其朝向的寬度拉伸因子,stretch_len 為平等于其朝向的長(cháng)度拉伸因子,決定形狀輪廓線(xiàn)的粗細。

>>>
>>> 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 -- 數值 (可選)

設置或返回當前的剪切因子。根據 share 指定的剪切因子即剪切角度的切線(xiàn)來(lái)剪切海龜形狀。 改變海龜的朝向 (移動(dòng)方向)。如未指定 shear 參數: 返回當前的剪切因子即剪切角度的切線(xiàn),與海龜朝向平行的線(xiàn)條將被剪切。

 >>> turtle.shape("circle")
 >>> turtle.shapesize(5,2)
 >>> turtle.shearfactor(0.5)
 >>> turtle.shearfactor()
 0.5
turtle.tilt(angle)?
參數

angle -- 一個(gè)數值

海龜形狀自其當前的傾角轉動(dòng) angle 指定的角度,但 改變海龜的朝向 (移動(dòng)方向)。

>>>
>>> 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 -- 一個(gè)數值

旋轉海龜形狀使其指向 angle 指定的方向,忽略其當前的傾角, 改變海龜的朝向 (移動(dòng)方向)。

>>>
>>> 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 -- 一個(gè)數值 (可選)

設置或返回當前的傾角。如果指定 angle 則旋轉海龜形狀使其指向 angle 指定的方向,忽略其當前的傾角。 改變海龜的朝向 (移動(dòng)方向)。如果未指定 angle: 返回當前的傾角,即海龜形狀的方向和海龜朝向 (移動(dòng)方向) 之間的夾角。

>>>
>>> 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 -- 一個(gè)數值 (可選)

  • t12 -- 一個(gè)數值 (可選)

  • t21 -- 一個(gè)數值 (可選)

  • t12 -- 一個(gè)數值 (可選)

設置或返回海龜形狀的當前變形矩陣。

如未指定任何矩陣元素,則返回以 4 元素元組表示的變形矩陣。 否則就根據設置指定元素的矩陣來(lái)改變海龜形狀,矩陣第一排的值為 t11, t12 而第二排的值為 t21, t22。 行列式 t11 * t22 - t12 * t21 必須不為零,否則會(huì )引發(fā)錯誤。 根據指定矩陣修改拉伸因子 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()?

返回以坐標值對元組表示的當前形狀多邊形。這可以用于定義一個(gè)新形狀或一個(gè)復合形狀的多個(gè)組成部分。

>>>
>>> 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 -- 一個(gè)函數,調用時(shí)將傳入兩個(gè)參數表示在畫(huà)布上點(diǎn)擊的坐標。

  • btn -- 鼠標按鈕編號,默認值為 1 (鼠標左鍵)

  • add -- TrueFalse -- 如為 True 則將添加一個(gè)新綁定,否則將取代先前的綁定

fun 指定的函數綁定到鼠標點(diǎn)擊此海龜事件。如果 fun 值為 None,則移除現有的綁定。以下為使用匿名海龜即過(guò)程式的示例:

>>>
>>> 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 -- 一個(gè)函數,調用時(shí)將傳入兩個(gè)參數表示在畫(huà)布上點(diǎn)擊的坐標。

  • btn -- 鼠標按鈕編號,默認值為 1 (鼠標左鍵)

  • add -- TrueFalse -- 如為 True 則將添加一個(gè)新綁定,否則將取代先前的綁定

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)     # clicking on turtle turns fillcolor red,
>>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.
turtle.ondrag(fun, btn=1, add=None)?
參數
  • fun -- 一個(gè)函數,調用時(shí)將傳入兩個(gè)參數表示在畫(huà)布上點(diǎn)擊的坐標。

  • btn -- 鼠標按鈕編號,默認值為 1 (鼠標左鍵)

  • add -- TrueFalse -- 如為 True 則將添加一個(gè)新綁定,否則將取代先前的綁定

fun 指定的函數綁定到在此海龜上移動(dòng)鼠標事件。如果 fun 值為 None,則移除現有的綁定。

注: 在海龜上移動(dòng)鼠標事件之前應先發(fā)生在此海龜上點(diǎn)擊鼠標事件。

>>>
>>> turtle.ondrag(turtle.goto)

在此之后點(diǎn)擊并拖動(dòng)海龜可在屏幕上手繪線(xiàn)條 (如果畫(huà)筆為落下)。

特殊海龜方法?

turtle.begin_poly()?

開(kāi)始記錄多邊形的頂點(diǎn)。當前海龜位置為多邊形的第一個(gè)頂點(diǎn)。

turtle.end_poly()?

停止記錄多邊形的頂點(diǎn)。當前海龜位置為多邊形的最后一個(gè)頂點(diǎn)。它將連線(xiàn)到第一個(gè)頂點(diǎn)。

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

創(chuàng )建并返回海龜的克隆體,具有相同的位置、朝向和海龜屬性。

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

返回海龜對象自身。唯一合理的用法: 作為一個(gè)函數來(lái)返回 "匿名海龜":

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

返回作為海龜繪圖場(chǎng)所的 TurtleScreen 類(lèi)對象。該對象將可調用 TurtleScreen 方法。

>>>
>>> ts = turtle.getscreen()
>>> ts
<turtle._Screen object at 0x...>
>>> ts.bgcolor("pink")
turtle.setundobuffer(size)?
參數

size -- 一個(gè)整型數值或 None

設置或禁用撤銷(xiāo)緩沖區。 如果 size 為整數,則開(kāi)辟一個(gè)給定大小的空撤銷(xiāo)緩沖區。 size 給出了可以通過(guò) undo() 方法/函數撤銷(xiāo)海龜動(dòng)作的最大次數。 如果 sizeNone,則禁用撤銷(xiāo)緩沖區。

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

返回撤銷(xiāo)緩沖區里的條目數。

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

復合形狀?

要使用由多個(gè)不同顏色多邊形構成的復合海龜形狀,你必須明確地使用輔助類(lèi) Shape,具體步驟如下:

  1. 創(chuàng )建一個(gè)空 Shape 對象,類(lèi)型為 "compound"。

  2. 按照需要使用 addcomponent() 方法向此對象添加多個(gè)部件。

    例如:

    >>>
    >>> 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. 接下來(lái)將 Shape 對象添加到 Screen 對象的形狀列表并使用它:

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

備注

Shape 類(lèi)在 register_shape() 方法的內部以多種方式使用。應用程序編寫(xiě)者 只有 在使用上述的復合形狀時(shí)才需要處理 Shape 類(lèi)。

TurtleScreen/Screen 方法及對應函數?

本節中的大部分示例都使用 TurtleScreen 類(lèi)的一個(gè)實(shí)例,命名為 screen。

窗口控制?

turtle.bgcolor(*args)?
參數

args -- 一個(gè)顏色字符串或三個(gè)取值范圍 0..colormode 內的數值或一個(gè)取值范圍相同的數值3元組

設置或返回 TurtleScreen 的背景顏色。

>>>
>>> screen.bgcolor("orange")
>>> screen.bgcolor()
'orange'
>>> screen.bgcolor("#800080")
>>> screen.bgcolor()
(128.0, 0.0, 128.0)
turtle.bgpic(picname=None)?
參數

picname -- 一個(gè)字符串, gif-文件名, "nopic", 或 None

設置背景圖片或返回當前背景圖片名稱(chēng)。如果 picname 為一個(gè)文件名,則將相應圖片設為背景。如果 picname"nopic",則刪除當前背景圖片。如果 picnameNone,則返回當前背景圖片文件名。:

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

備注

此 TurtleScreen 方法作為全局函數時(shí)只有一個(gè)名字 clearscreen。全局函數 clear 所對應的是 Turtle 方法 clear。

turtle.clearscreen()?

從中刪除所有海龜的全部繪圖。將已清空的 TurtleScreen 重置為初始狀態(tài): 白色背景,無(wú)背景片,無(wú)事件綁定并啟用追蹤。

turtle.reset()

備注

此 TurtleScreen 方法作為全局函數時(shí)只有一個(gè)名字 resetscreen。全局函數 reset 所對應的是 Turtle 方法 reset。

turtle.resetscreen()?

重置屏幕上的所有海龜為其初始狀態(tài)。

turtle.screensize(canvwidth=None, canvheight=None, bg=None)?
參數
  • canvwidth -- 正整型數,以像素表示畫(huà)布的新寬度值

  • canvheight -- 正整型數,以像素表示畫(huà)面的新高度值

  • bg -- 顏色字符串或顏色元組,新的背景顏色

如未指定任何參數,則返回當前的 (canvaswidth, canvasheight)。否則改變作為海龜繪圖場(chǎng)所的畫(huà)布大小。不改變繪圖窗口。要觀(guān)察畫(huà)布的隱藏區域,可以使用滾動(dòng)條。通過(guò)此方法可以令之前繪制于畫(huà)布之外的圖形變?yōu)榭梢?jiàn)。

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

也可以用來(lái)尋找意外逃走的海龜 ;-)

turtle.setworldcoordinates(llx, lly, urx, ury)?
參數
  • llx -- 一個(gè)數值, 畫(huà)布左下角的 x-坐標

  • lly -- 一個(gè)數值, 畫(huà)布左下角的 y-坐標

  • urx -- 一個(gè)數值, 畫(huà)面右上角的 x-坐標

  • ury -- 一個(gè)數值, 畫(huà)布右上角的 y-坐標

設置用戶(hù)自定義坐標系并在必要時(shí)切換模式為 "world"。這會(huì )執行一次 screen.reset()。如果 "world" 模式已激活,則所有圖形將根據新的坐標系重繪。

注意: 在用戶(hù)自定義坐標系中,角度可能顯得扭曲。

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

動(dòng)畫(huà)控制?

turtle.delay(delay=None)?
參數

delay -- 正整型數

設置或返回以毫秒數表示的延遲值 delay。(這約等于連續兩次畫(huà)布刷新的間隔時(shí)間。) 繪圖延遲越長(cháng),動(dòng)畫(huà)速度越慢。

可選參數:

>>>
>>> screen.delay()
10
>>> screen.delay(5)
>>> screen.delay()
5
turtle.tracer(n=None, delay=None)?
參數
  • n -- 非負整型數

  • delay -- 非負整型數

啟用/禁用海龜動(dòng)畫(huà)并設置刷新圖形的延遲時(shí)間。如果指定 n 值,則只有每第 n 次屏幕刷新會(huì )實(shí)際執行。(可被用來(lái)加速復雜圖形的繪制。) 如果調用時(shí)不帶參數,則返回當前保存的 n 值。第二個(gè)參數設置延遲值 (參見(jiàn) delay())。

>>>
>>> screen.tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
...     fd(dist)
...     rt(90)
...     dist += 2
turtle.update()?

執行一次 TurtleScreen 刷新。在禁用追蹤時(shí)使用。

另參見(jiàn) RawTurtle/Turtle 方法 speed()。

使用屏幕事件?

turtle.listen(xdummy=None, ydummy=None)?

設置焦點(diǎn)到 TurtleScreen (以便接收按鍵事件)。使用兩個(gè) Dummy 參數以便能夠傳遞 listen() 給 onclick 方法。

turtle.onkey(fun, key)?
turtle.onkeyrelease(fun, key)?
參數
  • fun -- 一個(gè)無(wú)參數的函數或 None

  • key -- 一個(gè)字符串: 鍵 (例如 "a") 或鍵標 (例如 "space")

綁定 fun 指定的函數到按鍵釋放事件。如果 fun 值為 None,則移除事件綁定。注: 為了能夠注冊按鍵事件,TurtleScreen 必須得到焦點(diǎn)。(參見(jiàn) method listen() 方法。)

>>>
>>> def f():
...     fd(50)
...     lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
turtle.onkeypress(fun, key=None)?
參數
  • fun -- 一個(gè)無(wú)參數的函數或 None

  • key -- 一個(gè)字符串: 鍵 (例如 "a") 或鍵標 (例如 "space")

綁定 fun 指定的函數到指定鍵的按下事件。如未指定鍵則綁定到任意鍵的按下事件。注: 為了能夠注冊按鍵事件,必須得到焦點(diǎn)。(參見(jiàn) 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 -- 一個(gè)函數,調用時(shí)將傳入兩個(gè)參數表示在畫(huà)布上點(diǎn)擊的坐標。

  • btn -- 鼠標按鈕編號,默認值為 1 (鼠標左鍵)

  • add -- TrueFalse -- 如為 True 則將添加一個(gè)新綁定,否則將取代先前的綁定

綁定 fun 指定的函數到鼠標點(diǎn)擊屏幕事件。如果 fun 值為 None,則移除現有的綁定。

以下示例使用一個(gè) TurtleScreen 實(shí)例 screen 和一個(gè) Turtle 實(shí)例 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 方法作為全局函數時(shí)只有一個(gè)名字 onscreenclick。全局函數 onclick 所對應的是 Turtle 方法 onclick。

turtle.ontimer(fun, t=0)?
參數
  • fun -- 一個(gè)無(wú)參數的函數

  • t -- 一個(gè)數值 >= 0

安裝一個(gè)計時(shí)器,在 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()?

開(kāi)始事件循環(huán) - 調用 Tkinter 的 mainloop 函數。必須作為一個(gè)海龜繪圖程序的結束語(yǔ)句。如果一個(gè)腳本是在以 -n 模式 (無(wú)子進(jìn)程) 啟動(dòng)的 IDLE 中運行時(shí) 不可 使用 - 用于實(shí)現海龜繪圖的交互功能。:

>>>
>>> screen.mainloop()

輸入方法?

turtle.textinput(title, prompt)?
參數
  • title -- string

  • prompt -- string

彈出一個(gè)對話(huà)框窗口用來(lái)輸入一個(gè)字符串。形參 title 為對話(huà)框窗口的標題,prompt 為一條文本,通常用來(lái)提示要輸入什么信息。返回輸入的字符串。如果對話(huà)框被取消則返回 None。:

>>>
>>> screen.textinput("NIM", "Name of first player:")
turtle.numinput(title, prompt, default=None, minval=None, maxval=None)?
參數
  • title -- string

  • prompt -- string

  • 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") 并執行重置。如未指定模式則返回當前的模式。

"standard" 模式與舊的 turtle 兼容。"logo" 模式與大部分 Logo 海龜繪圖兼容。"world" 模式使用用戶(hù)自定義的 "世界坐標系"。注意: 在此模式下,如果 x/y 單位比率不等于 1 則角度會(huì )顯得扭曲。

模式

初始海龜朝向

正數角度

"standard"

朝右 (東)

逆時(shí)針

"logo"

朝上 (北)

順時(shí)針

>>>
>>> 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 的 Canvas 對象。供了解 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 為一個(gè) gif 文件的文件名, shapeNone: 安裝相應的圖像形狀。:

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

    備注

    當海龜轉向時(shí)圖像形狀 不會(huì ) 轉動(dòng),因此無(wú)法顯示海龜的朝向!

  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.

將一個(gè)海龜形狀加入 TurtleScreen 的形狀列表。只有這樣注冊過(guò)的形狀才能通過(guò)執行 shape(shapename) 命令來(lái)使用。

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 專(zhuān)有方法, 而非繼承自 TurtleScreen?

turtle.bye()?

關(guān)閉海龜繪圖窗口。

turtle.exitonclick()?

bye() 方法綁定到 Screen 上的鼠標點(diǎn)擊事件。

如果配置字典中 "using_IDLE" 的值為 False (默認值) 則同時(shí)進(jìn)入主事件循環(huán)。注: 如果啟動(dòng) IDLE 時(shí)使用了 -n 開(kāi)關(guān) (無(wú)子進(jìn)程),turtle.cfg 中此數值應設為 True。在此情況下 IDLE 本身的主事件循環(huán)同樣會(huì )作用于客戶(hù)腳本。

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

設置主窗口的大小和位置。默認參數值保存在配置字典中,可通過(guò) turtle.cfg 文件進(jìn)行修改。

參數
  • width -- 如為一個(gè)整型數值,表示大小為多少像素,如為一個(gè)浮點(diǎn)數值,則表示屏幕的占比;默認為屏幕的 50%

  • height -- 如為一個(gè)整型數值,表示高度為多少像素,如為一個(gè)浮點(diǎn)數值,則表示屏幕的占比;默認為屏幕的 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 -- 一個(gè)字符串,顯示為海龜繪圖窗口的標題欄文本

設置海龜窗口標題為 titlestring 指定的文本。

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

公共類(lèi)?

class turtle.RawTurtle(canvas)?
class turtle.RawPen(canvas)?
參數

canvas -- 一個(gè) tkinter.Canvas , ScrolledCanvasTurtleScreen 類(lèi)對象

創(chuàng )建一個(gè)海龜。海龜對象具有 "Turtle/RawTurtle 方法" 一節所述的全部方法。

class turtle.Turtle?

RawTurtle 的子類(lèi),具有相同的接口,但其繪圖場(chǎng)所為默認的 Screen 類(lèi)對象,在首次使用時(shí)自動(dòng)創(chuàng )建。

class turtle.TurtleScreen(cv)?
參數

cv -- 一個(gè) tkinter.Canvas 類(lèi)對象

提供面向屏幕的方法例如 setbg() 等。說(shuō)明見(jiàn)上文。

class turtle.Screen?

TurtleScreen 的子類(lèi),增加了四個(gè)方法.

class turtle.ScrolledCanvas(master)?
參數

master -- 可容納 ScrolledCanvas 的 Tkinter 部件,即添加了滾動(dòng)條的 Tkinter-canvas

由 Screen 類(lèi)使用,使其能夠自動(dòng)提供一個(gè) ScrolledCanvas 作為海龜的繪圖場(chǎng)所。

class turtle.Shape(type_, data)?
參數

type_ -- 字符串 "polygon", "image", "compound" 其中之一

實(shí)現形狀的數據結構。(type_, data) 必須遵循以下定義:

type_

data

"polygon"

一個(gè)多邊形元組,即由坐標值對構成的元組

"image"

一個(gè)圖片 (此形式僅限內部使用!)

"compound"

None (復合形狀必須使用 addcomponent() 方法來(lái)構建)

addcomponent(poly, fill, outline=None)?
參數
  • poly -- 一個(gè)多邊形,即由數值對構成的元組

  • fill -- 一種顏色,將用來(lái)填充 poly 指定的多邊形

  • outline -- 一種顏色,用于多邊形的輪廓 (如有指定)

示例:

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

參見(jiàn) 復合形狀。

class turtle.Vec2D(x, y)?

一個(gè)二維矢量類(lèi),用來(lái)作為實(shí)現海龜繪圖的輔助類(lèi)。也可能在海龜繪圖程序中使用。派生自元組,因此矢量也屬于元組!

提供的運算 (a, b 為矢量, k 為數值):

  • a + b 矢量加法

  • a - b 矢量減法

  • a * b 內積

  • k * aa * k 與標量相乘

  • abs(a) a 的絕對值

  • a.rotate(angle) 旋轉

幫助與配置?

如何使用幫助?

Screen 和 Turtle 類(lèi)的公用方法以文檔字符串提供了詳細的文檔。因此可以利用 Python 幫助工具獲取這些在線(xiàn)幫助信息:

  • 當使用 IDLE 時(shí),輸入函數/方法調用將彈出工具提示顯示其簽名和文檔字符串的頭幾行。

  • 對文法或函數調用 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()
    
  • 方法對應函數的文檔字符串的形式會(huì )有一些修改:

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

這些修改版文檔字符串是在導入時(shí)與方法對應函數的定義一起自動(dòng)生成的。

文檔字符串翻譯為不同的語(yǔ)言?

可使用工具創(chuàng )建一個(gè)字典,鍵為方法名,值為 Screen 和 Turtle 類(lèi)公共方法的文檔字符串。

turtle.write_docstringdict(filename='turtle_docstringdict')?
參數

filename -- 一個(gè)字符串,表示文件名

創(chuàng )建文檔字符串字典并將其寫(xiě)入 filename 指定的 Python 腳本文件。此函數必須顯示地調用 (海龜繪圖類(lèi)并不使用此函數)。文檔字符串字典將被寫(xiě)入到 Python 腳本文件 filename.py。該文件可作為模板用來(lái)將文檔字符串翻譯為不同語(yǔ)言。

如果你 (或你的學(xué)生) 想使用本國語(yǔ)言版本的 turtle 在線(xiàn)幫助,你必須翻譯文檔字符串并保存結果文件,例如 turtle_docstringdict_german.py.

如果你在 turtle.cfg 文件中加入了相應的條目,此字典將在導入模塊時(shí)被讀取并替代原有的英文版文檔字符串。

在撰寫(xiě)本文檔時(shí)已經(jīng)有了德語(yǔ)和意大利語(yǔ)版的文檔字符串字典。(更多需求請聯(lián)系 glingl@aon.at)

如何配置 Screen 和 Turtle?

內置的默認配置是模仿舊 turtle 模塊的外觀(guān)和行為,以便盡可能地與其保持兼容。

如果你想使用不同的配置,以便更好地反映此模塊的特性或是更適合你的需求,例如在課堂中使用,你可以準備一個(gè)配置文件 turtle.cfg,該文件將在導入模塊時(shí)被讀取并根據其中的設定修改模塊配置。

內置的配置對應以下的 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

選定條目的簡(jiǎn)短說(shuō)明:

  • 開(kāi)頭的四行對應 Screen.setup() 方法的參數。

  • 第 5 和 6 行對應 Screen.screensize() 方法的參數。

  • shape 可以是任何內置形狀,即: arrow, turtle 等。更多信息可用 help(shape) 查看。

  • 如果你想使用無(wú)填充色 (即令海龜變透明),你必須寫(xiě) fillcolor = "" (但 cfg 文件中所有非空字符串都不可加引號)。

  • 如果你想令海龜反映其狀態(tài),你必須使用 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 條目定義了相應對象在文檔字符串中顯示的名稱(chēng)。方法文檔字符串轉換為函數文檔字符串時(shí)將從文檔字符串中刪去這些名稱(chēng)。

  • 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.cfg 文件可以保存于 turtle 所在目錄,當前工作目錄也可以有一個(gè)同名文件。后者會(huì )重載覆蓋前者的設置。

Lib/turtledemo 目錄中也有一個(gè) turtle.cfg 文件。你可以將其作為示例進(jìn)行研究,并在運行演示時(shí)查看其作用效果 (但最好不要在演示查看器中運行)。

turtledemo --- 演示腳本集?

turtledemo 包匯集了一組演示腳本。這些腳本可以通過(guò)以下命令打開(kāi)所提供的演示查看器運行和查看:

python -m turtledemo

此外,你也可以單獨運行其中的演示腳本。例如,:

python -m turtledemo.bytedesign

turtledemo 包目錄中的內容:

  • 一個(gè)演示查看器 __main__.py,可用來(lái)查看腳本的源碼并即時(shí)運行。

  • 多個(gè)腳本文件,演示 turtle 模塊的不同特性。所有示例可通過(guò) Examples 菜單打開(kāi)。也可以單獨運行每個(gè)腳本。

  • 一個(gè) turtle.cfg 文件,作為說(shuō)明如何編寫(xiě)并使用模塊配置文件的示例模板。

演示腳本清單如下:

名稱(chēng)

描述

相關(guān)特性

bytedesign

復雜的傳統海龜繪圖模式

tracer(), delay, update()

chaos

繪制 Verhulst 動(dòng)態(tài)模型,演示通過(guò)計算機的運算可能會(huì )生成令人驚嘆的結果

世界坐標系

clock

繪制模擬時(shí)鐘顯示本機的當前時(shí)間

海龜作為表針, ontimer

colormixer

試驗 r, g, b 顏色模式

ondrag() 當鼠標拖動(dòng)

forest

繪制 3 棵廣度優(yōu)先樹(shù)

隨機化

fractalcurves

繪制 Hilbert & Koch 曲線(xiàn)

遞歸

lindenmayer

文化數學(xué) (印度裝飾藝術(shù))

L-系統

minimal_hanoi

漢諾塔

矩形海龜作為漢諾盤(pán) (shape, shapesize)

nim

玩經(jīng)典的“尼姆”游戲,開(kāi)始時(shí)有三堆小棒,與電腦對戰。

海龜作為小棒,事件驅動(dòng) (鼠標, 鍵盤(pán))

paint

超極簡(jiǎn)主義繪畫(huà)程序

onclick() 當鼠標點(diǎn)擊

peace

初級技巧

海龜: 外觀(guān)與動(dòng)畫(huà)

penrose

非周期性地使用風(fēng)箏和飛鏢形狀鋪滿(mǎn)平面

stamp() 印章

planet_and_moon

模擬引力系統

復合開(kāi)關(guān), Vec2D 類(lèi)

round_dance

兩兩相對并不斷旋轉舞蹈的海龜

復合形狀, clone shapesize, tilt, get_shapepoly, update

sorting_animate

動(dòng)態(tài)演示不同的排序方法

簡(jiǎn)單對齊, 隨機化

tree

一棵 (圖形化的) 廣度優(yōu)先樹(shù) (使用生成器)

clone() 克隆

two_canvases

簡(jiǎn)單設計

兩塊畫(huà)布上的海龜

wikipedia

一個(gè)來(lái)自介紹海龜繪圖的維基百科文章的圖案

clone(), undo()

yinyang

另一個(gè)初級示例

circle() 畫(huà)圓

祝你玩得開(kāi)心!

Python 2.6 之后的變化?

  • Turtle.tracer(), Turtle.window_width()Turtle.window_height() 方法已被去除。具有這些名稱(chēng)和功能的方法現在只限于 Screen 類(lèi)的方法。但其對應的函數仍然可用。(實(shí)際上在 Python 2.6 中這些方法就已經(jīng)只是從對應的 TurtleScreen/Screen 類(lèi)的方法復制而來(lái)。)

  • Turtle.fill() 方法已被去除。begin_fill()end_fill() 的行為則有細微改變: 現在每個(gè)填充過(guò)程必須以一個(gè) end_fill() 調用來(lái)結束。

  • 新增了一個(gè) Turtle.filling() 方法。該方法返回一個(gè)布爾值: 如果填充過(guò)程正在進(jìn)行為 True,否則為 False。此行為相當于 Python 2.6 中不帶參數的 fill() 調用。

Python 3.0 之后的變化?

  • 新增了 Turtle.shearfactor(), Turtle.shapetransform()Turtle.get_shapepoly() 方法。這樣就可以使用所有標準線(xiàn)性變換來(lái)調整海龜形狀。Turtle.tiltangle() 的功能已被加強: 現在可被用來(lái)獲取或設置傾角。Turtle.settiltangle() 已棄用。

  • 新增了 Screen.onkeypress() 方法作為對 Screen.onkey() 的補充,實(shí)際就是將行為綁定到 keyrelease 事件。后者相應增加了一個(gè)別名: Screen.onkeyrelease()。

  • 新增了 Screen.mainloop() 方法。這樣當僅需使用 Screen 和 Turtle 對象時(shí)不需要再額外導入 mainloop()。

  • 新增了兩個(gè)方法 Screen.textinput()Screen.numinput()。用來(lái)彈出對話(huà)框接受輸入并分別返回字符串和數值。

  • 兩個(gè)新的示例腳本 tdemo_nim.pytdemo_round_dance.py 被加入到 Lib/turtledemo 目錄中。