在本文中,我们将用python编写几行代码来绘制心形并在其中编写文本。为了画一颗心,我们将使用一个名为“Turtle”的python库之一。

以下是用于绘图的函数:

  1. Turtle:用于创建对象
  2. bgcolor:用于设置背景颜色。
  3. delay:设置或返回绘图延迟(以毫秒为单位)。绘制延迟越长,动画越慢。
  4. color:更改笔的颜色。
  5. begin_fill:请记住填充面的起点。
  6. end_fill:关闭多边形并用当前填充颜色填充。
  7. forward:将向前移动指定的量。
  8. left: 逆时针转动。
  9. right:顺时针转动。
  10. setpos:将笔移动到绝对位置。
  11. up: 捡起的尾巴,使其在移动时不会画画。
  12. down: 放下尾巴,让它在移动时画画。
  13. write: 使用给定字体在当前位置写入文本。
  14. exitonclick:单击鼠标时关闭海龟图形窗口。

代码:

import turtle as t
pen = t.Turtle()
t.bgcolor('#9966cc')
t.delay(8)
pen.color('#ffe4e1')
pen.begin_fill()
pen.left(40)
pen.forward(120)
pen.circle(80, 190)
pen.right(100)
pen.circle(80, 180)
pen.forward(160)
pen.left(90)
pen.forward(50)
pen.setpos(-60, 100)
pen.end_fill()
def txt():
    pen.up()
    pen.setpos(-60, 100)
    pen.color('red')
    pen.write('I LoVe PyThON', font=("Comic Sans MS", 16))
txt()
pen.end_fill()
t.exitonclick()

输出:

Turtle是Python中的一个内置模块。它提供:

  1. 使用屏幕(纸板)绘图。
  2. Turtle(笔)。

要在屏幕上绘制一些东西,我们需要移动(笔)并移动,有一些功能,如 forward()、back() 等

  1. Import Turtle
  2. 制作对象
  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()

输出

 代码

import turtle

turtle.pensize(3)

def draw_heart_curve():
    for i in range(200):
        turtle.right(1)
        turtle.forward(1)
        
turtle.color("pink", "pink")

turtle.begin_fill()

turtle.left(140)
turtle.forward(111.65)
draw_heart_curve()

turtle.left(120)
draw_heart_curve()
turtle.forward(111.65)

turtle.end_fill()

turtle.color('deep pink')
style = ('Comic Sans MS', 30, 'italic')
turtle.write('Happy Valentine\'s Day', font=style, align='center')


turtle.hideturtle()
turtle.done()

物联沃分享整理
物联沃-IOTWORD物联网 » python爱心代码

发表评论