Mastering Python Turtle Graphics: Create Colorful Patterns with Code

codepythonic
0

 Mastering Python Turtle Graphics: Create Colorful Patterns with Code

Install command:


pip install PythonTurtle




import turtle
import colorsys

# Create a turtle object
t = turtle.Turtle()

# Create a screen object and set the background color
s = turtle.Screen()
s.bgcolor('black')

# Set the turtle's speed to the maximum
t.speed(0)

# Define the number of colors
n = 70

# Initialize the hue value
h = 0

# Loop for 360 degrees
for i in range(360):
    # Convert the hue value to an RGB color
    c = colorsys.hsv_to_rgb(h, 1, 1)

    # Increment the hue value
    h += 1 / n

    # Set the turtle's color to the generated color
    t.color(c)

    # Turn the turtle left by 1 degree
    t.left(1)

    # Move the turtle forward by 1 unit
    t.forward(1)

    # Loop to draw two circles
    for j in range(2):
        # Turn the turtle left by 2 degrees
        t.left(2)

        # Draw a circle with a radius of 100 units
        t.circle(100)

# Keep the turtle graphics window open
turtle.done()


Explanation:

  • The bgcolor() method is called on the Screen object s instead of chaining it after the Screen() call.
  • The bgcolor() method is passed the string 'black' to set the background color.
  • The third parameter of the colorsys.hsv_to_rgb() function is removed because it is not required.
  • The fd() method is changed to forward() to specify the distance the turtle should move forward. In this case, it's set to 1.
  • The turtle.done() function is called at the end to keep the turtle graphics window open.





Tags:

Post a Comment

0Comments

Post a Comment (0)