Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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中带有lambda的tkinter按钮命令_Python_List_Python 3.x_Lambda_Tkinter - Fatal编程技术网

Python中带有lambda的tkinter按钮命令

Python中带有lambda的tkinter按钮命令,python,list,python-3.x,lambda,tkinter,Python,List,Python 3.x,Lambda,Tkinter,我试着寻找一个解决方案,但找不到一个有效的。我有一个tkinter按钮的2d列表,我想在鼠标单击时更改它们的文本。我试着这样做: def create_board(number): print(number) for i in range (0,number): buttonList.append([]) for j in range(0,number): print(i,j) buttonList[

我试着寻找一个解决方案,但找不到一个有效的。我有一个tkinter按钮的2d列表,我想在鼠标单击时更改它们的文本。我试着这样做:

def create_board(number):
    print(number)
    for i in range (0,number):
        buttonList.append([])
        for j in range(0,number):
            print(i,j)
            buttonList[i].append(Button(root, text = " ", command = lambda: update_binary_text(i,j)))
            buttonList[i][j].pack()
然后单击它时调用此函数:

def update_binary_text(first,second):
    print(first,second)
    buttonList[first][second]["text"] = "1"
当我点击一个按钮时,它什么也不做,我让程序显示被点击按钮的索引,它们都显示为4,4(这是当变量数=5时),有解决方案吗?
这是我对类的第一次python尝试


谢谢

您可以通过创建每个lambda为
i
j
创建闭包来解决此问题:

command = lambda i=i, j=j: update_binary_text(i, j)
您还可以使用对按钮对象本身的引用创建回调工厂:

def callback_factory(button):
    return lambda: button["text"] = "1"
然后在初始化代码中:

for j in range(0, number):
    new_button = Button(root, text=" ")
    new_button.configure(command=callback_factory(new_button))
    new_button.pack()
    buttonList.append(new_button)

每当我需要一组类似的小部件时,我发现将它们封装在一个对象中,并将绑定方法作为回调传递,而不是使用lambda玩把戏,这是最简单的方法。因此,与使用小部件创建类似
buttonList[]
的列表不同,创建一个对象:

class MyButton(object):
    def __init__(self, i, j):
        self.i = i
        self.j = j
        self.button = Button(..., command = self.callback)

    def callback(self):
        . . .

现在,您有了这些对象的列表
buttonList[]
,而不是小部件本身。要更新文本,请提供相应的方法,或者直接访问成员:
buttonList[i].button.configure(…)
,当激活回调时,它具有整个对象以及您在
self
中可能需要的任何属性!你的解决方案奏效了!谢谢你,先生!现在我坚持使用您发布的第一个示例。但我肯定会研究你展示的第二个例子。再次感谢!这回答了你的问题吗?