天天看點

python海龜作圖好看圖案_海龜作圖---用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)

顯示效果:

python海龜作圖好看圖案_海龜作圖---用Python繪圖

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()

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

python海龜作圖好看圖案_海龜作圖---用Python繪圖