海龜作圖---用Python繪圖


一、關於Turtle
“turtle是一個簡單的繪圖工具。它提供了一個海龜,你可以把它理解為一個機器人,只聽得懂有限的指令”
操縱海龜繪圖有着許多的命令,這些命令可以划分為兩種:一種為運動命令,一種為畫筆控制命令
二、運動命令
forward(degree)
 #向前移動距離degree代表距離
backward(degree)
 #向后移動距離degree代表距離
right(degree)
 #向右移動多少度
left(degree)
 #向左移動多少度
goto(x,y)
 #將畫筆移動到坐標為x,y的位置
speed(speed)
 #畫筆繪制的速度范圍[0,10]整數
三、畫筆控制命令
down()
畫筆落下,移動時繪制圖形
up()
畫筆抬起,移動時不繪制圖形
setheading(degree)
海龜朝向,degree代表角度
reset()
恢復所有設置
pensize(width)
畫筆的寬度
pencolor(colorstring)
畫筆的顏色
fillcolor(colorstring)
繪制圖形的填充顏色
fill(True) 
fill(False)
四、程序體驗
1.奧運五環
代碼:
#繪制奧運五環
import turtle
turtle.width(15) #畫筆粗細

turtle.color("blue")
turtle.circle(50)

turtle.penup()
turtle.goto(120,0)
turtle.down()

turtle.color("black")
turtle.circle(50)

turtle.penup()
turtle.goto(240,0)
turtle.down()

turtle.color("red")
turtle.circle(50)

turtle.penup()
turtle.goto(60,-50)
turtle.down()

turtle.color("yellow")
turtle.circle(50)

turtle.penup()
turtle.goto(180,-50)
turtle.down()

turtle.color("green")
turtle.circle(50)

顯示效果:
2.使用遞歸,可以繪制出非常復雜的圖形。例如,下面的代碼可以繪制一棵分型樹:
from turtle import * # 設置色彩模式是RGB: colormode(255) lt(90) lv = 14 l = 120 s = 45 width(lv) # 初始化RGB顏色: r = 0 g = 0 b = 0 pencolor(r, g, b) penup() bk(l) pendown() fd(l) def draw_tree(l, level): global r, g, b # save the current pen width w = width() # narrow the pen width width(w * 3.0 / 4.0) # set color: r = r + 1 g = g + 2 b = b + 3 pencolor(r % 200, g % 200, b % 200) l = 3.0 / 4.0 * l lt(s) fd(l) if level < lv: draw_tree(l, level + 1) bk(l) rt(2 * s) fd(l) if level < lv: draw_tree(l, level + 1) bk(l) lt(s) # restore the previous pen width width(w) speed("fastest") draw_tree(l, 4) done() 

顯示效果:執行上述程序需要花費一定的時間,最后的效果如下

 

 


免責聲明!

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



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