用 Python 的 Turtle 模块绘制星号组成的正方形,应该怎么做?
本篇文章给大家分享《用 Python 的 Turtle 模块绘制星号组成的正方形,应该怎么做?》,覆盖了文章的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
用 python 画一个由星号组成的正方形
在 python 的 turtle 模块中,该如何绘制一个由星号组成的正方形而不是线条呢?
使用默认的 shape() 函数只能设置乌龟的形状为预定义的对象,例如箭头、乌龟或圈,无法绘制自定义形状。
为了绘制一个由星号组成的正方形,可以自己手动绘制星号或直接在指定位置写上星号。下面提供了一个示例代码:
import turtle turtle.shape('classic') turtle.speed(10) turtle.setpos(0,0) def make_star(pos, n): turtle.penup() turtle.setpos(pos) turtle.pendown() turtle.right(30) turtle.forward(n) turtle.back(n*0.5) turtle.right(120) turtle.forward(n*0.5) turtle.back(n) turtle.forward(n*0.5) turtle.right(120) turtle.forward(n*0.5) turtle.back(n) turtle.forward(n*0.5) turtle.right(90) def make_square(left_bottom, right_top, size = 10): # left_top: 对角左下顶点坐标 # right_bottom: 对角右上顶点坐标 # size: *的大小 x1, y1 = left_bottom x2, y2 = right_top if x1 > x2: raise Exception('left_bottom参数错误') if y1 > y2: raise Exception('right_top参数错误') if x2-x1 < size*3: raise Exception('size参数错误,size至多是边长的三分之一长度') if y2-y1 < size*3: raise Exception('size参数错误,size至多是边长的三分之一长度') # 第一条边 一 for i in range(x1, x2, size): turtle.penup() turtle.setpos((x1 + i, y1)) turtle.pendown() turtle.write('*', font=size) # 第二条边 一 | for i in range(y1, y2, size): turtle.penup() turtle.setpos((x2, y1 + i)) turtle.pendown() turtle.write('*', font=size) # 第三条边 一 | 一 for i in range(x1, x2, size): turtle.penup() turtle.setpos((x2 - i, y2)) turtle.pendown() turtle.write('*', font=size) # 第四条边 一 | 一 | for i in range(y1, y2, size): turtle.penup() turtle.setpos((x1, y2 - i)) turtle.pendown() turtle.write('*', font=size) make_square((0,0), (100, 100), 10) turtle.done()
到这里,我们也就讲完了《用 Python 的 Turtle 模块绘制星号组成的正方形,应该怎么做?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注公众号,带你了解更多关于的知识点!