Kodewick
Start learning →

Python Turtle Heart

A big red heart with little hearts floating around. The heart is two half circles and two straight lines.

Python Turtle Heart
The full code (37 lines)
import turtle
import random

screen = turtle.Screen()
screen.bgcolor("#fff0f3")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)


def heart(x, y, size, color):
    # start at the heart's bottom tip
    t.penup()
    t.goto(x, y)
    t.setheading(45)
    t.pendown()
    t.color(color)
    t.begin_fill()
    t.forward(size)
    t.circle(size / 2, 180)
    t.right(90)
    t.circle(size / 2, 180)
    t.forward(size)
    t.end_fill()


# little hearts floating around
for i in range(14):
    heart(random.randint(-260, 260), random.randint(-200, 200), random.randint(12, 26), random.choice(["pink", "hotpink", "lightpink"]))

# the big heart in the middle
heart(0, -130, 160, "red")

t.penup()
t.goto(0, 10)
t.color("white")
t.write("I love you", align="center", font=("Arial", 30, "bold"))

How it is drawn

The heart starts at its bottom tip: setheading(45) points up and to the right, a straight line, circle(size / 2, 180) draws half a circle, a right turn of 90 and another half circle, and a line back to the tip.

It is all between begin_fill() and end_fill(), so the shape is filled.

Wrapped in a function, heart(x, y, size, color) draws the big heart and the little ones (random places, random sizes).

t.write(...) writes the words in the middle; align="center" centres them.

Questions

How do I write a name instead?

Click Edit and change the text inside write(...), then run it.

My heart is tilted?

Set the direction first with setheading(45). If the turtle turned before and was not set straight, the heart tilts.

Try another