Python標準庫 之 turtle(海龜繪圖)

turtle庫介紹

首先,turtle庫是一個點線面的簡單圖像庫(也被人們成爲海龜繪圖),在Python2.6以後被引入進來,可以完成一些比較簡單的幾何圖像可視化。它就像一個小烏龜,在一個橫軸爲x、縱軸爲y的座標系原點,(0,0)位置開始,它根據一組函數指令的控制,在這個平面座標系中移動,從而在它爬行的路徑上繪製了圖形。java

turtle庫基礎知識

1.畫布(canvas)python

畫布就是turtle爲咱們展開用於繪圖區域默認大小(400, 300),咱們能夠設置它的大小和初始位置。canvas

1.1設置畫布大小:app

turtle.screensize(canvwidth=None, canvheight=None, bg=None),參數分別爲畫布的寬(單位像素), 高, 背景顏色。
如:
turtle.screensize(800,600, "green")
turtle.screensize() #返回默認大小(400, 300)
turtle.setup(width=0.5, height=0.75, startx=None, starty=None),參數:width, height: 輸入寬和高爲整數時, 表示像素; 爲小數時, 表示佔據電腦屏幕的比例,(startx, starty): 這一座標表示矩形窗口左上角頂點的位置, 若是爲空,則窗口位於屏幕中心。

如:ide

turtle.setup(width=0.6,height=0.6)
turtle.setup(width=800,height=800, startx=100, starty=100)

2.畫筆(pen)模塊化

2.1 畫筆的狀態
在畫布上,默認有一個座標原點爲畫布中心的座標軸,座標原點上有一隻面朝x軸正方向小烏龜。這裏咱們描述小烏龜時使用了兩個詞語:座標原點(位置),面朝x軸正方向(方向), turtle繪圖中,就是使用位置方向描述小烏龜(畫筆)的狀態。函數

2.2 畫筆的屬性
畫筆(畫筆的屬性,顏色、畫線的寬度等)oop

1) turtle.pensize():設置畫筆的寬度;字體

2) turtle.pencolor():沒有參數傳入,返回當前畫筆顏色,傳入參數設置畫筆顏色,能夠是字符串如"green", "red",也能夠是RGB 3元組。this

3) turtle.speed(speed):設置畫筆移動速度,畫筆繪製的速度範圍[0,10]整數,數字越大越快。

2.3 繪圖命令
操縱海龜繪圖有着許多的命令,這些命令能夠劃分爲3種:一種爲運動命令,一種爲畫筆控制命令,還有一種是全局控制命令。

2.3.1 畫筆運動命令:

命令 說明
turtle.home() 將turtle移動到起點(0,0)和向東
turtle.speed(speed) 畫筆繪製的速度範圍[0,10]整數
turtle.forward(distance) 向當前畫筆方向移動distance像素長
turtle.backward(distance) 向當前畫筆相反方向移動distance像素長度
turtle.right(degree) 順時針移動degree°
turtle.left(degree) 逆時針移動degree°
turtle.pendown() 移動時繪製圖形放下筆,,默認繪製
turtle.penup() 移動時不繪製圖形,提起筆,用於另起一個地方繪製時用
turtle.circle(r,extent,step) 繪製一個指定半徑、弧度範圍、階數(正多邊形)的圓
turtle.dot(diameter,color) 繪製一個指定直徑和顏色的圓

 

  2.3.2 畫筆控制命令:

