Skip to content

Instantly share code, notes, and snippets.

@JHay0112
Last active September 1, 2020 00:39
Show Gist options
  • Save JHay0112/98dbaa6d9bdad273694213de6afc3eea to your computer and use it in GitHub Desktop.
Save JHay0112/98dbaa6d9bdad273694213de6afc3eea to your computer and use it in GitHub Desktop.
Renders a tkinter canvas from a grid
'''
render.py
Author: Jordan Hay
Date: 2020-09-01
'''
# -- Imports --
import tkinter as tk
from tkinter import ttk
# -- Classes --
# Grid based canvas
class Canvas:
# Initialisation
def __init__(self, parent, width, height):
self._parent = parent
self._width = width
self._height = height
# Setup canvas
self._canvas = tk.Canvas(self._parent, width = self._width, height = self._height)
self._canvas.pack()
# Render a grid
def render(self, grid):
# Colour maps values to colours
colour_map = {
1: "black",
2: "green"
}
# Make sure canvas is empty
self._canvas.delete(tk.ALL)
rows = len(grid) # Rows in grid
grid_height = self._height/rows # Calculate the height of each grid piece
# Iteration counters
row_num = 0
column_num = 0
# For every row
for row in grid:
# Start at zeroeth column
column_num = 0
columns = len(row) # Get columns in row
grid_width = self._width/columns # Calculate the width of each grid piece
# For every column in this row
for column in row:
# If the column is non-zero
if(column != 0):
fill = colour_map[column]
# Calculate coordinates
x0 = column_num * grid_width
y0 = row_num * grid_height
x1 = x0 + grid_width
y1 = y0 + grid_height
# Generate rectangle
self._canvas.create_rectangle(x0, y0, x1, y1, fill = fill, outline = "")
# Iterate column
column_num += 1
# Iterate row
row_num += 1
# -- Main --
root = tk.Tk()
grid = [
[1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 1, 0, 2],
[1, 1, 0, 1, 1, 0, 1],
[1, 0, 0, 1, 0, 0, 1],
[1, 0, 1, 1, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1]
]
c = Canvas(root, 200, 200)
c.render(grid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment