Advertisement
here2share

# Tk_triangular_tiling.py

Apr 24th, 2021
864
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. # Tk_triangular_tiling.py
  2.  
  3. import tkinter as tk
  4. import math
  5.  
  6.  
  7. WIDTH, HEIGHT = 600, 600
  8.  
  9.  
  10. class Point:
  11.     """convenience for point arithmetic
  12.    """
  13.     def __init__(self, x, y):
  14.         self.x, self.y = x, y
  15.     def __add__(self, other):
  16.         return Point(self.x + other.x, self.y + other.y)
  17.     def __iter__(self):
  18.         yield self.x
  19.         yield self.y
  20.  
  21.  
  22. def tile_with_triangles(canvas, side_length=50):
  23.     """tiles the entire surface of the canvas with triangular polygons
  24.    """
  25.     triangle_height = int(side_length * math.sqrt(3) / 2)
  26.     half_side = side_length // 2
  27.     p0 = Point(0, 0)
  28.     p1 = Point(0, side_length)
  29.     p2 = Point(triangle_height, half_side)
  30.  
  31.     for idx, x in enumerate(range(-triangle_height, WIDTH+1, triangle_height)):
  32.         for y in range(-side_length, HEIGHT+1, side_length):
  33.             y += half_side * (idx%2 + 1)
  34.             offset = Point(x, y)
  35.             pa, pb, pc = p0 + offset, p1 + offset,p2 + offset
  36.             canvas.create_polygon(*pa, *pb, *pc, outline='black', fill='', activefill='red')
  37.  
  38.     p2 = Point(-triangle_height, half_side)  # flip the model triangle
  39.  
  40.     for idx, x in enumerate(range(-triangle_height, WIDTH+triangle_height+1, triangle_height)):
  41.         for y in range(-side_length, HEIGHT+1, side_length):
  42.             y += half_side * (idx%2 + 1)
  43.             offset = Point(x, y)
  44.             pa, pb, pc = p0 + offset, p1 + offset,p2 + offset
  45.             canvas.create_polygon(*pa, *pb, *pc, outline='black', fill='', activefill='blue')
  46.  
  47.  
  48. root = tk.Tk()
  49. canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg='cyan')
  50. canvas.pack()
  51.  
  52. tile_with_triangles(canvas) #, side_length=10)
  53.  
  54. root.mainloop()
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement