Advertisement
here2share

# tk_Grid_of_Triangles.py

Dec 23rd, 2023
713
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. # tk_Grid_of_Triangles.py
  2.  
  3. import tkinter as tk
  4. import math
  5.  
  6. ww = 500
  7. hh = 500
  8.  
  9. def rotate_polygon(polygon, angle_degrees):
  10.     angle_radians = math.radians(angle_degrees)
  11.     coords = canvas.coords(polygon)
  12.    
  13.     # Find the centroid of the polygon
  14.     x_coords = coords[::2]  # Extract x-coordinates
  15.     y_coords = coords[1::2]  # Extract y-coordinates
  16.    
  17.     # Calculate centroid
  18.     centroid_x = sum(x_coords) / len(x_coords)
  19.     centroid_y = sum(y_coords) / len(y_coords)
  20.    
  21.     # Translate centroid to the origin
  22.     translated_coords = [(x - centroid_x, y - centroid_y) for x, y in zip(x_coords, y_coords)]
  23.    
  24.     # Rotate each point around the origin
  25.     rotated_coords = []
  26.     for x, y in translated_coords:
  27.         new_x = x * math.cos(angle_radians) - y * math.sin(angle_radians)
  28.         new_y = x * math.sin(angle_radians) + y * math.cos(angle_radians)
  29.         rotated_coords.extend([new_x, new_y])
  30.    
  31.     # Translate back to original position by adding centroid coordinates
  32.     final_coords = [coord + centroid_x if i % 2 == 0 else coord + centroid_y for i, coord in enumerate(rotated_coords)]
  33.    
  34.     # Update the polygon coordinates on the canvas
  35.     canvas.coords(polygon, *final_coords)
  36.  
  37. def draw_triangles(size, rows, cols):
  38.     height = size * math.sqrt(3) / 2
  39.     row = 0
  40.     while row * height < ww:
  41.         half_offset_x = -2 if row % 2 else size // 2 - 2
  42.         col = -1
  43.         while col * size < hh + size * 2:
  44.             x0 = (col - 1) * size - 2 - half_offset_x
  45.             y0 = row * height
  46.             x1 = x0 + size
  47.             y1 = y0 + height
  48.             triangle = canvas.create_polygon(x0, y0, x1, y0, x1 - size / 2, y1, outline='black', fill='yellow')
  49.             triangle = canvas.create_polygon(x0, y0, x1, y0, x1 - size / 2, y1, outline='black', fill='white')
  50.             rotate_polygon(triangle, 180)
  51.             canvas.move(triangle, size // 2, size * 0.3)
  52.             col += 1
  53.         row += 1
  54.  
  55. root = tk.Tk()
  56. root.title("Grid of Triangles")
  57.  
  58. canvas = tk.Canvas(root, width=ww, height=hh, bg='black')
  59. canvas.pack()
  60.  
  61. triangle_size = 50
  62. rows = 10
  63. cols = 10
  64.  
  65. draw_triangles(triangle_size, rows, cols)
  66.  
  67. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement