python畫圖之“小海龜”turtle


“小海龜”turtle是Python語言中一個很流行的繪制圖像的函數庫,想象一個小烏龜,在一個橫軸為x、縱軸為y的坐標系原點,(0,0)位置開始,它根據一組函數指令的控制,在這個平面坐標系中移動,從而在它爬行的路徑上繪制了圖形。

turtle繪圖的基礎知識:

1.畫布(canvas)

畫布就是turtle為我們展開用於繪圖區域,我們可以設置它的大小和初始位置。

設置畫布大小

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):這一坐標表示矩形窗口左上角頂點的位置,如果為空,則窗口位於屏幕中心。

如:turtle.setup(width=0.6,height=0.6)

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

2.畫筆

2.1畫筆的狀態

在畫布上,默認有一個坐標原點為畫布中心的坐標軸,坐標原點上有一只面朝x軸正方向小烏龜。這里我們描述小烏龜時使用了兩個詞語:坐標原點(位置),面朝x軸正方向(方向),turtle繪圖中,就是使用位置方向描述小烏龜(畫筆)的狀態。

2.2畫筆的屬性

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

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

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

3)turtle.speed(speed):設置畫筆移動速度,畫筆繪制的速度范圍[0,∞]整數,數字越大越快。當前版本並不是如外面所說只有0到10,親測100,300皆可。

2.3繪圖命令

操縱海龜繪圖有着許多的命令,這些命令可以划分為3種:一種為運動命令,一種為畫筆控制命令,還有一種是全局控制命令。

(1)畫筆運動命令

 

命令

說明

turtle.forward(distance)

向當前畫筆方向移動distance像素長度

turtle.backward(distance)

向當前畫筆相反方向移動distance像素長度

turtle.right(degree)

順時針移動degree°

turtle.left(degree)

逆時針移動degree°

turtle.pendown()

移動時繪制圖形,缺省時也為繪制

turtle.goto(x,y)

將畫筆移動到坐標為x,y的位置

turtle.penup()

提起筆移動,不繪制圖形,用於另起一個地方繪制

turtle.circle()

畫圓,半徑為正(負),表示圓心在畫筆的左邊(右邊)畫圓

setx( )

將當前x軸移動到指定位置

sety( )

將當前y軸移動到指定位置

setheading(angle)

設置當前朝向為angle角度

home()

設置當前畫筆位置為原點,朝向東。

dot(r)

繪制一個指定直徑和顏色的圓點

 

(2) 畫筆控制命令

 

命令

說明

turtle.fillcolor(colorstring)

繪制圖形的填充顏色

turtle.color(color1, color2)

同時設置pencolor=color1, fillcolor=color2

turtle.filling()

返回當前是否在填充狀態

turtle.begin_fill()

准備開始填充圖形

turtle.end_fill()

填充完成

turtle.hideturtle()

隱藏畫筆的turtle形狀

turtle.showturtle()

顯示畫筆的turtle形狀

 

(3) 全局控制命令

 

命令

說明

turtle.clear()

清空turtle窗口,但是turtle的位置和狀態不會改變

turtle.reset()

清空窗口,重置turtle狀態為起始狀態

turtle.undo()

撤銷上一個turtle動作

turtle.isvisible()

返回當前turtle是否可見

stamp()

復制當前圖形

turtle.write(s [,font=("font-name",font_size,"font_type")])

寫文本,s為文本內容,font是字體的參數,分別為字體名稱,大小和類型;font為可選項,font參數也是可選項

 

(4) 其他命令

 

命令

說明

turtle.mainloop()或turtle.done()

啟動事件循環 -調用Tkinter的mainloop函數。

必須是烏龜圖形程序中的最后一個語句。

turtle.mode(mode=None)

設置烏龜模式(“standard”,“logo”或“world”)並執行重置。如果沒有給出模式,則返回當前模式。

模式

初始龜標題

正角度

standard

向右(東)

逆時針

logo

向上(北)

順時針

turtle.delay(delay=None)

設置或返回以毫秒為單位的繪圖延遲。

turtle.begin_poly()

開始記錄多邊形的頂點。當前的烏龜位置是多邊形的第一個頂點。

turtle.end_poly()

停止記錄多邊形的頂點。當前的烏龜位置是多邊形的最后一個頂點。將與第一個頂點相連。

turtle.get_poly()

返回最后記錄的多邊形。

 

3.命令詳解

3.1turtle.circle(radius,extent=None,steps=None)

描述:以給定半徑畫圓

參數:

radius(半徑):半徑為正(負),表示圓心在畫筆的左邊(右邊)畫圓;

extent(弧度)(optional);

steps(optional)(做半徑為radius的圓的內切正多邊形,多邊形邊數為steps)。

舉例:

circle(50)#整圓;

circle(50,steps=3)#三角形;

circle(120,180)#半圓

4.實例

1、太陽花

# coding=utf-8 
import turtle 
import time 
 
# 同時設置pencolor=color1, fillcolor=color2 
turtle.color("red", "yellow")  
turtle.begin_fill() 
for _ in range(50): 
turtle.forward(200) 
turtle.left(170) 
turtle.end_fill() 
turtle.mainloop() 

2、五角星

# coding=utf-8 
import turtle 
import time 
 
turtle.pensize(5) 
turtle.pencolor("yellow") 
turtle.fillcolor("red") 
 
turtle.begin_fill() 
for _ in range(5): 
 turtle.forward(200) 
 turtle.right(144) 
turtle.end_fill() 
time.sleep(2) 
  
turtle.penup() 
turtle.goto(-150,-120) 
turtle.color("violet") 
turtle.write("Done", font=('Arial', 40, 'normal')) 
 
turtle.mainloop() 

3、時鍾程序

# coding=utf-8 
import turtle 
from datetime import * 
# 抬起畫筆,向前運動一段距離放下 
def Skip(step): 
  turtle.penup() 
  turtle.forward(step) 
  turtle.pendown() 
def mkHand(name, length): 
  # 注冊Turtle形狀,建立表針Turtle 
  turtle.reset() 
  Skip(-length * 0.1) 
  # 開始記錄多邊形的頂點。當前的烏龜位置是多邊形的第一個頂點。 
  turtle.begin_poly() 
  turtle.forward(length * 1.1) 
  # 停止記錄多邊形的頂點。當前的烏龜位置是多邊形的最后一個頂點。將與第一個頂點相連。 
  turtle.end_poly() 
  # 返回最后記錄的多邊形。 
  handForm = turtle.get_poly() 
  turtle.register_shape(name, handForm) 
def Init(): 
  global secHand, minHand, hurHand, printer 
  # 重置Turtle指向北 
  turtle.mode("logo") 
  # 建立三個表針Turtle並初始化 
  mkHand("secHand", 135) 
  mkHand("minHand", 125) 
  mkHand("hurHand", 90) 
  secHand = turtle.Turtle() 
  secHand.shape("secHand") 
  minHand = turtle.Turtle() 
  minHand.shape("minHand") 
  hurHand = turtle.Turtle() 
  hurHand.shape("hurHand") 
  for hand in secHand, minHand, hurHand: 
    hand.shapesize(1, 1, 3) 
    hand.speed(0) 
  # 建立輸出文字Turtle 
  printer = turtle.Turtle() 
  # 隱藏畫筆的turtle形狀 
  printer.hideturtle() 
  printer.penup() 
def SetupClock(radius): 
  # 建立表的外框 
  turtle.reset() 
  turtle.pensize(7) 
  for i in range(60): 
    Skip(radius) 
    if i % 5 == 0: 
      turtle.forward(20) 
      Skip(-radius - 20) 
       
      Skip(radius + 20) 
      if i == 0: 
        turtle.write(int(12), align="center", font=("Courier", 14, "bold")) 
      elif i == 30: 
        Skip(25) 
        turtle.write(int(i/5), align="center", font=("Courier", 14, "bold")) 
        Skip(-25) 
      elif (i == 25 or i == 35): 
        Skip(20) 
        turtle.write(int(i/5), align="center", font=("Courier", 14, "bold")) 
        Skip(-20) 
      else: 
        turtle.write(int(i/5), align="center", font=("Courier", 14, "bold")) 
      Skip(-radius - 20) 
    else: 
      turtle.dot(5) 
      Skip(-radius) 
    turtle.right(6)    
def Week(t):   
  week = ["星期一", "星期二", "星期三", 
      "星期四", "星期五", "星期六", "星期日"] 
  return week[t.weekday()]  
def Date(t): 
  y = t.year 
  m = t.month 
  d = t.day 
  return "%s %d%d" % (y, m, d)   
def Tick(): 
  # 繪制表針的動態顯示 
  t = datetime.today() 
  second = t.second + t.microsecond * 0.000001 
  minute = t.minute + second / 60.0 
  hour = t.hour + minute / 60.0 
  secHand.setheading(6 * second) 
  minHand.setheading(6 * minute) 
  hurHand.setheading(30 * hour)    
  turtle.tracer(False)  
  printer.forward(65) 
  printer.write(Week(t), align="center", 
         font=("Courier", 14, "bold")) 
  printer.back(130) 
  printer.write(Date(t), align="center", 
         font=("Courier", 14, "bold")) 
  printer.home() 
  turtle.tracer(True)   
  # 100ms后繼續調用tick 
  turtle.ontimer(Tick, 100) 
def main(): 
  # 打開/關閉龜動畫,並為更新圖紙設置延遲。 
  turtle.tracer(False) 
  Init() 
  SetupClock(160) 
  turtle.tracer(True) 
  Tick() 
  turtle.mainloop() 
  
if __name__ == "__main__": 
  main() 

畫一個邊長為60的正方形,並填充為紅色,邊框為藍色

#-*- coding: utf-8 -*-
import turtle
turtle.reset()
a= 60
turtle.fillcolor("red")
turtle.pencolor("blue")
turtle.pensize(10)
turtle.fill(True)
turtle.left(90)
turtle.forward(a)
turtle.left(90)
turtle.forward(a)
turtle.left(90)
turtle.forward(a)
turtle.left(90)
turtle.forward(a)
turtle.fill(False)

最后一個實例:

from numpy import *
from random import random
import turtle
turtle.reset()
x = array([[.5],[.5]])
p = [0.85,0.92,0.99,1.00]
A1 = array([[.85, 0.04],
      [-0.04,.85]])
b1 = array([[0],[1.6]])
A2 = array([[0.20,-0.26],
      [0.23,0.22]])
b2 = array([[0],[1.6]])
A3 = array([[-0.15,0.28],
      [0.26,0.24]])
b3 = array([[0],[0.44]])

A4 = array([[0,0],
      [0,0.16]])

turtle.color("blue")
cnt = 1
while True:
  cnt += 1
  if cnt == 2000:
    break
  r = random()
  if r < p[0]:
    x = dot(A1 , x) + b1
  elif r < p[1]:
    x = dot(A2 , x) + b2
  elif r < p[2]:
    x = dot(A3 , x) + b3
  else:
    x = dot(A4 , x)
  #print x[1]
  turtle.up()
  turtle.goto(x[0][0] * 50,x[1][0] * 40 - 240)
  turtle.down()
  turtle.dot()

 

PS:在我自己第一次使用turtle的時候(Windows)出現了Can Not find the moudle named "tkinter",原因是我在安裝Python時取消了tcl組件的安裝。如果重裝Python不能解決的話,參看CSDN的諸位大神了解一下。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM