Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_Grid_of_Triangles.py
- import tkinter as tk
- import math
- ww = 500
- hh = 500
- 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, rows, cols):
- 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, outline='black', fill='yellow')
- triangle = canvas.create_polygon(x0, y0, x1, y0, x1 - size / 2, y1, outline='black', fill='white')
- rotate_polygon(triangle, 180)
- canvas.move(triangle, size // 2, size * 0.3)
- col += 1
- row += 1
- root = tk.Tk()
- root.title("Grid of Triangles")
- canvas = tk.Canvas(root, width=ww, height=hh, bg='black')
- canvas.pack()
- triangle_size = 50
- rows = 10
- cols = 10
- draw_triangles(triangle_size, rows, cols)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement