user2330621
user2330621

Reputation: 101

Creating shapes with Tkinter canvas

If I have a few lists of lists that create grids which contain '#',' ','X' and 'O' how could I go about using the Tkinter library to represent these as different coloured squares on a canvas?

I am able to do it statically for one of the lists, but am unsure of how to make it dynamic so that I can load in each list.

This is the canvas that I wish to create it on:

self._canvas = Canvas(root, relief=SUNKEN, bg="black", width=300, height=300)
self._canvas.pack(side=TOP, expand=True, fill=BOTH)

Upvotes: 0

Views: 492

Answers (1)

I'm unsure what your problem is, but you could just iterate over your grid like this:

DICT_COLOR = {'#':'red', 'X':'green', 'O':'yellow'}
SIZE_X = 300/len(grid[0])
SIZE_Y = 300/len(grid)
for i, line in enumerate(grid):
    for j, value in enumerate(line):
        self._canvas.create_rectangle(j*SIZE_X,
                                      i*SIZE_Y, 
                                      (j+1)*SIZE_X, 
                                      (i+1)*SIZE_Y, 
                                      fill=DICT_COLOR[value])

Upvotes: 2

Related Questions