在Python中使用turtle图形绘制心脏
Turtle是Python中的一个内建模块。它提供了
- 使用屏幕(纸板)绘图。
- turtle(笔)。
为了在屏幕上画东西,我们需要移动turtle(笔),为了移动turtle,有一些函数,如forward(), backward(),等等。
用turtle图形绘制心脏
在本节中,我们将讨论如何使用Turtle Graphics绘制Heart。
步骤:
1.import turtle
2.制作turtle对象
3.定义一种方法,用简单的向前和向左移动画出一条曲线
4.定义一个方法来绘制完整的心脏,并在其中填充红色。
5.定义一个方法,通过设置位置来显示一些文本
6.调用主部分的所有方法。
代码:
# Import turtle package
import turtle
# Creating a turtle object(pen)
pen = turtle.Turtle()
# Defining a method to draw curve
def curve():
for i in range(200):
# Defining step by step curve motion
pen.right(1)
pen.forward(1)
# Defining method to draw a full heart
def heart():
# Set the fill color to red
pen.fillcolor('red')
# Start filling the color
pen.begin_fill()
# Draw the left line
pen.left(140)
pen.forward(113)
# Draw the left curve
curve()
pen.left(120)
# Draw the right curve
curve()
# Draw the right line
pen.forward(112)
# Ending the filling of the color
pen.end_fill()
# Defining method to write text
def txt():
# Move turtle to air
pen.up()
# Move turtle to a given position
pen.setpos(-68, 95)
# Move the turtle to the ground
pen.down()
# Set the text color to lightgreen
pen.color('lightgreen')
# Write the specified text in
# specified font style and size
pen.write("GeeksForGeeks", font=(
"Verdana", 12, "bold"))
# Draw a heart
heart()
# Write text
txt()
# To hide turtle
pen.ht()
输出: