SoFunction
Updated on 2024-11-21

Python use turtle library to draw rainbow code example

Language: Python
IDE:

demand (economics)

Make a rainbow effect

color space

RGB model: the three primary colors of light, which together determine hue
HSB/HSV model: H color, S shade, B saturation, H determines hue
HSB models need to be converted to RGB models

code example

#-*- coding:utf-8 –*-
from turtle import *

def HSB2RGB(hues):
 hues = hues * 3.59 #100 to 359 range
 rgb=[0.0,0.0,0.0]
 i = int(hues/60)%6
 f = hues/60 -i
 if i == 0:
  rgb[0] = 1; rgb[1] = f; rgb[2] = 0
 elif i == 1:
  rgb[0] = 1-f; rgb[1] = 1; rgb[2] = 0
 elif i == 2:
  rgb[0] = 0; rgb[1] = 1; rgb[2] = f
 elif i == 3:
  rgb[0] = 0; rgb[1] = 1-f; rgb[2] = 1
 elif i == 4:
  rgb[0] = f; rgb[1] = 0; rgb[2] = 1
 elif i == 5:
  rgb[0] = 1; rgb[1] = 0; rgb[2] = 1-f
 return rgb

def rainbow():
 hues = 0.0
 color(1,0,0)
 #Painting the rainbow
 hideturtle()
 speed(100)
 pensize(3)
 penup()
 goto(-400,-300)
 pendown()
 right(110)
 for i in range (100):
  circle(1000)
  right(0.13)
  hues = hues + 1
  rgb = HSB2RGB(hues)
  color(rgb[0],rgb[1],rgb[2]) 
 penup()

def main():
 setup(800, 600, 0, 0)
 bgcolor((0.8, 0.8, 1.0))
 tracer(False)
 rainbow()
 # Output text
 tracer(False)
 goto(100,-100)
 pendown()
 color("red")
 write("Me.",align="center",
   font=("Script MT Bold", 80, "bold"))
 tracer(True)

 mainloop()

if __name__ == "__main__":
 main()

The effect is demonstrated:

summarize

At first in the picture to add the Chinese "I" when, due to the use of small, but also the occurrence of a messy code, the solution is very simple, in front of the code to add a sentence

#-*- coding:utf-8 –*-

For a more detailed approach, refer to:python Chinese garbled code is not anxious, first read the bytes and characters

The above is the entire content of this article on Python using turtle library to draw a rainbow code example, I hope it will help you. Interested friends can continue to refer to this site:

Drawing diagrams with Python's turtle module

Example of turtle graphing in Python

Python built-in module turtle drawing details

If there are deficiencies, welcome to leave a message to point out. Thank you friends for the support of this site!