Turtle Python Programs

Draw Rainbow In Python Using Turtle

Last updated July 3, 2023 by Jarvis Silva

In this tutorial we will see how to draw rainbow using python, we will use the turtle module to create this program in python, It is a GUI python library which can be used to draw anything from characters, cartoons, shapes and other objects.

Python Code To Draw Rainbow

import turtle
import colorsys

def draw_one_color_arc(x,y,r,pensize,color):

turtle.bgcolor('light blue')
turtle.title('Rainbow In Python Turtle')
num_colors = 49

radius = 300
penwidth = 20*7/num_colors
hue = 0

for i in range(num_colors):
    (r,g,b) = colorsys.hsv_to_rgb(hue,1,1)
    radius -= (penwidth-1) 
    hue += 0.9/num_colors

Above is the code for drawing rainbow, let’s see how this code actually works:

  • The draw_one_color_arc function is defined to draw a single arc of a specific color at a given position.
  • The turtle module is initialized with various settings such as speed, background color, and window size.
  • The variable num_colors is set to 49, indicating the number of colors that will be used to draw the rainbow.
  • The radius variable is set to 300, which represents the initial radius of the largest arc.
  • The penwidth variable is calculated based on the number of colors, and it determines the width of each arc.
  • The code uses the colorsys module to convert the hue value (ranging from 0 to 1) to RGB values. The hue value gradually changes for each arc to create a rainbow effect.
  • A loop is used to draw each arc. Inside the loop, the draw_one_color_arc function is called with the appropriate parameters: position, radius, pen width, and color.
  • The radius is decremented for each iteration, creating smaller arcs that form a concentric pattern. The hue value is also adjusted to change the color of each arc, giving the appearance of a rainbow.

Now to run this program you need to have python installed on your computer, If you don’t have then follow this guide: Install and setup python on your computer or else you can use this python compiler.

When you run the program and it will open a new window and it will start drawing rainbow and below is the finished drawing of rainbow.

Rainbow Drawing In Python

As you can see, we successfully drew the rainbow, I hope you were able to run this program successfully. 

Here are some more python drawing tutorials for you:

I hope you found what you were looking for from this tutorial, and if you want more python guides and tutorials like this, do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