用Python写一个能出现许多渐变色爱心的代码
时间: 2024-05-27 15:11:26 浏览: 132
python制作的爱心代码
```python
import turtle
import random
# 设置画布大小
turtle.setup(800, 600)
# 创建画笔对象
pen = turtle.Turtle()
# 隐藏画笔
pen.hideturtle()
# 设置画笔速度
pen.speed(0)
# 设置起点位置
pen.up()
pen.goto(-300, 0)
pen.down()
# 定义心形函数
def heart(size):
pen.begin_fill()
pen.left(45)
pen.forward(size)
pen.circle(size/2, 180)
pen.right(90)
pen.circle(size/2, 180)
pen.forward(size)
pen.end_fill()
# 定义渐变色函数
def gradient_color(start_color, end_color, step):
color_list = []
for i in range(3):
start = start_color[i]
end = end_color[i]
step_size = (end - start) / step
color_list.append(start)
for j in range(1, step):
color = round(start + step_size * j)
color_list.append(color)
color_list.append(end)
return color_list
# 定义随机颜色函数
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
# 循环绘制爱心
for i in range(30):
# 随机生成渐变色
start_color = random_color()
end_color = random_color()
color_list = gradient_color(start_color, end_color, 50)
# 设置填充颜色
pen.fillcolor(start_color)
# 绘制渐变色爱心
size = random.randint(50, 150)
for j in range(50):
pen.fillcolor(color_list[j*3:j*3+3])
heart(size)
size -= 2
# 点击关闭窗口
turtle.exitonclick()
```
效果如下:![gradient_heart.png](https://i.loli.net/2021/10/28/3M7jPdGwTqJN1hQ.png)
阅读全文