
用 python 画一个由星号组成的正方形
在 python 的 turtle 模块中,该如何绘制一个由星号组成的正方形而不是线条呢?
使用默认的 shape() 函数只能设置乌龟的形状为预定义的对象,例如箭头、乌龟或圈,无法绘制自定义形状。
为了绘制一个由星号组成的正方形,可以自己手动绘制星号或直接在指定位置写上星号。下面提供了一个示例代码:
立即学习“Python免费学习笔记(深入)”;
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 模块绘制星号组成的正方形,应该怎么做?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号