Home > database >  Is there a reason for this array not being callable?
Is there a reason for this array not being callable?

Time:11-30

from tkinter import *
import random

master = Tk()

w = Canvas(master, width=400, height=400)
w.pack()
w.config(background = "white")

class gridTile:
    def __init__(self,width,height,c1,c2,colour,val):
        self.width = width
        self.height = height
        self.c1 = c1
        self.c2 = c2
        self.colour = colour
        self.val = val
    def draw(self):
    w.create_rectangle(self.c1, self.c2, self.width   self.c1,
                       self.height   self.c2, fill = self.colour)


grid = [["a","b","c","d"],["1a","1b","1c","1d"],["2a","2b","2c","2d"],["3a","3b","3c","3d"]]

When I tested this in a separate environment it worked perfectly, when scaled up it doesn't work.

print(grid[(3)(3)])

grid_size = 4

count = 0
size = 60

for i in range(0,3):
    print(i)
    for j in range(0,3):
        print(j)
        count  = 1
        print (grid[[i][j]])

This range should be included within grid

grid[[i][j]] = gridTile(size,size,i*(size  10),j*(size   10),"black",count)

def end():
    sqry = random.randint(0,3)
    sqrx = random.randint(0,3)
    grid[[sqry][sqrx]].colour = "white"


for i in range(0,2):
    x = random.randint(0,3)
    y = random.randint(0,3)

mainloop()

Error:

 <module>
    grid[[i][j]] = gridTile(size,size,i*(size  10),j*(size   10),"black",count)
IndexError: list index out of range

CodePudding user response:

I’m on mobile but it seems like a 2D array. In order to access the value do grid[x][y] instead of tuples or arrays.

Please correct me if I’m misunderstanding something.

CodePudding user response:

Let's look at grid[[i][j]]. The inside of that expression is [i][j]. If i = 2 and j = 3, for example, that expands to [2][3]. In other words, it creates a list [2] and then tries to get the item at index 3 from it.

That's not going to work. grid[i][j] is the correct syntax. But for real, don't do that for i in range(...) stuff. Like Matiiss said, you'd really want to write something like:

for sublist in grid:
    for item in sublist:
        print(item)
        count  = 1
  • Related