Skip to content

Instantly share code, notes, and snippets.

@philipnorton42
Created December 25, 2021 17:30
Show Gist options
  • Save philipnorton42/6bee79030760de2ac6ecda97b99a3847 to your computer and use it in GitHub Desktop.
Save philipnorton42/6bee79030760de2ac6ecda97b99a3847 to your computer and use it in GitHub Desktop.
Hitomezashi Stitch Patterns. See https://www.hashbangcode.com/article/drawing-hitomezashi-stitch-patterns-tkinter-canvas-python for a detailed breakdown of this code.
'''
Hitomezashi Stitch Patterns
See https://www.hashbangcode.com/article/drawing-hitomezashi-stitch-patterns-tkinter-canvas-python for
a detailed breakdown of this code.
'''
import tkinter as tk
from tkinter import Canvas
import random, math
class Pattern(tk.Tk):
def __init__(self, vertical = 30, horizontal = 30):
super().__init__()
self.horizontal_line_length = vertical
self.vertical_line_length = horizontal
# Set application title.
self.title("Hitomezashi Stitch Pattern")
# Do not allow users to resize the application window.
self.resizable(False, False)
# Create the canvas widget and add it to the applciation.
self.canvas = Canvas(background='white')
self.canvas.pack(fill=tk.BOTH, expand=True)
# Generate the numbers.
self.generate_numbers()
# Draw the pattern using the vertical and horizontal number ranges.
self.draw_pattern()
# Resize the window.
self.resize_window()
def generate_numbers(self):
# Set up the vertical and horizontal numbers.
self.horizontal_numbers = []
self.vertical_numbers = []
for horizontal in range(0, self.horizontal_line_length):
self.horizontal_numbers.append(random.randrange(0,2))
for vertical in range(0, self.vertical_line_length):
self.vertical_numbers.append(random.randrange(0,2))
def resize_window(self):
# Re-calculate the size of the window to fit the pattern in.
toplevelwindow = self.winfo_toplevel()
toplevelwindow.wm_geometry(str(self.vertical_line_length * 10) + "x" + str(self.horizontal_line_length * 10))
def draw_pattern(self):
for index, value in enumerate(self.vertical_numbers):
if value % 2 == 0:
self.dashed_vertical_line(index * 10, 0)
else:
self.dashed_vertical_line(index * 10, 10)
for index, value in enumerate(self.horizontal_numbers):
if value % 2 == 0:
self.dashed_horizontal_line(index * 10, 0)
else:
self.dashed_horizontal_line(index * 10, 10)
def dashed_horizontal_line(self, depth, start):
for x in range(0, int(self.vertical_line_length/2)):
points = [
start,
depth,
start + 10,
depth
]
self.canvas.create_line(points, fill="black", width=2)
start = start + 20
def dashed_vertical_line(self, depth, start):
for x in range(0, int(self.horizontal_line_length/2)):
points = [
depth,
start,
depth,
start + 10
]
self.canvas.create_line(points, fill="black", width=2)
start = start + 20
if __name__ == "__main__":
sentence_clock = Pattern(40, 50)
sentence_clock.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment