【问题标题】:How to access a button in a grid of buttons using a 2D list in tkinter?如何使用 tkinter 中的 2D 列表访问按钮网格中的按钮?
【发布时间】:2020-01-11 10:39:08
【问题描述】:

我是 tkinter 的初学者,我正在尝试使用 2D 列表创建一个 5X5 的按钮网格。 但是如果我尝试在for循环之后改变按钮的bg颜色,它只会改变最后一行按钮的颜色。

from tkinter import *
rows=5
columns=5
btns=[[None]*5]*5
root=Tk()
def darken(btn):
    btn.configure(bg='black')
for i in range(rows):
    for j in range(columns):
        btns[i][j]=Button(root,padx=10,bg='white')
        btns[i][j]['command']=lambda btn=btns[i][j]:darken(btn)
        btns[i][j].grid(row=i,column=j)
btns[0][0]['bg']='yellow'
root.mainloop()

【问题讨论】:

    标签: python python-3.x button tkinter 2d


    【解决方案1】:

    问题在于你构建列表的方式

    btns=[[None]*5]*5
    

    通过这种方式,您可以创建一个列表并每 5 次对其引用进行蜕皮。 因为每次循环在行列表中添加按钮时,相同的更改都会影响其他行列表。

    EX

    btns = [[None]*5]*5
    btns[0][0] = 'a'
    
    btns ---> [
    ['a', None, None, None, None],
    ['a', None, None, None, None],
    ['a', None, None, None, None],
    ['a', None, None, None, None],
    ['a', None, None, None, None]
    ]
    

    这是建立列表的正确方法

    btns = [[None for i in range(rows)] for j in range(columns)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      • 2015-02-07
      相关资源
      最近更新 更多