python海龟绘图实例教程

WBOY
Release: 2016-06-16 08:43:04
Original
2921 people have browsed it

本文以实例形式介绍了python turtle模块即海龟绘图的使用方法,对于需要进行图形编程的朋友相信会有一定的借鉴价值。

python turtle模块简介:
 python2.6版本中引入的一个简单的绘图工具,叫做海龟绘图(Turtle Graphics)

1.使用海龟绘图首先我们需要导入turtle,如下所示:

 from turtle import * #将turtle中的所有方法导入

Copy after login

2.海龟绘图属性:

(1)位置
(2)方向
(3)画笔(画笔的属性,颜色、画线的宽度)

3.操纵海龟绘图有着许多的命令,这些命令可以划分为两种:一种为运动命令,一种为画笔控制命令

(1)运动命令:

  forward(degree)  #向前移动距离degree代表距离
  backward(degree)  #向后移动距离degree代表距离
  right(degree)    #向右移动多少度
 left(degree)  #向左移动多少度
 goto(x,y)  #将画笔移动到坐标为x,y的位置
  stamp()     #复制当前图形
 speed(speed)  #画笔绘制的速度范围[0,10]整数

Copy after login

(2)画笔控制命令:

 down() #移动时绘制图形,缺省时也为绘制
 up() #移动时不绘制图形
 pensize(width) #绘制图形时的宽度
 color(colorstring) #绘制图形时的颜色
 fillcolor(colorstring) #绘制图形的填充颜色
 fill(Ture)
 fill(false)

Copy after login

4.关于turtle简介许多下面我们看个实例:

(一)绘制正方形:

 import turtle
 import time
#定义绘制时画笔的颜色
 turtle.color("purple")
#定义绘制时画笔的线条的宽度
 turtle.size(5)
#定义绘图的速度 
turtle.speed(10)
#以0,0为起点进行绘制
 turtle.goto(0,0)
#绘出正方形的四条边
 for i in range(4):
   turtle.forward(100)
   turtle.right(90)
#画笔移动到点(-150,-120)时不绘图
 turtle.up()
 turtle.goto(-150,-120)
#再次定义画笔颜色
 turtle.color("red")
#在(-150,-120)点上打印"Done"
 turtle.write("Done")
 time.sleep(3)

Copy after login

(二)绘制五角星:

import turtle
import time
turtle.color("purple")
turtle.pensize(5)
turtle.goto(0,0)
turtle.speed(10)
for i in range(6):
 turtle.forward(100)
 turtle.right(144)
turtle.up()
turtle.forward(100)
turtle.goto(-150,-120)
turtle.color("red")
turtle.write("Done")
time.sleep(3)

Copy after login

这里给出了两个简单的实例,大家可以根据上面的思路与方法进一步拓展,绘制出一些更复杂的图形。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!