Search code examples
pythonturtle-graphicspython-turtleflower

Center the flower using turtle


I want to draw a flower with turtle. Although I am facing problem in centering the flower (0,0) should be flower's center or where turtle initially is spawned. How can I center it?

import turtle
import math

turtle.speed(-1)
def Flower():
    global radius, num_of
    for i in range(num_of):
        turtle.setheading(i * 360/num_of)
        turtle.circle(radius*3.5/num_of,180)

radius = 50
num_of = 10
Flower()

Flower not-centered using Turtle

I tried setting turtle to where it starts drawing but number of sides ruin it.


Solution

  • Since the turtle draws from a edge, we need to move the turtle to compensate for the radius of the entire image. To simplify this move, we align the starting point of the image with one (X) axis. We also switch from absolute coordinates (setheading()) to relative coordinates (right()) so our initial rotational offset doesn't get lost or need to be added to every position:

    import turtle
    import math
    
    radius = 50
    num_of = 13
    
    def flower():
        outer_radius = radius * 3.5 / math.pi
    
        turtle.penup()
        turtle.setx(-outer_radius)  # assumes heading of 0
        turtle.pendown()
    
        turtle.right(180 / num_of)
    
        for _ in range(num_of):
            turtle.right(180 - 360 / num_of)
            turtle.circle(radius * 3.5 / num_of, 180)
    
    turtle.speed('fastest')
    turtle.dot()  # mark turtle starting location
    
    flower()
    
    turtle.hideturtle()
    turtle.done()
    

    enter image description here

    To get the radius of the flower, we add up the diameters of all the petals and use the standard circumference to radius formula. There are probably simplifications, math-wise and code-wise, we could make.