Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用tkinter中的2D列表访问按钮网格中的按钮?_Python_Python 3.x_Button_Tkinter_2d - Fatal编程技术网

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

Python 如何使用tkinter中的2D列表访问按钮网格中的按钮?,python,python-3.x,button,tkinter,2d,Python,Python 3.x,Button,Tkinter,2d,我是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):

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

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

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