我正在尝试创建一个包含九个子列表的列表。这些子列表需要能够存储九个按钮,不幸的是它返回以下错误:
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
我相信问题在于
count
,最初我尝试使用 y
变量作为 for
循环,但根本不起作用。当使用数字 0-8 代替计数变量时,它不会产生错误,但也不会以二维数组格式动态放置按钮。
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()
BButtons[count][gridX*(y)+x]
gridX
的值为 9,这使得随着 gridX*(y)+x
的增加,y
变得相当大。这会导致IndexError
。
BButtons[y][x]
应该可以工作。