pythonpython-2.7tkinterbuttonnested-lists

Dynamic creation of buttons and storing in a 2d array problems


I'm attempting to create a list that has nine sub-lists. These sub-lists need to be able to store nine buttons, unfortunately it returns the following error:

File "C:\PythonLearning\Testing2dArrayOfButtons.py", line 18, in <module>
BButtons[count][gridX*(y)+x].grid(row=y, column=x)
IndexError: list index out of range

I believe the issue lies in the count, initially I tried using the y variable for the for loop but that didn't work at all. When using numbers 0-8 in place of the count variable it doesnt produce the error, but also doesn't dynamically place the buttons in a 2d array format.

from Tkinter import *

gridX = 9
gridY = 9

BButtons=[[] for i in range(9)]

root = Tk()

count = -1 #introduced count because 'y variable' was not working
for y in range(gridY):
    count += 1
    for x in range(gridX):
        print count
        BButtons[count].append(Button(root, text="X", height = 2, width = 4))
        print count
        print BButtons
        BButtons[count][gridX*(y)+x].grid(row=y, column=x) #gridX*(y)+x is the formula used to obtain the nested button location
        print BButtons                                     #the buttons[][].grid is setting the button positions on the scrin to a grid

print BButtons

root.mainloop()

Solution

  • BButtons[count][gridX*(y)+x]
    

    gridX has the value 9 which makes gridX*(y)+x be quite big number as y increases. That will cause IndexError.

    BButtons[y][x] should work.