概述
昨天在网上看到有人利用turtle模块画出了五角星,觉得很好玩。晚上睡觉前想,这样的话其实可以画国旗啊。于是编写了下面的代码。可是!我并没有准确的设计方法,所以不敢擅自画国旗啊。如果谁有标准的设计方法,可以基于此代码画出五星红旗,比心。
代码示例
关于turtle的简单实用方法,网络上有很多相关文章,我这里就不详细的解释。我只说几个这里会用到的
画布(canvas)
turtle.screensize(canvwidth=None, canvheight=None, bg=None),参数分别为画布的宽(单位像素), 高, 背景颜色。
画笔(Pen)
turtle.pensize():设置画笔的宽度;
turtle.pencolor():没有参数传入,返回当前画笔颜色,传入参数设置画笔颜色,可以是字符串如"green", "red",也可以是RGB 3元组。
绘图命令
turtle.forward(distance) 向当前画笔方向移动distance像素长度
turtle.right(degree) 顺时针移动degree°
turtle.pendown() 移动时绘制图形,缺省时也为绘制
turtle.goto(x,y) 将画笔移动到坐标为x,y的位置
turtle.penup() 提起笔移动,不绘制图形,用于另起一个地方绘制
turtle.fillcolor(colorstring) 绘制图形的填充颜色
turtle.begin_fill() 准备开始填充图形
turtle.end_fill() 填充完成
首先要创建一个类,并定义基本属性
class Wjx(object):
def __init__(self,lenth,startpoint=[],angle=0,pensize=2,pencolor='yellow',fillcolor='yellow'):
self.lenth = lenth
self.startpoint = startpoint
self.angle = angle
turtle.pensize(pensize)
turtle.pencolor(pencolor)
turtle.fillcolor(fillcolor)
因为要连续话几个五角星,所以要有抬笔换位置的方法
def skip(self):
turtle.penup()
turtle.goto(self.startpoint)
turtle.pendown()
为了调用更方便,我加了__call__
def __call__(self):
if self.startpoint:
self.skip()
turtle.begin_fill()
self.arch()
turtle.end_fill()
这块是实际的构建五角星的部分
def arch(self):
if self.angle:
turtle.right(self.angle)
for _ in range(5):
turtle.forward(self.lenth)
turtle.right(144)
全部代码可看我的github:五角星