命令 說明
turtle.pencolor() 畫筆顏色
turtle.pensize(width) 畫筆寬度(繪製圖形時的寬度)
turtle.color(color1, color2 同時設置pencolor=color1, fillcolor=color2
turtle.filling() 返回當前是否在填充狀態
turtle.begin_fill() 準備開始填充圖形
turtle.end_fill() 填充完成
turtle.hideturtle() 隱藏畫筆的turtle形狀
turtle.showturtle() 顯示畫筆的turtle形狀

 

  2.3.3 全局控制命令

命令 說明
turtle.clear() 清空turtle窗口,可是turtle的位置和狀態不會改變
turtle.reset() 清空窗口,重置turtle狀態爲起始狀態
turtle.undo() 取消最後一個圖的操做
turtle.isvisible() 返回當前turtle是否可見
turtle.stamp() 複製當前圖形
turtle.write(s , [font=("font-name",font_size,"font_type")]) 寫文本,s爲文本內容,font是字體的參數,分別爲字體名稱,大小和類型;font爲可選項,font參數也是可選項

  

  2.3.4 其餘命令

命令 說明
turtle.mainloop()或turtle.done() 啓動事件循環 -調用Tkinter的mainloop函數。必須是烏龜圖形程序中的最後一個語句。
turtle.mode(mode=None) 設置烏龜模式(「standard」,「logo(向北或向上)」或「world()」)並執行重置。若是沒有給出模式,則返回當前模式。
turtle.undo() 取消最後一個圖的操做
turtle.isvisible() 返回當前turtle是否可見
turtle.stamp() 複製當前圖形
turtle.write(s , [font=("font-name",font_size,"font_type")]) 寫文本,s爲文本內容,font是字體的參數,分別爲字體名稱,大小和類型;font爲可選項,font參數也是可選項

實例

五角星圖形

#五角星圖形
from turtle import Turtle

p = Turtle()
p.speed(3)
p.pensize(5)
p.color("black", 'yellow')
#p.fillcolor("red")
p.begin_fill()
for i in range(5):
    p.forward(200)  #將箭頭移到某一指定座標 
    p.right(144)    #當前方向上向右轉動角度
p.end_fill()

Python標準庫 之 turtle(海龜繪圖)

樹的繪製

Python標準庫 之 turtle(海龜繪圖)

觀察:對稱樹, 從主杆出發以必定角度向左向右生成對稱的枝丫, 且每一棵枝杈上以相同的角度生成更小的左右枝杈,如此往復。
聯繫:所學內容,易想到利用遞歸程序實現;

# drawtree.py

from turtle import Turtle, mainloop

def tree(plist, l, a, f):
    """ plist is list of pens
    l is length of branch
    a is half of the angle between 2 branches
    f is factor by which branch is shortened
    from level to level."""
    if l > 5: #
        lst = []
        for p in plist:
            p.forward(l)#沿着當前的方向畫畫Move the turtle forward by the specified distance, in the direction the turtle is headed.
            q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
            p.left(a) #Turn turtle left by angle units
            q.right(a)#Turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
            lst.append(p)#將元素增長到列表的最後
            lst.append(q)
        tree(lst, l*f, a, f)



def main():
    p = Turtle()
    p.color("green")
    p.pensize(5)
    #p.setundobuffer(None)
    p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
                   #because hiding the turtle speeds up the drawing observably.

    p.getscreen().tracer(10,0)
        #Return the TurtleScreen object the turtle is drawing on.
        #TurtleScreen methods can then be called for that object.
    #p.speed(10)
    p.left(90)  #Turn turtle left by angle units. direction 調整畫筆

    p.penup() #Pull the pen up – no drawing when moving.
    p.goto(0,-200)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
    p.pendown()# Pull the pen down – drawing when moving. 這三條語句是一個組合至關於先把筆收起來再移動到指定位置,再把筆放下開始畫
    #不然turtle一移動就會自動的把線畫出來

    #t = tree([p], 200, 65, 0.6375)
    t = tree([p], 200, 65, 0.6375)

main()

森林的繪製

如何畫出多棵樹,甚至整片森林呢? 
答案很簡單,只要在畫每棵樹以前調整畫筆的位置,調用畫樹程序,就能夠重新位置生成一顆新樹了。 
利用模塊化的函數思想,調整代碼: 
將每棵樹的繪製以maketree函數封裝,參數x,y爲畫樹的起點位置即樹根位置。在main函數中只要以不一樣的參數設置來調用maketree函數就能夠完成多棵樹的繪製了

# drawtree.py
from turtle import Turtle, mainloop

def tree(plist, l, a, f):
    """ plist is list of pens
    l is length of branch
    a is half of the angle between 2 branches
    f is factor by which branch is shortened
    from level to level."""
    if l > 5: #
        lst = []
        for p in plist:
            p.forward(l)#沿着當前的方向畫畫Move the turtle forward by the specified distance, in the direction the turtle is headed.
            q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
            p.left(a) #Turn turtle left by angle units
            q.right(a)#Turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
            lst.append(p)#將元素增長到列表的最後
            lst.append(q)
        tree(lst, l*f, a, f)

def maketree(x, y):
    p = Turtle()
    p.color("green")
    p.pensize(5)
    p.hideturtle()
    p.getscreen().tracer(30, 0)
    p.left(90)

    p.penup()
    p.goto(x, y)
    p.pendown()

    t = tree([p], 110, 65, 0.6375)
    print(len(p.getscreen().turtles())) #用了多少個turtle繪製

def main():
    maketree(-200, -200)
    maketree(0, 0)
    maketree(200, -200)

main()

Python標準庫 之 turtle(海龜繪圖)

做者:碼農大表哥
連接:

https://www.jianshu.com/p/df81a110cdfd
來源:簡書

-END-


  識別圖中二維碼,領取python全套視頻資料

相關文章
相關標籤/搜索