【问题标题】:Dynamic creation of buttons and storing in a 2d array problems动态创建按钮和存储在二维数组中的问题
【发布时间】:2016-07-29 13:06:32
【问题描述】:

我正在尝试创建一个包含九个子列表的列表。这些子列表需要能够存储九个按钮,不幸的是它返回以下错误:

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 代替 count 变量时,它不会产生错误,但也不会以二维数组格式动态放置按钮。

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()

【问题讨论】:

    标签: arrays python-2.7 button multidimensional-array tkinter


    【解决方案1】:
    BButtons[count][gridX*(y)+x]
    

    gridX 的值是 9,这使得随着 y 的增加,gridX*(y)+x 成为一个相当大的数字。这将导致IndexError

    BButtons[y][x] 应该可以工作。

    【讨论】:

    • 谢谢,我不知道我是怎么弄糊涂的。 gridX*(y)+x 最初用于为按钮分配文本,出于某种愚蠢的原因,我认为它会起作用。
    猜你喜欢
    • 2013-02-22
    • 2011-08-14
    • 2020-05-20
    • 2017-06-01
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多