用 Python 的 Turtle 模块绘制星号组成的正方形,应该怎么做?

用 python 的 turtle 模块绘制星号组成的正方形,应该怎么做?

用 python 画一个由星号组成的正方形

在 python 的 turtle 模块中,该如何绘制一个由星号组成的正方形而不是线条呢?

使用默认的 shape() 函数只能设置乌龟的形状为预定义的对象,例如箭头、乌龟或圈,无法绘制自定义形状。

为了绘制一个由星号组成的正方形,可以自己手动绘制星号或直接在指定位置写上星号。下面提供了一个示例代码:

立即学习“Python免费学习笔记(深入)”;

import turtleturtle.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 模块绘制星号组成的正方形,应该怎么做?的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2179724.html

(0)
上一篇 2025年2月25日 14:13:45
下一篇 2025年2月18日 04:11:39

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论