简体   繁体   English

使用Tkinter为2d数组的每个像元创建矩形

[英]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. 我想使用tkinter创建一个内部有很多正方形的正方形。 These squares are represented by my 2d array. 这些正方形由我的2d数组表示。 I want to make them either green or red, depending on the value in the 2d array. 我想根据2d数组中的值使它们变为绿色或红色。 I tried to accomplish this by iterating through my 2d array, and creating rectangles like this: 我尝试通过遍历2d数组并创建如下矩形来实现此目的:

        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 为了简单起见,我省略了一些代码,但是您可以在此处查看整个代码: 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. 我不确定为什么它不起作用,因为在我的头上,我遍历2d数组,然后创建一个相应的矩形。 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. 我没有在repl.it上运行它,只是在那里显示完整的代码。

Every rectangle has black border which hides other rectangles. 每个rectangle都有黑色边框,可隐藏其他矩形。 And finally you have only black canvas. 最后,您只有黑色的画布。

You have to remove border using width=0 您必须使用width=0删除边框

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

Doc: Canvas Doc: 画布

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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