Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_Grid_of_Triangles_2.py
- import tkinter as tk
- import math
- import random
- ww = 500
- hh = 500
- colors = ['#%02X%02X%02X'%(r,g,b) for r in range(0, 256, 15) for g in range(0, 256, 15) for b in range(0, 256, 15)]
- random.shuffle(colors)
- Lc = len(colors)
- print(Lc)
- def rotate_polygon(polygon, angle_degrees):
- angle_radians = math.radians(angle_degrees)
- coords = canvas.coords(polygon)
- # Find the centroid of the polygon
- x_coords = coords[::2] # Extract x-coordinates
- y_coords = coords[1::2] # Extract y-coordinates
- # Calculate centroid
- centroid_x = sum(x_coords) / len(x_coords)
- centroid_y = sum(y_coords) / len(y_coords)
- # Translate centroid to the origin
- translated_coords = [(x - centroid_x, y - centroid_y) for x, y in zip(x_coords, y_coords)]
- # Rotate each point around the origin
- rotated_coords = []
- for x, y in translated_coords:
- new_x = x * math.cos(angle_radians) - y * math.sin(angle_radians)
- new_y = x * math.sin(angle_radians) + y * math.cos(angle_radians)
- rotated_coords.extend([new_x, new_y])
- # Translate back to original position by adding centroid coordinates
- final_coords = [coord + centroid_x if i % 2 == 0 else coord + centroid_y for i, coord in enumerate(rotated_coords)]
- # Update the polygon coordinates on the canvas
- canvas.coords(polygon, *final_coords)
- def draw_triangles(size):
- height = size * math.sqrt(3) / 2
- row = 0
- while row * height < ww:
- half_offset_x = -2 if row % 2 else size // 2 - 2
- col = -1
- while col * size < hh + size * 2:
- x0 = (col - 1) * size - 2 - half_offset_x
- y0 = row * height
- x1 = x0 + size
- y1 = y0 + height
- triangle = canvas.create_polygon(x0, y0, x1, y0, x1 - size / 2, y1, tags=("triangle"), outline='black', fill=colors[(row+col*250)])
- triangle = canvas.create_polygon(x0, y0, x1, y0, x1 - size / 2, y1, tags=("triangle"), outline='black', fill=colors[(row*500+col)])
- rotate_polygon(triangle, 180)
- canvas.move(triangle, size // 2, size * 0.3)
- col += 1
- row += 1
- def change_triangle_colors(event):
- color_index = 0
- random.shuffle(colors)
- triangles = canvas.find_withtag("triangle")
- for triangle in triangles:
- canvas.itemconfig(triangle, fill=colors[color_index])
- color_index = (color_index + 1) % Lc
- root = tk.Tk()
- root.title("Grid of Triangles")
- canvas = tk.Canvas(root, width=ww, height=hh, bg='black')
- canvas.pack()
- root.bind("<space>", change_triangle_colors)
- triangle_size = 50
- draw_triangles(triangle_size)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement