简体   繁体   English

如何使用 tkinter 中的 2D 列表访问按钮网格中的按钮?

[英]How to access a button in a grid of buttons using a 2D list in tkinter?

I am a beginner to tkinter and I was trying to create a 5X5 grid of buttons using a 2D list.我是 tkinter 的初学者,我试图使用 2D 列表创建一个 5X5 的按钮网格。 But if I try to change the bg colour of the button after the for loop, it only changes the colour of the buttons of the last row.但是如果我尝试在 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()

The problem is in the way you construct the list问题在于您构建列表的方式

btns=[[None]*5]*5

in this way you create a list and moltiplicate its reference per 5 times.通过这种方式,您可以创建一个列表并每 5 次对其引用进行 moltiplicate。 As this each time that it loops for add a button in the row list the same changes affects the other row lists.由于每次循环以在行列表中添加按钮时,相同的更改都会影响其他行列表。

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]
]

This is the correct way of build the list这是构建列表的正确方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM