1. 程式人生 > >海龜繪圖:Python3.7的turtle模組

海龜繪圖:Python3.7的turtle模組

小海龜歷險記

Shawn
python3.7
文件:
https://docs.python.org/3/library/turtle.html

  • 想象一下,把一個小海龜扔到沙灘上.小海龜爬啊爬,沙灘上留下來一道道痕跡,這就是turtle模組.

小海龜的動作

爬行

前進:forward/fd

turtle.forward(distance)
turtle.fd(distance)
Parameters: distance – a number (integer or float)
  • 小海龜朝當前方向向前爬行.

後退:back/bk/backward

turtle.back(distance)
turtle.bk(distance)
turtle.backward(distance)
Parameters: distance – a number (integer or float)
  • 小海龜向後爬行.

右拐(順時針轉):right/rt

turtle.right(angle)
turtle.rt(angle)
Parameters: distance – a number (integer or float)
  • 小海龜順指標轉向.

左拐(逆時針轉):left/lt

turtle.left(angle)
turtle.lt(angle)
Parameters: angle – a number (integer or float)
  • 小海龜逆時針轉向.

爬到指定位置:goto/setpos/setposition

turtle.goto(x, y=None)
turtle.setpos(x, y=None)
turtle.setposition(x, y=None)
Parameters: 
x – a number or a pair/vector of numbers
y – a number or None
  • 小海龜爬到指定的座標位置.

x軸上移動:setx

turtle.setx(x)
Parameters: x – a number (integer or float)
  • 小海龜橫向爬行.

y軸上移動:sety

turtle.sety(y)
Parameters: y – a number (integer or float)
  • 小海龜縱向爬行.

轉向指定方向:setheading/seth

turtle.setheading(to_angle)
turtle.seth(to_angle)
Parameters: to_angle – a number (integer or float)
  • 小海龜朝向指定方向.
  • 注意,預設的方向可能有所不同:
standard mode logo mode
0 - east 0 - north
90 - north 90 - east
180 - west 180 - south
270 - south 270 - west

回家:home

turtle.home()
  • 小海龜回到影象原點(0,0),並朝向預設初始方向.

畫圓:circle

turtle.circle(radius, extent=None, steps=None)
Parameters: 
radius – a number
extent – a number (or None)
steps – an integer (or None)
  • 小海龜從當前位置開始向前畫半徑為radius,角度為extent的圓弧.
  • radius為正,則逆時針,反之順時針.
  • 在turtle裡,本質上,畫圓弧相當於畫n段直線.
  • 用steps可以指定n的數量.換而言之,可以用於實現一些多邊形.

畫點:dot

turtle.dot(size=None, *color)
Parameters: 
size – an integer >= 1 (if given)
color – a colorstring or a numeric color tuple
  • 在當前位置畫一個直徑為size,顏色為color的點.
  • 如果沒有指定size,會預設選擇max(當前筆粗+4,當前筆粗*2)

海龜分身:stamp

turtle.stamp()
  • 在當前位置儲存一個一模一樣小海龜幻象,並返回這個幻象的id.

分身解除:clearstamp

turtle.clearstamp(stampid)
Parameters: stampid – an integer, must be return value of previous stamp() call
  • 根據id解除海龜分身.

批量分身解除:clearstamps

turtle.clearstamps(n=None)
Parameters: n – an integer (or None)
  • 批量解除分身.
  • 預設全部,若n為正則解除最早n個,為負責解除最晚n個.

時光回溯:undo

turtle.undo()
  • 每執行一次可以回到上一步的狀態.

調速:speed

turtle.speed(speed=None)
Parameters: speed – an integer in the range 0..10 or a speedstring (see below)
  • “fastest”: 0
  • “fast”: 10
  • “normal”: 6
  • “slow”: 3
  • “slowest”: 1

  • 調節小海龜爬行以及轉向的速度.

  • 從1到10逐步加快,也可以設定為最快:0.
  • 注意:小於等於0.5或者大於10都會被直接設定為0

海龜狀態查詢

海龜位置:position/pos

turtle.position()
turtle.pos()
  • 返回小海龜當前的位置.

小海龜的頭部與目標間的角度:towards

turtle.towards(x, y=None)
Parameters: 
x – a number or a pair/vector of numbers or a turtle instance
y – a number if x is a number, else None
  • 返回小海龜當前方向與指定座標(或者另一個海龜實體)連線的夾角.

x座標查詢:xcor

turtle.xcor()
  • 返回x座標.

y座標查詢:ycor

turtle.ycor()
  • 返回y座標.

當前方向:heading

turtle.heading()
  • 返回小海龜當前方向.

距離查詢:distance

turtle.distance(x, y=None)
Parameters: 
x – a number or a pair/vector of numbers or a turtle instance
y – a number if x is a number, else None
  • 返回小海龜與指定座標(或者另一個海龜實體)間的距離.

定製規則

一圈有多少度:degrees

turtle.degrees(fullcircle=360.0)
Parameters: fullcircle – a number
  • 設定一圈有多少度.如果你填400,那在小海龜的世界裡一圈會被劃分成400份而不是360份.

用弧度:radians

turtle.radians()
  • 設定用弧度而不是角度.

畫筆

  • 好吧,可愛的小海龜現在終於變成畫筆了.

下筆(肚皮貼地):pendown/pd/down

turtle.pendown()
turtle.pd()
turtle.down()
  • 開始畫出移動軌跡.

擡筆(肚皮離地):penup/pu/up

turtle.penup()
turtle.pu()
turtle.up()
  • 移動時不畫線了.

筆粗:pensize/width

turtle.pensize(width=None)
turtle.width(width=None)
Parameters: width – a positive number
  • 設定畫筆的粗細.
  • 如果無引數,返回當前筆粗.

畫筆(海龜)狀態總控:pen

turtle.pen(pen=None, **pendict)
Parameters: 
pen – a dictionary with some or all of the below listed keys
pendict – one or more keyword-arguments with the below listed keys as keywords
  • 可以調節\查詢當前畫筆的狀態.
    • “shown”: True/False
    • “pendown”: True/False
    • “pencolor”: color-string or color-tuple
    • “fillcolor”: color-string or color-tuple
    • “pensize”: positive number
    • “speed”: number in range 0..10
    • “resizemode”: “auto” or “user” or “noresize”
    • “stretchfactor”: (positive number, positive number)
    • “outline”: positive number
    • “tilt”: number

是否在畫:isdown

turtle.isdown()
  • 返回當前是否是pendown狀態.

顏色控制

畫筆顏色:pencolor

turtle.pencolor(*args)
  • 設定畫筆顏色:
    • 無引數:返回當前畫筆顏色.
    • 顏色名字串或TKcolor字串:設定顏色
      • ”red”, “yellow”, “#33cc8c”
    • rgb元組或rgb單值:設定顏色
      • (0.2, 0.8, 0.55),(51.0, 204.0, 140.0)
      • 255模式或者1.0模式由colormode()設定:
        • colormode(255)
        • colormode(1)

填充顏色: fillcolor

turtle.fillcolor(*args)
  • 設定填充顏色,方法同pencolor

顏色總控:color

turtle.color(*args)
  • 同時查詢\設定畫筆顏色與填充顏色.
  • 第一組引數為畫筆顏色.
  • 第二組引數為填充顏色.

填充控制

填充狀態:filling

turtle.filling()
  • 返回填充狀態.

開始填充:begin_fill

turtle.begin_fill()
  • 開始計算填充圖形.

正式填充:end_fill

turtle.end_fill()
  • 計算從上一個begin_fill開始的圖形,並進行填充.

更多騷操作

初始化:reset

turtle.reset()
  • 清空沙灘並且復原小海龜.

清理沙灘:clear

turtle.clear()
  • 將沙灘上的圖形清空.

寫字:write

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
Parameters: 
arg – object to be written to the TurtleScreen
move – True/False
align – one of the strings “left”, “center” or right”
font – a triple (fontname, fontsize, fonttype)
  • 按照引數將arg寫在沙灘上.

其他海龜引數

海龜可見

隱藏海龜:hideturtle/ht
turtle.hideturtle()
turtle.ht()
  • 隱藏海龜
顯示海龜:showturtle/st
turtle.showturtle()
turtle.st()
  • 顯示海龜
海龜可見狀態查詢:isvisible
turtle.isvisible()
  • 查詢海龜可見狀態.

海龜外觀

海龜外形:shape
turtle.shape(name=None)
Parameters: name – a string which is a valid shapename
  • “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”
  • 小海龜可以變身成圓圈\三角等
海龜大小縮放:resizemode
turtle.resizemode(rmode=None)
Parameters: rmode – one of the strings “auto”, “user”, “noresize”
  • 設定海龜大小縮放模式:
    • “auto”: adapts the appearance of the turtle corresponding to the value of pensize.
    • “user”: adapts the appearance of the turtle according to the values of stretchfactor and outlinewidth (outline), which are set by shapesize().
    • “noresize”: no adaption of the turtle’s appearance takes place.
海龜大小詳細設定:shapesize/turtlesize
turtle.shapesize(stretch_wid=None, stretch_len=None, outline=None)
turtle.turtlesize(stretch_wid=None, stretch_len=None, outline=None)
Parameters: 
stretch_wid – positive number
stretch_len – positive number
outline – positive number
  • 在resizemode為’user’時起效.
海龜剪下係數:shearfactor
turtle.shearfactor(shear=None)
Parameters: shear – number (optional)
  • 設定海龜外觀的剪下形變係數.
  • 不改變朝向.
海龜外形旋轉:tilt/settiltangle
turtle.tilt(angle)
turtle.settiltangle(angle)
Parameters: angle – a number
  • 旋轉海龜外形.
  • 不同的是tilt會根據當前angle做出調整.
  • 而settiltangle為絕對角度.
海龜外形角度查詢:tiltangle
turtle.tiltangle(angle=None)
Parameters: angle – a number (optional)
  • 返回當前外觀角度.
  • 如果有引數,效果同settiltangle.
海龜外形總控:shapetransform
turtle.shapetransform(t11=None, t12=None, t21=None, t22=None)
Parameters: 
t11 – a number (optional)
t12 – a number (optional)
t21 – a number (optional)
t12 – a number (optional)
  • 返回(設定)當前海龜外形變形引數(參照shapesize\shearfactor\settiltangle).
海龜外觀獲取:get_shapepoly
turtle.get_shapepoly()
  • 獲取當前海龜外形的圖形座標元組.

事件監聽器

監聽器:listen

turtle.listen(xdummy=None, ydummy=None)
Set focus on TurtleScreen (in order to collect key-events). Dummy arguments are provided in order to be able to pass listen() to the onclick method.
  • 在螢幕上設定監聽區域.

監聽滑鼠按鍵按下:onclick

turtle.onclick(fun, btn=1, add=None)
Parameters: 
fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas
numnumber of the mouse-button, defaults to 1 (left mouse button)
add – True or False – if True, a new binding will be added, otherwise it will replace a former binding
  • 按下滑鼠時,執行繫結的操作.

監聽滑鼠按鍵擡起:onrelease

turtle.onrelease(fun, btn=1, add=None)
Parameters: 
fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas
numnumber of the mouse-button, defaults to 1 (left mouse button)
add – True or False – if True, a new binding will be added, otherwise it will replace a former binding
  • 擡起滑鼠按鍵時,執行繫結的操作.

監聽滑鼠按鍵拖動:ondrag

turtle.ondrag(fun, btn=1, add=None)
Parameters: 
fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas
numnumber of the mouse-button, defaults to 1 (left mouse button)
add – True or False – if True, a new binding will be added, otherwise it will replace a former binding
  • 拖動滑鼠按鍵時,執行繫結的操作.

監聽鍵盤按鍵:onkey/onkeyrelease/onkeypress

