基于turtle的Python作画

2018年6月12日笔记

  1. 按win+q键换出搜索界面,输入path,进入系统属性,选择高级,选择环境变量。在系统变量中的PATHEXT这个变量中文本内容为.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC。如果这个文本内容中没有.EXE,在cmd中输入命令的时候则不能省略.exe的后缀,即原本pip install xlwt要写成pip.exe install xlwt
  2. 学习用python作画:首先进入python的shell界面,方法是在安装好python的情况下在cmd中运行python命令,就可以进入python的shell界面。
    进入以后,导入turtle库。方法是在python的shell中运行命令:from turtle import *。文章后面运行命令的环境都是python的shell。
  3. 画一条直线,执行下面的两行命令可以实现。
pendown()
forward(100)

pendown()的作用是落笔,只有落笔才能作画。
当不作画却想移动画笔的时候要提笔,用函数penup()
forward是画笔向前移动,函数当中参数为移动距离。
forward(100)的意思是画笔向前移动100。

  1. 画一个边长为200的正方形。
for i in range(4):
    forward(200)
    right(90)
  1. 画一个复杂图形。
def draw1():
    reset()
    speed(10)
    for i in range(36):
        forward(200)
        left(170)
reset()
speed(10)
draw1()

speed()中的参数1-10画图速度递增,但是有一个反例参数为0时速度最快。
reset()会重置画笔,画布,作画速度。

  1. 顺时针方向画一个200半径的圆:circle(-200)
    逆时针方向画一个200半径的圆:circle(200)
    顺时针画一个100半径的半圆:circle(-100,180)
    顺时针画一个边长为150的正方形:circle(-150,360,4)
  2. 将图形涂色示例,画一个红色的半圆。
reset()
fillcolor('red')
begin_fill()
circle(100,180)
end_fill()

8.复杂图形涂色示例,画一个“太极”图案。

reset()
speed(10)
pendown()
circle(100,180)
circle(200,180)
circle(100,-180)
fillcolor('black')
begin_fill()
circle(100,180)
circle(200,180)
circle(100,-180)
end_fill()
penup()
goto(0,100)
dot(50)
goto(0,-100)
pencolor('white')
dot(50)
hideturtle()

circle(100)与circle(100,360)两条命令效果相同。
撤回一步:undo(),清空画布:clear()。


基于turtle的Python作画
画出的太极图形.png
  1. 画一段曲线
for i in range(8):
    circle(20,100)
    circle(-20,100)
  1. 画一个复杂图形,利用循环嵌套方法
from turtle import *
reset()
speed(0)
pendown()
for i in range(6):
    fd(150)
    for j in range(10):
        circle(40)
        lt(36)
    lt(60)
基于turtle的Python作画
复杂图形1.png
  1. 画一个复杂图形,利用循环嵌套方法
from turtle import *
reset()
speed(0)
for i in range(6):
    pendown()
    fd(150)
    for j in range(10):
        circle(40)
        lt(36)
    lt(60)
    penup()
    goto(0,0)
基于turtle的Python作画
复杂图形2.png
  1. 获取画笔当前位置:position() pos() 两个函数用处一样
    设置画笔位置:setposition() setpos()
    获取角度:heading()
    设置角度setheading() seth()
  2. 画一个椭圆
reset()
setheading(45)
circle(10,90)
circle(90,90)
circle(10,90)
circle(90,90)

14.画一个笑脸。下面的代码作为一个单独py文件可以运行。

from turtle import *
def go(x,y):
    penup()
    goto(x,y)
    pendown()
def arc(radius):
    circle(radius,90)
reset()
speed(0)
go(0,-150)
circle(200)
go(50,100)
seth(225)
arc(10)
arc(50)
arc(10)
arc(50)
go(-50,100)
seth(-45)
arc(-10)
arc(-50)
arc(-10)
arc(-50)
go(-70,-50)
arc(100)
hideturtle()
基于turtle的Python作画
笑脸.png

直接在cmd中可能无法运行,需要先定义函数,再调用函数,如下图所示,。


基于turtle的Python作画
cmd中运行示例.png
  1. 画一个酷炫图形。
from turtle import *
reset()
bgcolor('black')
speed(0)
colors = ['red','orange','green','cyan','blue','purple']
for i in range(360):
    pencolor(colors[i%6])
    fd(i*3/6+i)
    left(61)
    pensize(i*6/200)
基于turtle的Python作画
炫酷图案.png