可以写一个同心正方形的Python代码吗
时间: 2023-05-23 21:01:34 浏览: 150
当然可以,以下是一个 Python 代码实现同心正方形的方法:
``` python
import turtle
def draw_square(side_length):
for i in range(4):
turtle.forward(side_length)
turtle.right(90)
turtle.speed(10)
for i in range(1, 6):
draw_square(10 * i)
turtle.penup()
turtle.right(135)
turtle.forward(7.07)
turtle.right(45)
turtle.pendown()
```
这段代码使用 Python 中的 turtle 库绘制同心正方形,通过 for 循环控制方形边长和绘制次数,从而实现同心效果。
相关问题
利用turtle绘图:1000个同心正方形逐渐缩小,10种颜色,每种颜色100个正方形,最外层边长为1000请用python帮我写三个可以完成这个任务的程序
程序1:
import turtle
turtle.speed(0)
colors = ["red", "orange", "yellow", "green", "cyan", "blue", "purple", "pink", "brown", "black"]
length = 1000
square_count = 100
for i in range(10):
color = colors[i]
square_length = length // square_count
for j in range(square_count):
turtle.color(color)
turtle.penup()
turtle.setpos(-square_length * j, -square_length * j)
turtle.pendown()
for k in range(4):
turtle.forward(square_length * (2 * j + 1))
turtle.left(90)
length -= square_length
turtle.done()
程序2:
import turtle
turtle.speed(0)
colors = ["red", "orange", "yellow", "green", "cyan", "blue", "purple", "pink", "brown", "black"]
length = 1000
square_count = 100
for i in range(10):
color = colors[i]
square_length = length // square_count
for j in range(1, square_count + 1):
turtle.color(color)
turtle.penup()
turtle.setpos(-square_length * j, -square_length * j)
turtle.pendown()
for k in range(4):
turtle.forward(square_length * (2 * j - 1))
turtle.left(90)
length -= square_length
turtle.done()
程序3:
import turtle
turtle.speed(0)
colors = ["red", "orange", "yellow", "green", "cyan", "blue", "purple", "pink", "brown", "black"]
length = 1000
square_count = 100
turtle.hideturtle()
for i in range(10):
color = colors[i]
square_length = length // square_count
for j in range(1, square_count + 1):
turtle.color(color)
turtle.penup()
turtle.setpos(-square_length * j, -square_length * j)
turtle.pendown()
turtle.begin_fill()
for k in range(4):
turtle.forward(square_length * (2 * j - 1))
turtle.left(90)
turtle.end_fill()
length -= square_length
turtle.done()
python画同心七彩正方形
在Python中,你可以使用`turtle`模块来绘制同心圆和多彩的正方形。以下是一个简单的示例,展示如何创建一个同心的彩色正方形:
```python
import turtle
# 创建turtle对象
t = turtle.Turtle()
t.speed(0) # 设置快速移动
# 定义颜色列表
colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
# 绘制同心正方形
def draw_square(size, color):
t.fillcolor(color)
t.begin_fill()
for _ in range(4):
t.forward(size)
t.right(90)
t.end_fill()
# 同心圆大小递减
radius = 50
while radius > 0:
draw_square(radius, colors.pop()) # 取出并使用最后一个颜色
radius -= 10 # 每次减小一圈的距离
# 关闭turtle窗口
turtle.done()
```
在这个例子中,我们首先设置了一个turtle对象,然后定义了七种颜色。接着通过一个循环,每次从颜色列表中取出一个颜色,并以此颜色填充一个小正方形。随着循环进行,正方形的半径逐次减小,形成同心结构。
阅读全文