I’ve created a Tkinter script that generates random triangles. And of course I am sharing that with you.
Generating Random Triangles with Tkinter
This script utilizes the Tkinter library, Python’s standard GUI toolkit, to create a simple window with a canvas. Upon execution, it programmatically draws a specified number of triangles with random positions and colors onto this canvas. This example serves as a basic introduction to graphical programming with Tkinter and demonstrates fundamental concepts like canvas drawing and random number generation.
from tkinter import * import random def generate_triangles(count, height, width): colors = ['black', 'violet', 'brown', 'orange', 'yellow', 'green', 'red', 'silver', 'gold', 'pink'] for i in range(int(count)): color = random.choice(colors) x1 = random.randrange(0, int(width)) y1 = random.randrange(0, int(height)) x2 = random.randrange(0, int(width)) y2 = random.randrange(0, int(height)) x3 = random.randrange(0, int(width)) y3 = random.randrange(0, int(height)) triangle = canvas.create_polygon(x1, y1, x2, y2, x3, y3, fill=color, outline='black') root = Tk() canvas = Canvas(root, width=400, height=400) canvas.pack() generate_triangles(1, 400, 400) root.mainloop()
The script generates random triangles using the generate_triangles function. To generate more triangles, adjust the count parameter in the generate_triangles function call. Feel free to customize the colors array as well.