接觸python,就發現python是一門很有趣的課程。往往只需要利用幾行簡單的代碼,就能繪製出簡單漂亮的圖案。毫不誇張的說,掌握好turtle庫,就能繪製一整片藍圖。有時候,當我們遇到一些對稱圖形的時候,利用 for in 循環語句,也能達到很好的效果。我們先了解一些關於turtle庫的基本函數。
turtle庫的基本函數:
一、繪圖窗口設置命令
①turtle.setup(width,height,starty,starty) 注:(starty,starty)指的是繪圖窗體左上角位置的座標,這兩個參數可選,若爲空,則窗口位於屏幕中心
turtle.setup(100,100)
turtle.setup800, 800, 100,100)
②turtle.screensize(canvwidth=None, canvheight=None, bg=None) 參數分別爲畫布的寬(單位像素), 高, 背景顏色 注:若括號爲空,則默認值爲(400,300)
turtle.screensize(400, 300, "red")
二、座標體系
(1)空間座標體系
①turtle.goto(x,y):直接跳轉到(x,y)點,以繪圖窗口中心爲原點,向右爲x軸,向上爲y軸。
②turtle.fd(d)、turtle.forward(d):以當前方向,往前行進d像素。
③turtle.bk(d)、turtle.backword(d):保持當前方向不變,往後退行d像素。
④turtle.circle(r,angle):從當前位置以r爲半徑圓的angle角度旋轉。
(2)角度座標體系
①turtle.setheading(angle)也可簡寫爲turtle.seth() 表示海龜改變行進角度,但不運動。繪圖窗體以x軸爲起點,將方向偏轉爲angle度,逆時針爲正。
②turtle.left(angle):在當前行進方向的基礎上,向左旋轉angle度。
③turtle.right(angle):在當前行進方向的基礎上,向右旋轉angle度。
(3)畫筆控制命令
①turtle.penup() 表示 擡筆
turtle.pendown() 表示 落筆
②turtle.pensize(x) 表示畫筆寬度
③turtle.pencolor(顏色名red/RGB三元組/顏色編碼) 表示畫筆顏色 e.g.turtle.pencolor("red") 畫筆爲紅色
turtle.colormode(mode)
④turtle.fillcolor(colorstring):繪製圖形的填充顏色
turtle.begin_fill():開始填充
turtle.end_fill():結束填充
turtle.done() 寫在末尾,程序運行完不會退出
注意:寫代碼之前要引入turtle庫。
import turtle
圖形繪製:一箭穿心
一、繪製一個愛心
import turtle
turtle.color('red', 'pink')
turtle.pensize(2)
turtle.pendown()
turtle.seth(150)
turtle.begin_fill()
turtle.fd(40)
turtle.circle(40 * -3.745, 45)
turtle.circle(40 * -1.431, 165)
turtle.left(120)
turtle.circle(40 * -1.431, 165)
turtle.circle(40 * -3.745, 45)
turtle.fd(40)
turtle.end_fill()
效果如圖
二、繪製箭
turtle.pensize(5)
turtle.pencolor("black")
turtle.seth(100)
turtle.penup()
turtle.fd(90)
turtle.pendown()
turtle.seth(75)
turtle.fd(20)
turtle.seth(-155)
turtle.fd(20)
turtle.seth(25)
turtle.penup()
turtle.fd(20)
turtle.pendown()
turtle.seth(-130)
turtle.fd(120)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.seth(180)
turtle.fd(10)
turtle.seth(50)
turtle.fd(15)
turtle.seth(0)
turtle.fd(10)
turtle.seth(-80)
turtle.fd(10)
turtle.seth(-130)
turtle.fd(15)
turtle.seth(100)
turtle.fd(10)
turtle.end_fill()
三、將兩者組合起來
import turtle
turtle.color('red', 'pink')
turtle.pensize(2)
turtle.pendown()
turtle.seth(150)
turtle.begin_fill()
turtle.fd(40)
turtle.circle(40 * -3.745, 45)
turtle.circle(40 * -1.431, 165)
turtle.left(120)
turtle.circle(40 * -1.431, 165)
turtle.circle(40 * -3.745, 45)
turtle.fd(40)
turtle.end_fill()
turtle.pensize(5)
turtle.pencolor("black")
turtle.seth(100)
turtle.penup()
turtle.fd(90)
turtle.pendown()
turtle.seth(75)
turtle.fd(20)
turtle.seth(-155)
turtle.fd(20)
turtle.seth(25)
turtle.penup()
turtle.fd(20)
turtle.pendown()
turtle.seth(-130)
turtle.fd(120)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.seth(180)
turtle.fd(10)
turtle.seth(50)
turtle.fd(15)
turtle.seth(0)
turtle.fd(10)
turtle.seth(-80)
turtle.fd(10)
turtle.seth(-130)
turtle.fd(15)
turtle.seth(100)
turtle.fd(10)
turtle.end_fill()
效果如圖
掌握了turtle庫之後,我們可以根據自己的想法,畫出更復雜,更漂亮的圖畫。