简体   繁体   中英

Using Tkinter to create rectangles for each cell of a 2d array

I've created a 2d array like this:

a, b = 150, 150;
density = .5

def RedOrGreen():
  c = random.uniform(0,1)
  if c > density:
    d = "GREEN"
  else:
    d = "RED"
  return d

Matrix = [[RedOrGreen() for x in range(a)] for y in range(b)]

I'd like to use tkinter to create a square that has a lot of squares inside of it. These squares are represented by my 2d array. I want to make them either green or red, depending on the value in the 2d array. I tried to accomplish this by iterating through my 2d array, and creating rectangles like this:

        self.forest = tk.Canvas(self, width = 500, height = 500)
        for x in range(a):
            for y in range(b):
                self.forest.create_rectangle(x,y,x+1,y+1, fill = Matrix[x][y])
        self.forest.pack()

I've omitted some code for simplicity, but you can view the entire code here: https://repl.it/repls/WindingUnwelcomeLibrary

However, this solution does not work. I'm not sure why it's not working, because in my head I am iterating through the 2d array, and then creating a corresponding rectangle. Please let me know if you have any ideas.

Edit: The reason it does not work is because it just displays a black canvas. It's not correctly populating the rectangles with the colors I want. I am not running it on repl.it, I just have it there to display the full code.

Every rectangle has black border which hides other rectangles. And finally you have only black canvas.

You have to remove border using width=0

 self.forest.create_rectangle(x, y, x+1, y+1, fill=Matrix[x][y], width=0)

Doc: Canvas

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM