python海龟绘图turtle

python海龟绘图turtle

概述

海龟绘图提供了一个实体“海龟”形象,假定它在地板上平铺的纸张上画线。使用海龟绘图可以编写重复执行简单动作的程序画出精细复杂的形状。官方参考

启动海龟环境

  1. 在python shell中导入turtle模块的所有对象
from turtle import *

基本绘图

# 海龟前进100步,海龟画出一条线段,方向朝东
forward(100)
# 改变海龟的方向,左转120度
left(200)
# 画出一个三角形
forward(100)
left(120)
forward(100)
# 画笔控制,笔的颜色color('blue'),线宽width(3)
# 海龟的位置
# 海龟送回起点
home()
# 初始位置在海龟屏幕的中心,获取对应的坐标
pos()
# 清空窗口
clearscreen()

在脚本中使用海龟绘图

import turtle as t  

for steps in range(100):
    for c in ('blue', 'red', 'green'):
        t.color(c)
        t.forward(steps)
        t.right(30)
# 脚本结束,python会同时关闭海龟的窗口
t.mainloop()

python海龟绘图turtle_第1张图片

# 绘制星形
import turtle as t  

# 红色线条
t.color('red')
# 黄色填充
t.fillcolor('yellow')
# up()和down()决定是否画线,begin_fill()和end_fill()决定是否填充
t.begin_fill()
while True:
    t.forward(200)
    t.left(170)    
    # 确定海龟何时回到初始点的好办法
    if abs(t.pos()) < 1:
        break

t.end_fill()
t.mainloop()

python海龟绘图turtle_第2张图片

你可能感兴趣的:(python,python,开发语言)