turtle.onkey(fun, key)
turtle.onkeyrelease(fun, key)
turtle.onkeypress(fun, key=None)
Parameters: 
fun – a function with no arguments or None
key – a string: key (e.g. “a”) or key-symbol (e.g. “space”)
  • 按下\釋放鍵盤相應按鍵時,執行操作.

定時操作:ontimer

turtle.ontimer(fun, t=0)
Parameters: 
fun – a function with no arguments
t – a number >= 0
  • 設定計時器,計時t毫秒後執行fun.

時間迴圈:mainloop/done

turtle.mainloop()
turtle.done()
Starts event loop - calling Tkinter’s mainloop function. Must be the last statement in a turtle graphics program. Must not be used if a script is run from within IDLE in -n mode (No subprocess) - for interactive use of turtle graphics.

更多海龜操作

開始記錄多邊形:begin_poly

turtle.begin_poly()
  • 開始記錄多邊形,當前位置為第一個頂點.

結束記錄多邊形:end_poly

turtle.end_poly()
  • 結束記錄多邊形,當前位置為最後一個頂點.

獲取記錄到的多邊形:get_poly

turtle.get_poly()
  • 獲取最後一次記錄到的多邊形.

克隆海龜:clone

turtle.clone()
  • 建立並且返回一個當前海龜一模一樣的克隆.

查詢海龜:getturtle/getpen

turtle.getturtle()
turtle.getpen()
  • 返回海龜自己.

查詢螢幕:getscreen

turtle.getscreen()
  • 返回海龜所在的沙灘,能用於呼叫其方法.

設定undobuffer:setundobuffer

turtle.setundobuffer(size)
Parameters: size – an integer or None
  • 設定一個undobuffer,記錄最多size步可以由undo反悔的海龜操作.
  • 如果size為None,則關閉這個buffer.

查詢undobuffer:undobufferentries

turtle.undobufferentries()
  • 返回undobuffer中現在有多少步.

Screen/TurtleScreen操作

視窗控制

背景色:bgcolor

turtle.bgcolor(*args)
Parameters: args – a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers
  • 改變螢幕背景色(無引數則返回當前背景色.)

背景圖:bgpic

turtle.bgpic(picname=None)
Parameters: picname – a string, name of a gif-file or "nopic", or None
  • 設定或返回背景圖,picname可以是檔名,如果為’nopic’則刪除背景圖.

視窗size:screensize

turtle.screensize(canvwidth=None, canvheight=None, bg=None)
Parameters: 
canvwidth – positive integer, new width of canvas in pixels
canvheight – positive integer, new height of canvas in pixels
bg – colorstring or color-tuple, new background color
  • 設定視窗寬\高\背景色.

world座標:setworldcoordinates

turtle.setworldcoordinates(llx, lly, urx, ury)
Parameters: 
llx – a number, x-coordinate of lower left corner of canvas
lly – a number, y-coordinate of lower left corner of canvas
urx – a number, x-coordinate of upper right corner of canvas
ury – a number, y-coordinate of upper right corner of canvas
  • 通過左下\右上兩個點的座標來設定world座標系統,並切換到world模式(非world模式會reset).
  • 如果已經是world模式,則所有的繪製會在新座標下重繪.

動畫操作

延遲:delay

turtle.delay(delay=None)
Parameters: delay – positive integer
  • 設定繪畫延遲時間(毫秒)

快速繪圖:tracer/update

turtle.tracer(n=None, delay=None)
Parameters: 
n – nonnegative integer
delay – nonnegative integer
turtle.update()
  • tracer:關掉\開啟繪圖動畫.n:每n次螢幕更新顯示一次,delay:每次延時.
  • update:螢幕更新.

輸入操作

彈出文字輸入框:textinput

turtle.textinput(title, prompt)
Parameters: 
title – string
prompt – string
  • 彈出一個文字輸入框,並返回輸入的字串.

彈出數字輸入框:numinput

turtle.numinput(title, prompt, default=None, minval=None, maxval=None)
Parameters: 
title – string
prompt – string
default – number (optional)
minval – number (optional)
maxval – number (optional)
  • 彈出一個數字輸入框,並返回輸入的數字.

模式設定

繪畫模式:mode

turtle.mode(mode=None)
Parameters: mode – one of the strings “standard”, “logo” or “world”
  • 設定或返回繪畫模式.
Mode Initial turtle heading positive angles
“standard” to the right (east) counterclockwise
“logo” upward (north) clockwise

顏色模式:colormode

turtle.colormode(cmode=None)
Parameters: cmode – one of the values 1.0 or 255
  • 設定或返回當前顏色模式.

查詢畫布:getcanvas

turtle.getcanvas()
  • 返回當前畫布.

查詢圖形:getshapes

turtle.getshapes()
  • 返回當前所有可用的海龜圖形的名稱列表

註冊新圖形:register_shape/addshape

turtle.register_shape(name, shape=None)
turtle.addshape(name, shape=None)
  • 註冊一個新的圖形.

查詢海龜:turtles

turtle.turtles()
  • 返回當前螢幕上所有的海龜.

查詢螢幕尺寸:window_height/window_width

turtle.window_height()
turtle.window_width()
  • 返回當前螢幕高/寬.

螢幕特有操作(非繼承自TurtleScreen)

關閉海龜繪圖視窗:bye

turtle.bye()

點選滑鼠後關閉:exitonclick

turtle.exitonclick()
  • 點選滑鼠後關閉視窗.

螢幕設定:setup

turtle.setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])
Parameters: 
width – if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen
height – if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen
startx – if positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if None, center window horizontally
starty – if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if None, center window vertically
  • 設定螢幕的size以及位置.

螢幕標題:title

turtle.title(titlestring)
Parameters: titlestring – a string that is shown in the titlebar of the turtle graphics window
  • 設定螢幕標題.

公共類

造龜:RawTurtle/RawPen

class turtle.RawTurtle(canvas)
class turtle.RawPen(canvas)
Parameters: canvas – a tkinter.Canvas, a ScrolledCanvas or a TurtleScreen
  • 在給定畫布上造一個龜.

預設造龜:Turtle

class turtle.Turtle
  • RawTurtle的子類,在預設螢幕上造龜.

海龜屏:TurtleScreen

class turtle.TurtleScreen(cv)
Parameters: cv – a tkinter.Canvas
  • 提供一個海龜屏.

螢幕:Screen

class turtle.Screen
  • 海龜屏的子類,添加了上一節裡的新功能(bye/title等)

卷屏:ScrolledCanvas

class turtle.ScrolledCanvas(master)
Parameters: master – some Tkinter widget to contain the ScrolledCanvas, i.e. a Tkinter-canvas with scrollbars added
Used by class Screen, which thus automatically provides a ScrolledCanvas as playground for the turtles.

圖形類:Shape

class turtle.Shape(type_, data)
Parameters: type_ – one of the strings “polygon”, “image”, “compound”

Shape.addcomponent(poly, fill, outline=None)
Parameters: 
poly – a polygon, i.e. a tuple of pairs of numbers
fill – a color the poly will be filled with
outline – a color for the poly’s outline (if given)
  • 提供了儲存圖形的資料結構.
type_ data
“polygon” a polygon-tuple, i.e. a tuple of pairs of coordinates
“image” an image (in this form only used internally!)
“compound” None (a compound shape has to be constructed using the addcomponent() method)

向量:Vec2D

class turtle.Vec2D(x, y)

a + b vector addition
a - b vector subtraction
a * b inner product
k * a and a * k multiplication with scalar
abs(a) absolute value of a
a.rotate(angle) rotation
  • 提供了一些二維向量運算.

轉換語言:write_docstringdict

turtle.write_docstringdict(filename="turtle_docstringdict")
Parameters: filename – a string, used as filename
Create and write docstring-dictionary to a Python script with the given filename. This function has to be called explicitly (it is not used by the turtle graphics classes). The docstring dictionary will be written to the Python script filename.py. It is intended to serve as a template for translation