### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](cmd.xhtml "cmd --- 支持面向行的命令解釋器") |
- [上一頁](frameworks.xhtml "程序框架") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 標準庫](index.xhtml) ?
- [程序框架](frameworks.xhtml) ?
- $('.inline-search').show(0); |
# [`turtle`](#module-turtle "turtle: An educational framework for simple graphics applications") --- 海龜繪圖
**源碼:** [Lib/turtle.py](https://github.com/python/cpython/tree/3.7/Lib/turtle.py) \[https://github.com/python/cpython/tree/3.7/Lib/turtle.py\]
- - - - - -
## 概述
海龜繪圖很適合用來引導孩子學習編程。最初來自于 Wally Feurzig 和 Seymour Papert 于 1966 年所創造的 Logo 編程語言。
請想象繪圖區有一只機器海龜,起始位置在 x-y 平面的 (0, 0) 點。先執行 `import turtle`,再執行 `turtle.forward(15)`,它將(在屏幕上)朝所面對的 x 軸正方向前進 15 像素,隨著它的移動畫出一條線段。再執行 `turtle.right(25)`,它將原地右轉 25 度。
Turtle star
使用海龜繪圖可以編寫重復執行簡單動作的程序畫出精細復雜的形狀。

```
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
```
通過組合使用此類命令,可以輕松地繪制出精美的形狀和圖案。
[`turtle`](#module-turtle "turtle: An educational framework for simple graphics applications") 模塊是基于 Python 標準發行版 2.5 以來的同名模塊重新編寫并進行了功能擴展。
新模塊盡量保持了原模塊的特點,并且(幾乎)100%與其兼容。這就意味著初學編程者能夠以交互方式使用模塊的所有命令、類和方法——運行 IDLE 時注意加 `-n` 參數。
turtle 模塊提供面向對象和面向過程兩種形式的海龜繪圖基本組件。由于它使用 [`tkinter`](tkinter.xhtml#module-tkinter "tkinter: Interface to Tcl/Tk for graphical user interfaces") 實現基本圖形界面,因此需要安裝了 Tk 支持的 Python 版本。
面向對象的接口主要使用“2+2”個類:
1. [`TurtleScreen`](#turtle.TurtleScreen "turtle.TurtleScreen") 類定義圖形窗口作為繪圖海龜的運動場。它的構造器需要一個 `tkinter.Canvas` 或 [`ScrolledCanvas`](#turtle.ScrolledCanvas "turtle.ScrolledCanvas") 作為參數。應在 [`turtle`](#module-turtle "turtle: An educational framework for simple graphics applications") 作為某個程序的一部分的時候使用。
[`Screen()`](#turtle.Screen "turtle.Screen") 函數返回一個 [`TurtleScreen`](#turtle.TurtleScreen "turtle.TurtleScreen") 子類的單例對象。此函數應在 [`turtle`](#module-turtle "turtle: An educational framework for simple graphics applications") 作為獨立繪圖工具時使用。作為一個單例對象,其所屬的類是不可被繼承的。
TurtleScreen/Screen 的所有方法還存在對應的函數,即作為面向過程的接口組成部分。
2. [`RawTurtle`](#turtle.RawTurtle "turtle.RawTurtle") (別名: [`RawPen`](#turtle.RawPen "turtle.RawPen")) 類定義海龜對象在 [`TurtleScreen`](#turtle.TurtleScreen "turtle.TurtleScreen") 上繪圖。它的構造器需要一個 Canvas, ScrolledCanvas 或 TurtleScreen 作為參數,以指定 RawTurtle 對象在哪里繪圖。
從 RawTurtle 派生出子類 [`Turtle`](#turtle.Turtle "turtle.Turtle") (別名: `Pen`),該類對象在 [`Screen`](#turtle.Screen "turtle.Screen") 實例上繪圖,如果實例不存在則會自動創建。
RawTurtle/Turtle 的所有方法也存在對應的函數,即作為面向過程的接口組成部分。
過程式接口提供與 [`Screen`](#turtle.Screen "turtle.Screen") 和 [`Turtle`](#turtle.Turtle "turtle.Turtle") 類的方法相對應的函數。函數名與對應的方法名相同。當 Screen 類的方法對應函數被調用時會自動創建一個 Screen 對象。當 Turtle 類的方法對應函數被調用時會自動創建一個 (匿名的) Turtle 對象。
如果屏幕上需要有多個海龜,就必須使用面向對象的接口。
注解
以下文檔給出了函數的參數列表。對于方法來說當然還有額外的第一個參數 *self*,這里省略了。
## 可用的 Turtle 和 Screen 方法概覽
### Turtle 方法
海龜動作移動和繪制[`forward()`](#turtle.forward "turtle.forward") | [`fd()`](#turtle.fd "turtle.fd") 前進
[`backward()`](#turtle.backward "turtle.backward") | [`bk()`](#turtle.bk "turtle.bk") | [`back()`](#turtle.back "turtle.back") 后退
[`right()`](#turtle.right "turtle.right") | [`rt()`](#turtle.rt "turtle.rt") 右轉
[`left()`](#turtle.left "turtle.left") | [`lt()`](#turtle.lt "turtle.lt") 左轉
[`goto()`](#turtle.goto "turtle.goto") | [`setpos()`](#turtle.setpos "turtle.setpos") | [`setposition()`](#turtle.setposition "turtle.setposition") 前往/定位
[`setx()`](#turtle.setx "turtle.setx") 設置x坐標
[`sety()`](#turtle.sety "turtle.sety") 設置y坐標
[`setheading()`](#turtle.setheading "turtle.setheading") | [`seth()`](#turtle.seth "turtle.seth") 設置朝向
[`home()`](#turtle.home "turtle.home") 返回原點
[`circle()`](#turtle.circle "turtle.circle") 畫圓
[`dot()`](#turtle.dot "turtle.dot") 畫點
[`stamp()`](#turtle.stamp "turtle.stamp") 印章
[`clearstamp()`](#turtle.clearstamp "turtle.clearstamp") 清除印章
[`clearstamps()`](#turtle.clearstamps "turtle.clearstamps") 清除多個印章
[`undo()`](#turtle.undo "turtle.undo") 撤消
[`speed()`](#turtle.speed "turtle.speed") 速度
獲取海龜的狀態[`position()`](#turtle.position "turtle.position") | [`pos()`](#turtle.pos "turtle.pos") 位置
[`towards()`](#turtle.towards "turtle.towards") 目標方向
[`xcor()`](#turtle.xcor "turtle.xcor") x坐標
[`ycor()`](#turtle.ycor "turtle.ycor") y坐標
[`heading()`](#turtle.heading "turtle.heading") 朝向
[`distance()`](#turtle.distance "turtle.distance") 距離
設置與度量單位[`degrees()`](#turtle.degrees "turtle.degrees") 角度
[`radians()`](#turtle.radians "turtle.radians") 弧度
畫筆控制繪圖狀態[`pendown()`](#turtle.pendown "turtle.pendown") | [`pd()`](#turtle.pd "turtle.pd") | [`down()`](#turtle.down "turtle.down") 畫筆落下
[`penup()`](#turtle.penup "turtle.penup") | [`pu()`](#turtle.pu "turtle.pu") | [`up()`](#turtle.up "turtle.up") 畫筆抬起
[`pensize()`](#turtle.pensize "turtle.pensize") | [`width()`](#turtle.width "turtle.width") 畫筆粗細
[`pen()`](#turtle.pen "turtle.pen") 畫筆
[`isdown()`](#turtle.isdown "turtle.isdown") 畫筆是否落下
顏色控制[`color()`](#turtle.color "turtle.color") 顏色
[`pencolor()`](#turtle.pencolor "turtle.pencolor") 畫筆顏色
[`fillcolor()`](#turtle.fillcolor "turtle.fillcolor") 填充顏色
填充[`filling()`](#turtle.filling "turtle.filling") 是否填充
[`begin_fill()`](#turtle.begin_fill "turtle.begin_fill") 開始填充
[`end_fill()`](#turtle.end_fill "turtle.end_fill") 結束填充
更多繪圖控制[`reset()`](#turtle.reset "turtle.reset") 重置
[`clear()`](#turtle.clear "turtle.clear") 清空
[`write()`](#turtle.write "turtle.write") 書寫
海龜狀態可見性[`showturtle()`](#turtle.showturtle "turtle.showturtle") | [`st()`](#turtle.st "turtle.st") 顯示海龜
[`hideturtle()`](#turtle.hideturtle "turtle.hideturtle") | [`ht()`](#turtle.ht "turtle.ht") 隱藏海龜
[`isvisible()`](#turtle.isvisible "turtle.isvisible") 是否可見
外觀[`shape()`](#turtle.shape "turtle.shape") 形狀
[`resizemode()`](#turtle.resizemode "turtle.resizemode") 大小調整模式
[`shapesize()`](#turtle.shapesize "turtle.shapesize") | [`turtlesize()`](#turtle.turtlesize "turtle.turtlesize") 形狀大小
[`shearfactor()`](#turtle.shearfactor "turtle.shearfactor") 剪切因子
[`settiltangle()`](#turtle.settiltangle "turtle.settiltangle") 設置傾角
[`tiltangle()`](#turtle.tiltangle "turtle.tiltangle") 傾角
[`tilt()`](#turtle.tilt "turtle.tilt") 傾斜
[`shapetransform()`](#turtle.shapetransform "turtle.shapetransform") 變形
[`get_shapepoly()`](#turtle.get_shapepoly "turtle.get_shapepoly") 獲取形狀多邊形
使用事件[`onclick()`](#turtle.onclick "turtle.onclick") 當鼠標點擊
[`onrelease()`](#turtle.onrelease "turtle.onrelease") 當鼠標釋放
[`ondrag()`](#turtle.ondrag "turtle.ondrag") 當鼠標拖動
特殊海龜方法[`begin_poly()`](#turtle.begin_poly "turtle.begin_poly") 開始記錄多邊形
[`end_poly()`](#turtle.end_poly "turtle.end_poly") 結束記錄多邊形
[`get_poly()`](#turtle.get_poly "turtle.get_poly") 獲取多邊形
[`clone()`](#turtle.clone "turtle.clone") 克隆
[`getturtle()`](#turtle.getturtle "turtle.getturtle") | [`getpen()`](#turtle.getpen "turtle.getpen") 獲取海龜畫筆
[`getscreen()`](#turtle.getscreen "turtle.getscreen") 獲取屏幕
[`setundobuffer()`](#turtle.setundobuffer "turtle.setundobuffer") 設置撤消緩沖區
[`undobufferentries()`](#turtle.undobufferentries "turtle.undobufferentries") 撤消緩沖區條目數
### TurtleScreen/Screen 方法
窗口控制[`bgcolor()`](#turtle.bgcolor "turtle.bgcolor") 背景顏色
[`bgpic()`](#turtle.bgpic "turtle.bgpic") 背景圖片
[`clear()`](#turtle.clear "turtle.clear") | [`clearscreen()`](#turtle.clearscreen "turtle.clearscreen") 清屏
[`reset()`](#turtle.reset "turtle.reset") | [`resetscreen()`](#turtle.resetscreen "turtle.resetscreen") 重置
[`screensize()`](#turtle.screensize "turtle.screensize") 屏幕大小
[`setworldcoordinates()`](#turtle.setworldcoordinates "turtle.setworldcoordinates") 設置世界坐標系
動畫控制[`delay()`](#turtle.delay "turtle.delay") 延遲
[`tracer()`](#turtle.tracer "turtle.tracer") 追蹤
[`update()`](#turtle.update "turtle.update") 更新
使用屏幕事件[`listen()`](#turtle.listen "turtle.listen") 監聽
[`onkey()`](#turtle.onkey "turtle.onkey") | [`onkeyrelease()`](#turtle.onkeyrelease "turtle.onkeyrelease") 當鍵盤按下并釋放
[`onkeypress()`](#turtle.onkeypress "turtle.onkeypress") 當鍵盤按下
[`onclick()`](#turtle.onclick "turtle.onclick") | [`onscreenclick()`](#turtle.onscreenclick "turtle.onscreenclick") 當點擊屏幕
[`ontimer()`](#turtle.ontimer "turtle.ontimer") 當達到定時
[`mainloop()`](#turtle.mainloop "turtle.mainloop") | [`done()`](#turtle.done "turtle.done") 主循環
設置與特殊方法[`mode()`](#turtle.mode "turtle.mode") 模式
[`colormode()`](#turtle.colormode "turtle.colormode") 顏色模式
[`getcanvas()`](#turtle.getcanvas "turtle.getcanvas") 獲取畫布
[`getshapes()`](#turtle.getshapes "turtle.getshapes") 獲取形狀
[`register_shape()`](#turtle.register_shape "turtle.register_shape") | [`addshape()`](#turtle.addshape "turtle.addshape") 添加形狀
[`turtles()`](#turtle.turtles "turtle.turtles") 所有海龜
[`window_height()`](#turtle.window_height "turtle.window_height") 窗口高度
[`window_width()`](#turtle.window_width "turtle.window_width") 窗口寬度
輸入方法[`textinput()`](#turtle.textinput "turtle.textinput") 文本輸入
[`numinput()`](#turtle.numinput "turtle.numinput") 數字輸入
Screen 專有方法[`bye()`](#turtle.bye "turtle.bye") 退出
[`exitonclick()`](#turtle.exitonclick "turtle.exitonclick") 當點擊時退出
[`setup()`](#turtle.setup "turtle.setup") 設置
[`title()`](#turtle.title "turtle.title") 標題
## RawTurtle/Turtle 方法和對應函數
本節中的大部分示例都使用 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* 個單位。(單位默認為角度,但可通過 [`degrees()`](#turtle.degrees "turtle.degrees") 和 [`radians()`](#turtle.radians "turtle.radians") 函數改變設置。) 角度的正負由海龜模式確定,參見 [`mode()`](#turtle.mode "turtle.mode")。
```
>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0
```
`turtle.``left`(*angle*)`turtle.``lt`(*angle*)參數**angle** -- 一個數值 (整型或浮點型)
海龜左轉 *angle* 個單位。(單位默認為角度,但可通過 [`degrees()`](#turtle.degrees "turtle.degrees") 和 [`radians()`](#turtle.radians "turtle.radians") 函數改變設置。) 角度的正負由海龜模式確定,參見 [`mode()`](#turtle.mode "turtle.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`
如果 *y* 為 `None`,*x* 應為一個表示坐標的數值對或 [`Vec2D`](#turtle.Vec2D "turtle.Vec2D") 類對象 (例如 [`pos()`](#turtle.pos "turtle.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.``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*。以下是以角度表示的幾個常用方向:
標準模式
logo 模式
0 - 東
0 - 北
90 - 北
90 - 東
180 - 西
180 - 南
270 - 南
270 - 西
```
>>> turtle.setheading(90)
>>> turtle.heading()
90.0
```
`turtle.``home`()海龜移至初始坐標 (0,0),并設置朝向為初始方向 (由海龜模式確定,參見 [`mode()`](#turtle.mode "turtle.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** -- 一個顏色字符串或顏色數值元組
繪制一個直徑為 *size*,顏色為 *color* 的圓點。如果 *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")
>>> turtle.stamp()
11
>>> turtle.fd(50)
```
`turtle.``clearstamp`(*stampid*)參數**stampid** -- 一個整型數,必須是之前 [`stamp()`](#turtle.stamp "turtle.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* 個海龜印章。如果 *n* 為 `None` 則刪除全部印章,如果 *n* > 0 則刪除前 *n* 個印章,否則如果 *n* < 0 則刪除后 *n* 個印章。
```
>>> 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`()撤消 (或連續撤消) 最近的一個 (或多個) 海龜動作。可撤消的次數由撤消緩沖區的大小決定。
```
>>> 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.Vec2D "turtle.Vec2D") 矢量類對象)。
```
>>> turtle.pos()
(440.00,-0.00)
```
`turtle.``towards`(*x*, *y=None*)參數- **x** -- 一個數值或數值對/矢量,或一個海龜實例
- **y** -- 一個數值——如果 *x* 是一個數值,否則為 `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.mode "turtle.mode"))。
```
>>> turtle.home()
>>> turtle.left(67)
>>> turtle.heading()
67.0
```
`turtle.``distance`(*x*, *y=None*)參數- **x** -- 一個數值或數值對/矢量,或一個海龜實例
- **y** -- 一個數值——如果 *x* 是一個數值,否則為 `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** -- 一個數值
設置角度的度量單位,即設置一個圓周為多少 "度"。默認值為 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" 并且 turtleshape 為多邊形,該多邊形也以同樣組細的線條繪制。如未指定參數,則返回當前的 pensize。
```
>>> 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 "turtle.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()`返回以顏色描述字符串或元組 (見示例) 表示的當前畫筆顏色。可用作其他 color/pencolor/fillcolor 調用的輸入。
`pencolor(colorstring)`設置畫筆顏色為 *colorstring* 指定的 Tk 顏色描述字符串,例如 `"red"`、`"yellow"` 或 `"#33cc8c"`。
`pencolor((r, g, b))`設置畫筆顏色為以 *r*, *g*, *b* 元組表示的 RGB 顏色。*r*, *g*, *b* 的取值范圍應為 0..colormode,colormode 的值為 1.0 或 255 (參見 [`colormode()`](#turtle.colormode "turtle.colormode"))。
`pencolor(r, g, b)`> 設置畫筆顏色為以 *r*, *g*, *b* 表示的 RGB 顏色。*r*, *g*, *b* 的取值范圍應為 0..colormode。
如果 turtleshape 為多邊形,該多邊形輪廓也以新設置的畫筆顏色繪制。
```
>>> 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()`返回以顏色描述字符串或元組 (見示例) 表示的當前填充顏色。可用作其他 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 (參見 [`colormode()`](#turtle.colormode "turtle.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*)返回或設置畫筆顏色和填充顏色。
允許多種輸入格式。使用如下 0 至 3 個參數:
`color()`返回以一對顏色描述字符串或元組表示的當前畫筆顏色和填充顏色,兩者可分別由 [`pencolor()`](#turtle.pencolor "turtle.pencolor") 和 [`fillcolor()`](#turtle.fillcolor "turtle.fillcolor") 返回。
`color(colorstring)`, `color((r,g,b))`, `color(r,g,b)`輸入格式與 [`pencolor()`](#turtle.pencolor "turtle.pencolor") 相同,同時設置填充顏色和畫筆顏色為指定的值。
`color(colorstring1, colorstring2)`, `color((r1,g1,b1), (r2,g2,b2))`> 相當于 `pencolor(colorstring1)` 加 `fillcolor(colorstring2)`,使用其他輸入格式的方法也與之類似。
如果 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))
```
另參見: Screen 方法 [`colormode()`](#turtle.colormode "turtle.colormode")。
#### 填充
`turtle.``filling`()返回填充狀態 (填充為 `True`,否則為 `False`)。
```
>>> turtle.begin_fill()
>>> if turtle.filling():
... turtle.pensize(5)
... else:
... turtle.pensize(3)
```
`turtle.``begin_fill`()在繪制要填充的形狀之前調用。
`turtle.``end_fill`()填充上次調用 [`begin_fill()`](#turtle.begin_fill "turtle.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** -- 一個三元組 (fontname, fontsize, fonttype)
書寫文本 - *arg* 指定的字符串 - 到當前海龜位置,*align* 指定對齊方式 ("left", "center" 或 right"),font 指定字體。如果 *move* 為 True,畫筆會移動到文本的右下角。默認 *move* 為 `False`。
```
>>> 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** -- 一個有效的形狀名字符串
設置海龜形狀為 *name* 指定的形狀名,如未指定形狀名則返回當前的形狀名。*name* 指定的形狀名應存在于 TurtleScreen 的 shape 字典中。多邊形的形狀初始時有以下幾種: "arrow", "turtle", "circle", "square", "triangle", "classic"。要了解如何處理形狀請參看 Screen 方法 [`register_shape()`](#turtle.register_shape "turtle.register_shape")。
```
>>> turtle.shape()
'classic'
>>> turtle.shape("turtle")
>>> turtle.shape()
'turtle'
```
`turtle.``resizemode`(*rmode=None*)參數**rmode** -- 字符串 "auto", "user", "noresize" 其中之一
設置大小調整模式為以下值之一: "auto", "user", "noresize"。如未指定 *rmode* 則返回當前的大小調整模式。不同的大小調整模式的效果如下:
- "auto": 根據畫筆粗細值調整海龜的外觀。
- "user": 根據拉伸因子和輪廓寬度 (outline) 值調整海龜的外觀,兩者是由 [`shapesize()`](#turtle.shapesize "turtle.shapesize") 設置的。
- "noresize": 不調整海龜的外觀大小。
大小調整模式 ("user") 會在 [`shapesize()`](#turtle.shapesize "turtle.shapesize") 帶參數調用時生效。
```
>>> 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** -- 正數值
返回或設置畫筆的屬性 x/y-拉伸因子和/或輪廓。設置大小調整模式為 "user"。當且僅當大小調整模式設為 "user" 時海龜會基于其拉伸因子調整外觀: *stretch\_wid* 為垂直于其朝向的寬度拉伸因子,*stretch\_len* 為平等于其朝向的長度拉伸因子,決定形狀輪廓線的粗細。
```
>>> 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 指定的剪切因子即剪切角度的切線來剪切海龜形狀。*不* 改變海龜的朝向 (移動方向)。如未指定 shear 參數: 返回當前的剪切因子即剪切角度的切線,與海龜朝向平行的線條將被剪切。
```
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.shearfactor(0.5)
>>> turtle.shearfactor()
0.5
```
`turtle.``tilt`(*angle*)參數**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** -- 一個數值
旋轉海龜形狀使其指向 *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** -- 一個數值 (可選)
設置或返回當前的傾角。如果指定 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。行列式 t11 \* t22 - t12 \* t21 的值不能為零,否則會出錯。根據指定的矩陣修改拉伸因子,剪切因子和傾角。
```
>>> 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 (鼠標左鍵)
- **add** -- `True` 或 `False` -- 如為 `True` 則將添加一個新綁定,否則將取代先前的綁定
將 *fun* 指定的函數綁定到鼠標點擊此海龜事件。如果 *fun* 值為 `None`,則移除現有的綁定。以下為使用匿名海龜即過程式的示例:
```
>>> 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 (鼠標左鍵)
- **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) # 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 (鼠標左鍵)
- **add** -- `True` 或 `False` -- 如為 `True` 則將添加一個新綁定,否則將取代先前的綁定
將 *fun* 指定的函數綁定到在此海龜上移動鼠標事件。如果 *fun* 值為 `None`,則移除現有的綁定。
注: 在海龜上移動鼠標事件之前應先發生在此海龜上點擊鼠標事件。
```
>>> turtle.ondrag(turtle.goto)
```
在此之后點擊并拖動海龜可在屏幕上手繪線條 (如果畫筆為落下)。
### 特殊海龜方法
`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`](#turtle.TurtleScreen "turtle.TurtleScreen") 類對象。該對象將可調用 TurtleScreen 方法。
```
>>> ts = turtle.getscreen()
>>> ts
<turtle._Screen object at 0x...>
>>> ts.bgcolor("pink")
```
`turtle.``setundobuffer`(*size*)參數**size** -- 一個整型數值或 `None`
設置或禁用撤消緩沖區。如果 *size* 為一個整型數則將開辟一個指定大小的空緩沖區。*size* 表示可使用 [`undo()`](#turtle.undo "turtle.undo") 方法/函數撤消的海龜命令的次數上限。如果 *size* 為 `None` 則禁用撤消緩沖區。
```
>>> turtle.setundobuffer(42)
```
`turtle.``undobufferentries`()返回撤銷緩沖區里的條目數。
```
>>> while undobufferentries():
... undo()
```
### 復合形狀
要使用由多個不同顏色多邊形構成的復合海龜形狀,你必須明確地使用輔助類 [`Shape`](#turtle.Shape "turtle.Shape"),具體步驟如下:
1. 創建一個空 Shape 對象,類型為 "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 對象的形狀列表并使用它:
```
>>> register_shape("myshape", s)
>>> shape("myshape")
```
注解
[`Shape`](#turtle.Shape "turtle.Shape") 類在 [`register_shape()`](#turtle.register_shape "turtle.register_shape") 方法的內部以多種方式使用。應用程序編寫者 *只有* 在使用上述的復合形狀時才需要處理 Shape 類。
## TurtleScreen/Screen 方法及對應函數
本節中的大部分示例都使用 TurtleScreen 類的一個實例,命名為 `screen`。
### 窗口控制
`turtle.``bgcolor`(*\*args*)參數**args** -- 一個顏色字符串或三個取值范圍 0..colormode 內的數值或一個取值范圍相同的數值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`
設置背景圖片或返回當前背景圖片名稱。如果 *picname* 為一個文件名,則將相應圖片設為背景。如果 *picname* 為 `"nopic"`,則刪除當前背景圖片。如果 *picname* 為 `None`,則返回當前背景圖片文件名。:
```
>>> screen.bgpic()
'nopic'
>>> screen.bgpic("landscape.gif")
>>> screen.bgpic()
"landscape.gif"
```
`turtle.``clear`()`turtle.``clearscreen`()從中刪除所有海龜的全部繪圖。將已清空的 TurtleScreen 重置為初始狀態: 白色背景,無背景片,無事件綁定并啟用追蹤。
注解
此 TurtleScreen 方法作為全局函數時只有一個名字 `clearscreen`。全局函數 `clear` 所對應的是 Turtle 方法 `clear`。
`turtle.``reset`()`turtle.``resetscreen`()重置屏幕上的所有海龜為其初始狀態。
注解
此 TurtleScreen 方法作為全局函數時只有一個名字 `resetscreen`。全局函數 `reset` 所對應的是 Turtle 方法 `reset`。
`turtle.``screensize`(*canvwidth=None*, *canvheight=None*, *bg=None*)參數- **canvwidth** -- 正整型數,以像素表示畫布的新寬度值
- **canvheight** -- 正整型數,以像素表示畫面的新高度值
- **bg** -- 顏色字符串或顏色元組,新的背景顏色
如未指定任何參數,則返回當前的 (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()`](#turtle.delay "turtle.delay"))。
```
>>> screen.tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
... fd(dist)
... rt(90)
... dist += 2
```
`turtle.``update`()執行一次 TurtleScreen 刷新。在禁用追蹤時使用。
另參見 RawTurtle/Turtle 方法 [`speed()`](#turtle.speed "turtle.speed")。
### 使用屏幕事件
`turtle.``listen`(*xdummy=None*, *ydummy=None*)設置焦點到 TurtleScreen (以便接收按鍵事件)。使用兩個 Dummy 參數以便能夠傳遞 [`listen()`](#turtle.listen "turtle.listen") 給 onclick 方法。
`turtle.``onkey`(*fun*, *key*)`turtle.``onkeyrelease`(*fun*, *key*)參數- **fun** -- 一個無參數的函數或 `None`
- **key** -- 一個字符串: 鍵 (例如 "a") 或鍵標 (例如 "space")
綁定 *fun* 指定的函數到按鍵釋放事件。如果 *fun* 值為 `None`,則移除事件綁定。注: 為了能夠注冊按鍵事件,TurtleScreen 必須得到焦點。(參見 method [`listen()`](#turtle.listen "turtle.listen") 方法。)
```
>>> def f():
... fd(50)
... lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()
```
`turtle.``onkeypress`(*fun*, *key=None*)參數- **fun** -- 一個無參數的函數或 `None`
- **key** -- 一個字符串: 鍵 (例如 "a") 或鍵標 (例如 "space")
綁定 *fun* 指定的函數到指定鍵的按下事件。如未指定鍵則綁定到任意鍵的按下事件。注: 為了能夠注冊按鍵事件,必須得到焦點。(參見 [`listen()`](#turtle.listen "turtle.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 (鼠標左鍵)
- **add** -- `True` 或 `False` -- 如為 `True` 則將添加一個新綁定,否則將取代先前的綁定
綁定 *fun* 指定的函數到鼠標點擊屏幕事件。如果 *fun* 值為 `None`,則移除現有的綁定。
以下示例使用一個 TurtleScreen 實例 `screen` 和一個 Turtle 實例 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** -- 數值 (可選)
彈出一個對話框窗口用來輸入一個數值。title 為對話框窗口的標題,prompt 為一條文本,通常用來描述要輸入的數值信息。default: 默認值, minval: 可輸入的最小值, maxval: 可輸入的最大值。輸入數值的必須在指定的 minval .. maxval 范圍之內,否則將給出一條提示,對話框保持打開等待修改。返回輸入的數值。如果對話框被取消則返回 `None`。:
```
>>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
```
### 設置與特殊方法
`turtle.``mode`(*mode=None*)參數**mode** -- 字符串 "standard", "logo" 或 "world" 其中之一
設置海龜模式 ("standard", "logo" 或 "world") 并執行重置。如未指定模式則返回當前的模式。
"standard" 模式與舊的 [`turtle`](#module-turtle "turtle: An educational framework for simple graphics applications") 兼容。"logo" 模式與大部分 Logo 海龜繪圖兼容。"world" 模式使用用戶自定義的 "世界坐標系"。**注意**: 在此模式下,如果 `x/y` 單位比率不等于 1 則角度會顯得扭曲。
模式
初始海龜朝向
正數角度
"standard"
朝右 (東)
逆時針
"logo"
朝上 (北)
順時針
```
>>> mode("logo") # resets turtle heading to north
>>> mode()
'logo'
```
`turtle.``colormode`(*cmode=None*)參數**cmode** -- 數值 1.0 或 255 其中之一
返回顏色模式或將其設為 1.0 或 255。構成顏色三元組的 *r*, *g*, *b* 數值必須在 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* 為一個 gif 文件的文件名, *shape* 為 `None`: 安裝相應的圖像形狀。:
```
>>> screen.register_shape("turtle.gif")
```
注解
當海龜轉向時圖像形狀 *不會* 轉動,因此無法顯示海龜的朝向!
2. *name* 為指定的字符串,*shape* 為由坐標值對構成的元組: 安裝相應的多邊形形狀。
```
>>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))
```
3. *name* 為指定的字符串, 為一個 (復合) [`Shape`](#turtle.Shape "turtle.Shape") 類對象: 安裝相應的復合形狀。
將一個海龜形狀加入 TurtleScreen 的形狀列表。只有這樣注冊過的形狀才能通過執行 `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
```
### Screen 專有方法, 而非繼承自 TurtleScreen
`turtle.``bye`()關閉海龜繪圖窗口。
`turtle.``exitonclick`()將 bye() 方法綁定到 Screen 上的鼠標點擊事件。
如果配置字典中 "using\_IDLE" 的值為 `False` (默認值) 則同時進入主事件循環。注: 如果啟動 IDLE 時使用了 `-n` 開關 (無子進程),`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** -- 一個 `tkinter.Canvas` , [`ScrolledCanvas`](#turtle.ScrolledCanvas "turtle.ScrolledCanvas") 或 [`TurtleScreen`](#turtle.TurtleScreen "turtle.TurtleScreen") 類對象
創建一個海龜。海龜對象具有 "Turtle/RawTurtle 方法" 一節所述的全部方法。
*class* `turtle.``Turtle`RawTurtle 的子類,具有相同的接口,但其繪圖場所為默認的 [`Screen`](#turtle.Screen "turtle.Screen") 類對象,在首次使用時自動創建。
*class* `turtle.``TurtleScreen`(*cv*)參數**cv** -- 一個 `tkinter.Canvas` 類對象
提供面向屏幕的方法例如 `setbg()` 等。說明見上文。
*class* `turtle.``Screen`TurtleScreen 的子類,[增加了四個方法](#screenspecific).
*class* `turtle.``ScrolledCanvas`(*master*)參數**master** -- 可容納 ScrolledCanvas 的 Tkinter 部件,即添加了滾動條的 Tkinter-canvas
由 Screen 類使用,使其能夠自動提供一個 ScrolledCanvas 作為海龜的繪圖場所。
*class* `turtle.``Shape`(*type\_*, *data*)參數**type\_** -- 字符串 "polygon", "image", "compound" 其中之一
實現形狀的數據結構。`(type_, data)` 必須遵循以下定義:
*type\_*
*data*
"polygon"
一個多邊形元組,即由坐標值對構成的元組
"image"
一個圖片 (此形式僅限內部使用!)
"compound"
`None` (復合形狀必須使用 [`addcomponent()`](#turtle.Shape.addcomponent "turtle.Shape.addcomponent") 方法來構建)
`addcomponent`(*poly*, *fill*, *outline=None*)參數- **poly** -- 一個多邊形,即由數值對構成的元組
- **fill** -- 一種顏色,將用來填充 *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()
```
參見 [復合形狀](#compoundshapes)。
*class* `turtle.``Vec2D`(*x*, *y*)一個二維矢量類,用來作為實現海龜繪圖的輔助類。也可能在海龜繪圖程序中使用。派生自元組,因此矢量也屬于元組!
提供的運算 (*a*, *b* 為矢量, *k* 為數值):
- `a + b` 矢量加法
- `a - b` 矢量減法
- `a * b` 內積
- `k * a` 和 `a * k` 與標量相乘
- `abs(a)` a 的絕對值
- `a.rotate(angle)` 旋轉
## 幫助與配置
### 如何使用幫助
Screen 和 Turtle 類的公用方法以文檔字符串提供了詳細的文檔。因此可以利用 Python 幫助工具獲取這些在線幫助信息:
- 當使用 IDLE 時,輸入函數/方法調用將彈出工具提示顯示其簽名和文檔字符串的頭幾行。
- 對文法或函數調用 [`help()`](functions.xhtml#help "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 指定的 Python 腳本文件。此函數必須顯示地調用 (海龜繪圖類并不使用此函數)。文檔字符串字典將被寫入到 Python 腳本文件 `filename.py`。該文件可作為模板用來將文檔字符串翻譯為不同語言。
如果你 (或你的學生) 想使用本國語言版本的 [`turtle`](#module-turtle "turtle: An educational framework for simple graphics applications") 在線幫助,你必須翻譯文檔字符串并保存結果文件,例如 `turtle_docstringdict_german.py`.
如果你在 `turtle.cfg` 文件中加入了相應的條目,此字典將在導入模塊時被讀取并替代原有的英文版文檔字符串。
在撰寫本文檔時已經有了德語和意大利語版的文檔字符串字典。(更多需求請聯系 [glingl@aon.at](mailto:glingl%40aon.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)` 查看。
- 如果你想使用無填充色 (即令海龜變透明),你必須寫 `fillcolor = ""` (但 cfg 文件中所有非空字符串都不可加引號)。
- 如果你想令海龜反映其狀態,你必須使用 `resizemode = auto`。
- 如果你設置語言例如 `language = italian` 則文檔字符串字典 `turtle_docstringdict_italian.py` 將在導入模塊時被加載 (如果導入路徑即 [`turtle`](#module-turtle "turtle: An educational framework for simple graphics applications") 的目錄中存在此文件。
- *exampleturtle* 和 *examplescreen* 條目定義了相應對象在文檔字符串中顯示的名稱。方法文檔字符串轉換為函數文檔字符串時將從文檔字符串中刪去這些名稱。
- *using\_IDLE*: 如果你經常使用 IDLE 并啟用其 -n 開關 ("無子進程") 則應將此項設為 `True`,這將阻止 [`exitonclick()`](#turtle.exitonclick "turtle.exitonclick") 進入主事件循環。
`turtle.cfg` 文件可以保存于 [`turtle`](#module-turtle "turtle: An educational framework for simple graphics applications") 所在目錄,當前工作目錄也可以有一個同名文件。后者會重載覆蓋前者的設置。
`Lib/turtledemo` 目錄中也有一個 `turtle.cfg` 文件。你可以將其作為示例進行研究,并在運行演示時查看其作用效果 (但最好不要在演示查看器中運行)。
## [`turtledemo`](#module-turtledemo "turtledemo: A viewer for example turtle scripts") --- 演示腳本集
[`turtledemo`](#module-turtledemo "turtledemo: A viewer for example turtle scripts") 包匯集了一組演示腳本。這些腳本可以通過以下命令打開所提供的演示查看器運行和查看:
```
python -m turtledemo
```
此外,你也可以單獨運行其中的演示腳本。例如,:
```
python -m turtledemo.bytedesign
```
[`turtledemo`](#module-turtledemo "turtledemo: A viewer for example turtle scripts") 包目錄中的內容:
- 一個演示查看器 `__main__.py`,可用來查看腳本的源碼并即時運行。
- 多個腳本文件,演示 [`turtle`](#module-turtle "turtle: An educational framework for simple graphics applications") 模塊的不同特性。所有示例可通過 Examples 菜單打開。也可以單獨運行每個腳本。
- 一個 `turtle.cfg` 文件,作為說明如何編寫并使用模塊配置文件的示例模板。
演示腳本清單如下:
名稱
描述
相關特性
bytedesign
復雜的傳統海龜繪圖模式
`tracer()`, delay, `update()`
chaos
繪制 Verhulst 動態模型,演示通過計算機的運算可能會生成令人驚嘆的結果
世界坐標系
clock
繪制模擬時鐘顯示本機的當前時間
海龜作為表針, ontimer
colormixer
試驗 r, g, b 顏色模式
`ondrag()` 當鼠標拖動
forest
繪制 3 棵廣度優先樹
隨機化
fractalcurves
繪制 Hilbert & Koch 曲線
遞歸
lindenmayer
文化數學 (印度裝飾藝術)
L-系統
minimal\_hanoi
漢諾塔
矩形海龜作為漢諾盤 (shape, shapesize)
nim
玩經典的“尼姆”游戲,開始時有三堆小棒,與電腦對戰。
海龜作為小棒,事件驅動 (鼠標, 鍵盤)
paint
超極簡主義繪畫程序
`onclick()` 當鼠標點擊
peace
初級技巧
海龜: 外觀與動畫
penrose
非周期性地使用風箏和飛鏢形狀鋪滿平面
`stamp()` 印章
planet\_and\_moon
模擬引力系統
復合開關, `Vec2D` 類
round\_dance
兩兩相對并不斷旋轉舞蹈的海龜
復合形狀, clone shapesize, tilt, get\_shapepoly, update
sorting\_animate
動態演示不同的排序方法
簡單對齊, 隨機化
tree
一棵 (圖形化的) 廣度優先樹 (使用生成器)
`clone()` 克隆
two\_canvases
簡單設計
兩塊畫布上的海龜
wikipedia
一個來自介紹海龜繪圖的維基百科文章的圖案
`clone()`, `undo()`
yinyang
另一個初級示例
`circle()` 畫圓
祝你玩得開心!
## Python 2.6 之后的變化
- `Turtle.tracer()`, `Turtle.window_width()` 和 `Turtle.window_height()` 方法已被去除。具有這些名稱和功能的方法現在只限于 `Screen` 類的方法。但其對應的函數仍然可用。(實際上在 Python 2.6 中這些方法就已經只是從對應的 `TurtleScreen`/`Screen` 類的方法復制而來。)
- `Turtle.fill()` 方法已被去除。`begin_fill()` 和 `end_fill()` 的行為則有細微改變: 現在每個填充過程必須以一個 `end_fill()` 調用來結束。
- 新增了一個 `Turtle.filling()` 方法。該方法返回一個布爾值: 如果填充過程正在進行為 `True`,否則為 `False`。此行為相當于 Python 2.6 中不帶參數的 `fill()` 調用。
## Python 3.0 之后的變化
- 新增了 `Turtle.shearfactor()`, `Turtle.shapetransform()` 和 `Turtle.get_shapepoly()` 方法。這樣就可以使用所有標準線性變換來調整海龜形狀。`Turtle.tiltangle()` 的功能已被加強: 現在可被用來獲取或設置傾角。`Turtle.settiltangle()` 已棄用。
- 新增了 `Screen.onkeypress()` 方法作為對 `Screen.onkey()` 的補充,實際就是將行為綁定到 keyrelease 事件。后者相應增加了一個別名: `Screen.onkeyrelease()`。
- 新增了 `Screen.mainloop()` 方法。這樣當僅需使用 Screen 和 Turtle 對象時不需要再額外導入 `mainloop()`。
- 新增了兩個方法 `Screen.textinput()` 和 `Screen.numinput()`。用來彈出對話框接受輸入并分別返回字符串和數值。
- 兩個新的示例腳本 `tdemo_nim.py` 和 `tdemo_round_dance.py` 被加入到 `Lib/turtledemo` 目錄中。
### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](cmd.xhtml "cmd --- 支持面向行的命令解釋器") |
- [上一頁](frameworks.xhtml "程序框架") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 標準庫](index.xhtml) ?
- [程序框架](frameworks.xhtml) ?
- $('.inline-search').show(0); |
? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation.
Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/)
最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)?
使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
- Python文檔內容
- Python 有什么新變化?
- Python 3.7 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- C API 的改變
- 構建的改變
- 性能優化
- 其他 CPython 實現的改變
- 已棄用的 Python 行為
- 已棄用的 Python 模塊、函數和方法
- 已棄用的 C API 函數和類型
- 平臺支持的移除
- API 與特性的移除
- 移除的模塊
- Windows 專屬的改變
- 移植到 Python 3.7
- Python 3.7.1 中的重要變化
- Python 3.7.2 中的重要變化
- Python 3.6 有什么新變化A
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 其他改進
- 棄用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要變化
- Python 3.6.4 中的重要變化
- Python 3.6.5 中的重要變化
- Python 3.6.7 中的重要變化
- Python 3.5 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- Other module-level changes
- 性能優化
- Build and C API Changes
- 棄用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 發布重點
- 新的特性
- 新增模塊
- 改進的模塊
- CPython Implementation Changes
- 棄用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 發布重點
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他語言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 棄用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 多線程
- 性能優化
- Unicode
- Codecs
- 文檔
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 性能優化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他語言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新變化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他語言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他語言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推導式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最終版
- Python 3.7.3 發布候選版 1
- Python 3.7.2 最終版
- Python 3.7.2 發布候選版 1
- Python 3.7.1 最終版
- Python 3.7.1 RC 2版本
- Python 3.7.1 發布候選版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 課前甜點
- 使用 Python 解釋器
- 調用解釋器
- 解釋器的運行環境
- Python 的非正式介紹
- Python 作為計算器使用
- 走向編程的第一步
- 其他流程控制工具
- if 語句
- for 語句
- range() 函數
- break 和 continue 語句,以及循環中的 else 子句
- pass 語句
- 定義函數
- 函數定義的更多形式
- 小插曲:編碼風格
- 數據結構
- 列表的更多特性
- del 語句
- 元組和序列
- 集合
- 字典
- 循環的技巧
- 深入條件控制
- 序列和其它類型的比較
- 模塊
- 有關模塊的更多信息
- 標準模塊
- dir() 函數
- 包
- 輸入輸出
- 更漂亮的輸出格式
- 讀寫文件
- 錯誤和異常
- 語法錯誤
- 異常
- 處理異常
- 拋出異常
- 用戶自定義異常
- 定義清理操作
- 預定義的清理操作
- 類
- 名稱和對象
- Python 作用域和命名空間
- 初探類
- 補充說明
- 繼承
- 私有變量
- 雜項說明
- 迭代器
- 生成器
- 生成器表達式
- 標準庫簡介
- 操作系統接口
- 文件通配符
- 命令行參數
- 錯誤輸出重定向和程序終止
- 字符串模式匹配
- 數學
- 互聯網訪問
- 日期和時間
- 數據壓縮
- 性能測量
- 質量控制
- 自帶電池
- 標準庫簡介 —— 第二部分
- 格式化輸出
- 模板
- 使用二進制數據記錄格式
- 多線程
- 日志
- 弱引用
- 用于操作列表的工具
- 十進制浮點運算
- 虛擬環境和包
- 概述
- 創建虛擬環境
- 使用pip管理包
- 接下來?
- 交互式編輯和編輯歷史
- Tab 補全和編輯歷史
- 默認交互式解釋器的替代品
- 浮點算術:爭議和限制
- 表示性錯誤
- 附錄
- 交互模式
- 安裝和使用 Python
- 命令行與環境
- 命令行
- 環境變量
- 在Unix平臺中使用Python
- 獲取最新版本的Python
- 構建Python
- 與Python相關的路徑和文件
- 雜項
- 編輯器和集成開發環境
- 在Windows上使用 Python
- 完整安裝程序
- Microsoft Store包
- nuget.org 安裝包
- 可嵌入的包
- 替代捆綁包
- 配置Python
- 適用于Windows的Python啟動器
- 查找模塊
- 附加模塊
- 在Windows上編譯Python
- 其他平臺
- 在蘋果系統上使用 Python
- 獲取和安裝 MacPython
- IDE
- 安裝額外的 Python 包
- Mac 上的圖形界面編程
- 在 Mac 上分發 Python 應用程序
- 其他資源
- Python 語言參考
- 概述
- 其他實現
- 標注
- 詞法分析
- 行結構
- 其他形符
- 標識符和關鍵字
- 字面值
- 運算符
- 分隔符
- 數據模型
- 對象、值與類型
- 標準類型層級結構
- 特殊方法名稱
- 協程
- 執行模型
- 程序的結構
- 命名與綁定
- 異常
- 導入系統
- importlib
- 包
- 搜索
- 加載
- 基于路徑的查找器
- 替換標準導入系統
- Package Relative Imports
- 有關 main 的特殊事項
- 開放問題項
- 參考文獻
- 表達式
- 算術轉換
- 原子
- 原型
- await 表達式
- 冪運算符
- 一元算術和位運算
- 二元算術運算符
- 移位運算
- 二元位運算
- 比較運算
- 布爾運算
- 條件表達式
- lambda 表達式
- 表達式列表
- 求值順序
- 運算符優先級
- 簡單語句
- 表達式語句
- 賦值語句
- assert 語句
- pass 語句
- del 語句
- return 語句
- yield 語句
- raise 語句
- break 語句
- continue 語句
- import 語句
- global 語句
- nonlocal 語句
- 復合語句
- if 語句
- while 語句
- for 語句
- try 語句
- with 語句
- 函數定義
- 類定義
- 協程
- 最高層級組件
- 完整的 Python 程序
- 文件輸入
- 交互式輸入
- 表達式輸入
- 完整的語法規范
- Python 標準庫
- 概述
- 可用性注釋
- 內置函數
- 內置常量
- 由 site 模塊添加的常量
- 內置類型
- 邏輯值檢測
- 布爾運算 — and, or, not
- 比較
- 數字類型 — int, float, complex
- 迭代器類型
- 序列類型 — list, tuple, range
- 文本序列類型 — str
- 二進制序列類型 — bytes, bytearray, memoryview
- 集合類型 — set, frozenset
- 映射類型 — dict
- 上下文管理器類型
- 其他內置類型
- 特殊屬性
- 內置異常
- 基類
- 具體異常
- 警告
- 異常層次結構
- 文本處理服務
- string — 常見的字符串操作
- re — 正則表達式操作
- 模塊 difflib 是一個計算差異的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 數據庫
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函數
- 二進制數據服務
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 數據類型
- datetime — 基礎日期/時間數據類型
- calendar — General calendar-related functions
- collections — 容器數據類型
- collections.abc — 容器的抽象基類
- heapq — 堆隊列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 淺層 (shallow) 和深層 (deep) 復制操作
- pprint — 數據美化輸出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 數字和數學模塊
- numbers — 數字的抽象基類
- math — 數學函數
- cmath — Mathematical functions for complex numbers
- decimal — 十進制定點和浮點運算
- fractions — 分數
- random — 生成偽隨機數
- statistics — Mathematical statistics functions
- 函數式編程模塊
- itertools — 為高效循環而創建迭代器的函數
- functools — 高階函數和可調用對象上的操作
- operator — 標準運算符替代函數
- 文件和目錄訪問
- pathlib — 面向對象的文件系統路徑
- os.path — 常見路徑操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路徑操作函數
- 數據持久化
- pickle —— Python 對象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 數據庫 DB-API 2.0 接口模塊
- 數據壓縮和存檔
- zlib — 與 gzip 兼容的壓縮
- gzip — 對 gzip 格式的支持
- bz2 — 對 bzip2 壓縮算法的支持
- lzma — 用 LZMA 算法壓縮
- zipfile — 在 ZIP 歸檔中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件讀寫
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服務
- hashlib — 安全哈希與消息摘要
- hmac — 基于密鑰的消息驗證
- secrets — Generate secure random numbers for managing secrets
- 通用操作系統服務
- os — 操作系統接口模塊
- io — 處理流的核心工具
- time — 時間的訪問和轉換
- argparse — 命令行選項、參數和子命令解析器
- getopt — C-style parser for command line options
- 模塊 logging — Python 的日志記錄工具
- logging.config — 日志記錄配置
- logging.handlers — Logging handlers
- getpass — 便攜式密碼輸入工具
- curses — 終端字符單元顯示的處理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函數庫
- 并發執行
- threading — 基于線程的并行
- multiprocessing — 基于進程的并行
- concurrent 包
- concurrent.futures — 啟動并行任務
- subprocess — 子進程管理
- sched — 事件調度器
- queue — 一個同步的隊列類
- _thread — 底層多線程 API
- _dummy_thread — _thread 的替代模塊
- dummy_threading — 可直接替代 threading 模塊。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 網絡和進程間通信
- asyncio — 異步 I/O
- socket — 底層網絡接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高級 I/O 復用庫
- asyncore — 異步socket處理器
- asynchat — 異步 socket 指令/響應 處理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互聯網數據處理
- email — 電子郵件與 MIME 處理包
- json — JSON 編碼和解碼器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 數據編碼
- binhex — 對binhex4文件進行編碼和解碼
- binascii — 二進制和 ASCII 碼互轉
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 結構化標記處理工具
- html — 超文本標記語言支持
- html.parser — 簡單的 HTML 和 XHTML 解析器
- html.entities — HTML 一般實體的定義
- XML處理模塊
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互聯網協議和支持
- webbrowser — 方便的Web瀏覽器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 處理模塊
- urllib.request — 用于打開 URL 的可擴展庫
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模塊
- http.client — HTTP協議客戶端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP協議客戶端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服務器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服務端與客戶端模塊
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒體服務
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 讀寫 Sun AU 文件
- wave — 讀寫WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推測圖像類型
- sndhdr — 推測聲音文件的類型
- ossaudiodev — Access to OSS-compatible audio devices
- 國際化
- gettext — 多語種國際化服務
- locale — 國際化服務
- 程序框架
- turtle — 海龜繪圖
- cmd — 支持面向行的命令解釋器
- shlex — Simple lexical analysis
- Tk圖形用戶界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滾動文字控件
- IDLE
- 其他圖形用戶界面(GUI)包
- 開發工具
- typing — 類型標注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 單元測試框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自動將 Python 2 代碼轉為 Python 3 代碼
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 調試和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 測量小代碼片段的執行時間
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 軟件打包和分發
- distutils — 構建和安裝 Python 模塊
- ensurepip — Bootstrapping the pip installer
- venv — 創建虛擬環境
- zipapp — Manage executable Python zip archives
- Python運行時服務
- sys — 系統相關的參數和函數
- sysconfig — Provide access to Python's configuration information
- builtins — 內建對象
- main — 頂層腳本環境
- warnings — Warning control
- dataclasses — 數據類
- contextlib — Utilities for with-statement contexts
- abc — 抽象基類
- atexit — 退出處理器
- traceback — Print or retrieve a stack traceback
- future — Future 語句定義
- gc — 垃圾回收器接口
- inspect — 檢查對象
- site — Site-specific configuration hook
- 自定義 Python 解釋器
- code — Interpreter base classes
- codeop — Compile Python code
- 導入模塊
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找腳本使用的模塊
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 語言服務
- parser — Access Python parse trees
- ast — 抽象語法樹
- symtable — Access to the compiler's symbol tables
- symbol — 與 Python 解析樹一起使用的常量
- token — 與Python解析樹一起使用的常量
- keyword — 檢驗Python關鍵字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊縮進檢測
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字節碼反匯編器
- pickletools — Tools for pickle developers
- 雜項服務
- formatter — Generic output formatting
- Windows系統相關模塊
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注冊表訪問
- winsound — Sound-playing interface for Windows
- Unix 專有服務
- posix — The most common POSIX system calls
- pwd — 用戶密碼數據庫
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 終端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 庫例程
- 被取代的模塊
- optparse — Parser for command line options
- imp — Access the import internals
- 未創建文檔的模塊
- 平臺特定模塊
- 擴展和嵌入 Python 解釋器
- 推薦的第三方工具
- 不使用第三方工具創建擴展
- 使用 C 或 C++ 擴展 Python
- 自定義擴展類型:教程
- 定義擴展類型:已分類主題
- 構建C/C++擴展
- 在Windows平臺編譯C和C++擴展
- 在更大的應用程序中嵌入 CPython 運行時
- Embedding Python in Another Application
- Python/C API 參考手冊
- 概述
- 代碼標準
- 包含文件
- 有用的宏
- 對象、類型和引用計數
- 異常
- 嵌入Python
- 調試構建
- 穩定的應用程序二進制接口
- The Very High Level Layer
- Reference Counting
- 異常處理
- Printing and clearing
- 拋出異常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 標準異常
- 標準警告類別
- 工具
- 操作系統實用程序
- 系統功能
- 過程控制
- 導入模塊
- Data marshalling support
- 語句解釋及變量編譯
- 字符串轉換與格式化
- 反射
- 編解碼器注冊與支持功能
- 抽象對象層
- Object Protocol
- 數字協議
- Sequence Protocol
- Mapping Protocol
- 迭代器協議
- 緩沖協議
- Old Buffer Protocol
- 具體的對象層
- 基本對象
- 數值對象
- 序列對象
- 容器對象
- 函數對象
- 其他對象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置變量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 內存管理
- 概述
- 原始內存接口
- Memory Interface
- 對象分配器
- 默認內存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 對象實現支持
- 在堆中分配對象
- Common Object Structures
- Type 對象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使對象類型支持循環垃圾回收
- API 和 ABI 版本管理
- 分發 Python 模塊
- 關鍵術語
- 開源許可與協作
- 安裝工具
- 閱讀指南
- 我該如何...?
- ...為我的項目選擇一個名字?
- ...創建和分發二進制擴展?
- 安裝 Python 模塊
- 關鍵術語
- 基本使用
- 我應如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安裝 pip ?
- ... 只為當前用戶安裝軟件包?
- ... 安裝科學計算類 Python 軟件包?
- ... 使用并行安裝的多個 Python 版本?
- 常見的安裝問題
- 在 Linux 的系統 Python 版本上安裝
- 未安裝 pip
- 安裝二進制編譯擴展
- Python 常用指引
- 將 Python 2 代碼遷移到 Python 3
- 簡要說明
- 詳情
- 將擴展模塊移植到 Python 3
- 條件編譯
- 對象API的更改
- 模塊初始化和狀態
- CObject 替換為 Capsule
- 其他選項
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 實現描述器
- 摘要
- 定義和簡介
- 描述器協議
- 發起調用描述符
- 描述符示例
- Properties
- 函數和方法
- Static Methods and Class Methods
- 函數式編程指引
- 概述
- 迭代器
- 生成器表達式和列表推導式
- 生成器
- 內置函數
- itertools 模塊
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文獻
- 日志 HOWTO
- 日志基礎教程
- 進階日志教程
- 日志級別
- 有用的處理程序
- 記錄日志中引發的異常
- 使用任意對象作為消息
- 優化
- 日志操作手冊
- 在多個模塊中使用日志
- 在多線程中使用日志
- 使用多個日志處理器和多種格式化
- 在多個地方記錄日志
- 日志服務器配置示例
- 處理日志處理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正則表達式HOWTO
- 概述
- 簡單模式
- 使用正則表達式
- 更多模式能力
- 修改字符串
- 常見問題
- 反饋
- 套接字編程指南
- 套接字
- 創建套接字
- 使用一個套接字
- 斷開連接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 關鍵函數
- Operator 模塊函數
- 升序和降序
- 排序穩定性和排序復雜度
- 使用裝飾-排序-去裝飾的舊方法
- 使用 cmp 參數的舊方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包獲取網絡資源
- 概述
- Fetching URLs
- 處理異常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 腳注
- Argparse 教程
- 概念
- 基礎
- 位置參數介紹
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模塊介紹
- 創建 Address/Network/Interface 對象
- 審查 Address/Network/Interface 對象
- Network 作為 Address 列表
- 比較
- 將IP地址與其他模塊一起使用
- 實例創建失敗時獲取更多詳細信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 檢測CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常見問題
- Python常見問題
- 一般信息
- 現實世界中的 Python
- 編程常見問題
- 一般問題
- 核心語言
- 數字和字符串
- 性能
- 序列(元組/列表)
- 對象
- 模塊
- 設計和歷史常見問題
- 為什么Python使用縮進來分組語句?
- 為什么簡單的算術運算得到奇怪的結果?
- 為什么浮點計算不準確?
- 為什么Python字符串是不可變的?
- 為什么必須在方法定義和調用中顯式使用“self”?
- 為什么不能在表達式中賦值?
- 為什么Python對某些功能(例如list.index())使用方法來實現,而其他功能(例如len(List))使用函數實現?
- 為什么 join()是一個字符串方法而不是列表或元組方法?
- 異常有多快?
- 為什么Python中沒有switch或case語句?
- 難道不能在解釋器中模擬線程,而非得依賴特定于操作系統的線程實現嗎?
- 為什么lambda表達式不能包含語句?
- 可以將Python編譯為機器代碼,C或其他語言嗎?
- Python如何管理內存?
- 為什么CPython不使用更傳統的垃圾回收方案?
- CPython退出時為什么不釋放所有內存?
- 為什么有單獨的元組和列表數據類型?
- 列表是如何在CPython中實現的?
- 字典是如何在CPython中實現的?
- 為什么字典key必須是不可變的?
- 為什么 list.sort() 沒有返回排序列表?
- 如何在Python中指定和實施接口規范?
- 為什么沒有goto?
- 為什么原始字符串(r-strings)不能以反斜杠結尾?
- 為什么Python沒有屬性賦值的“with”語句?
- 為什么 if/while/def/class語句需要冒號?
- 為什么Python在列表和元組的末尾允許使用逗號?
- 代碼庫和插件 FAQ
- 通用的代碼庫問題
- 通用任務
- 線程相關
- 輸入輸出
- 網絡 / Internet 編程
- 數據庫
- 數學和數字
- 擴展/嵌入常見問題
- 可以使用C語言中創建自己的函數嗎?
- 可以使用C++語言中創建自己的函數嗎?
- C很難寫,有沒有其他選擇?
- 如何從C執行任意Python語句?
- 如何從C中評估任意Python表達式?
- 如何從Python對象中提取C的值?
- 如何使用Py_BuildValue()創建任意長度的元組?
- 如何從C調用對象的方法?
- 如何捕獲PyErr_Print()(或打印到stdout / stderr的任何內容)的輸出?
- 如何從C訪問用Python編寫的模塊?
- 如何從Python接口到C ++對象?
- 我使用Setup文件添加了一個模塊,為什么make失敗了?
- 如何調試擴展?
- 我想在Linux系統上編譯一個Python模塊,但是缺少一些文件。為什么?
- 如何區分“輸入不完整”和“輸入無效”?
- 如何找到未定義的g++符號__builtin_new或__pure_virtual?
- 能否創建一個對象類,其中部分方法在C中實現,而其他方法在Python中實現(例如通過繼承)?
- Python在Windows上的常見問題
- 我怎樣在Windows下運行一個Python程序?
- 我怎么讓 Python 腳本可執行?
- 為什么有時候 Python 程序會啟動緩慢?
- 我怎樣使用Python腳本制作可執行文件?
- *.pyd 文件和DLL文件相同嗎?
- 我怎樣將Python嵌入一個Windows程序?
- 如何讓編輯器不要在我的 Python 源代碼中插入 tab ?
- 如何在不阻塞的情況下檢查按鍵?
- 圖形用戶界面(GUI)常見問題
- 圖形界面常見問題
- Python 是否有平臺無關的圖形界面工具包?
- 有哪些Python的GUI工具是某個平臺專用的?
- 有關Tkinter的問題
- “為什么我的電腦上安裝了 Python ?”
- 什么是Python?
- 為什么我的電腦上安裝了 Python ?
- 我能刪除 Python 嗎?
- 術語對照表
- 文檔說明
- Python 文檔貢獻者
- 解決 Bug
- 文檔錯誤
- 使用 Python 的錯誤追蹤系統
- 開始為 Python 貢獻您的知識
- 版權
- 歷史和許可證
- 軟件歷史
- 訪問Python或以其他方式使用Python的條款和條件
- Python 3.7.3 的 PSF 許可協議
- Python 2.0 的 BeOpen.com 許可協議
- Python 1.6.1 的 CNRI 許可協議
- Python 0.9.0 至 1.2 的 CWI 許可協議
- 集成軟件的許可和認可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec