使用Python绘制爱心可以通过多种方法实现,以下是使用turtle库和matplotlib库的两种方法:
使用turtle库绘制爱心
import turtle
创建画笔
t = turtle.Turtle()
t.hideturtle()
t.getscreen().bgcolor("f0e6ef")
t.color("f2546d", "f2546d")
t.pensize(2)
绘制爱心
t.begin_fill()
t.left(140)
t.forward(180)
t.circle(-90, 200)
t.setheading(60)
t.circle(-90, 200)
t.forward(180)
t.end_fill()
写上文字
t.penup()
t.goto(-30, 60)
t.pencolor("cc3b3b")
t.write("Love", font=("Arial", 30, "bold"))
隐藏画笔
t.hideturtle()
显示窗口
turtle.done()
使用matplotlib库绘制爱心
import matplotlib.pyplot as plt
import numpy as np
定义爱心的参数
t = np.linspace(0, 2 * np.pi, 1000)
x = 16 * np.sin(t) 3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
绘制爱心
plt.plot(x, y)
显示图形
plt.show()
运行上述代码,你将分别看到一个使用turtle库绘制的爱心图案和使用matplotlib库绘制的爱心图形。