Title: Draw a colored spiral of Theodorus in Python
My post Draw a spiral of Theodorus in Python explains how to draw a spiral of Theodorus. This example just colors it.
Drawing the Spiral
The main change to the program is in the draw_theodorus_spiral method, which is shown in the following code with the changes from the previous version highlighted in blue.
def draw_theodorus_spiral(self, edge_points):
'''Draw the spiral of Theodorus.'''
# Clear the canvas.
self.canvas.delete(tk.ALL)
# Transform the points so they fit nicely on the canvas.
margin = 10
rect = [margin, margin,
self.canvas.winfo_width() - margin - 1,
self.canvas.winfo_height() - margin - 1]
edge_points, dx, dy = transform_points(edge_points, rect)
# Define color parameters.
r = 255
dr = 255 / len(edge_points)
# Draw the spiral.
for i in range(len(edge_points)-1, 1, -1):
triangle = [
(dx, dy),
(edge_points[i][0], edge_points[i][1]),
(edge_points[i-1][0], edge_points[i-1][1]),
]
color = rgb_to_hex((int(r), 0, 0))
r -= dr
self.canvas.create_polygon(triangle, fill=color, outline='')
The code transforms the spiral's edge points as before so the spiral sits nicely on the program's Canvas widget. It then sets the value r to 255. This will be the red color component when the program draws the spiral's triangles. The code also sets dr to 255 / len(edge_points) so it can increment the r value for each of the spiral's triangles.
As it loops through the spiral's edge points, the code uses the rgb_to_hex function (described shortly) to convert the red, green, and blue color components into the #rrggbb format that tkinter understands. It then subtracts dr to r to get the red color component for the next triangle and it draws the current triangle with the current color.
rgb_to_hex
The following rgb_to_hex function converts red, green, and blue color components into the #rrggbb format that tkinter understands.
def rgb_to_hex(rgb):
'''Converts an RGB tuple to a Tkinter-compatible hexadecimal color string.'''
r, g, b = rgb
return f'#{r:02x}{g:02x}{b:02x}'
This function's parameter is a list or tuple holding the red, green, and blue color components. It simply uses an f-string to format those values in hexadecimal and returns the result.
Conclusion
The changes to this program are small, but they make the spiral a bit more interesting. Feel free to experiment if you like. For example, you could color the triangles with shades of green, blue, yellow, or some other color. You can also color them randomly.
In my next post, I'll show one way you can fill the spiral with rainbow colors.
Download the example to experiment with it and to see additional details.
|