Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.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/8/python-3.x/19.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按钮中的lambda命令,但给出错误答案_Python_Python 3.x_Tkinter - Fatal编程技术网

Python 替换Tkinter按钮中的lambda命令,但给出错误答案

Python 替换Tkinter按钮中的lambda命令,但给出错误答案,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,在我的代码中,我有一个自定义框架类,其中包含多个条目和一个按钮,该按钮应该能够从整个框架中删除自身。还有第二个按钮,用于将节添加到管理所有不同节的列表中: def addSection(): sectionNumber = len(sections) if sectionNumber <= 25: sections.append(sectionFrame(SectionsFrame.interior,sectionNumber)) secti

在我的代码中,我有一个自定义框架类,其中包含多个条目和一个按钮,该按钮应该能够从整个框架中删除自身。还有第二个按钮,用于将节添加到管理所有不同节的列表中:

def addSection():
    sectionNumber = len(sections)
    if sectionNumber <= 25:
        sections.append(sectionFrame(SectionsFrame.interior,sectionNumber))
        sections[sectionNumber].pack(side=TOP)
        sections[sectionNumber].getButton().config(command = lambda: removeSpecificSection(sections[sectionNumber].getSectionNumber()))
section.moveDownIndex()
在其自己的类中仅为
self.sectionNumber=self.sectionNumber-1

我遇到的问题是,如果我试图删除remove函数所涉及的任何部分,它只会删除最后一个部分,而进入第二次调用的索引会确认它始终是最后一个索引


也许我不理解lambda函数,为什么每个按钮在调用remove函数时没有使用自己的部分?

这是一个非常常见的初学者陷阱
lambda
是后期绑定,这意味着它在调用时使用sectionNumber中的值,而不是在定义时使用sectionNumber中的值。要获得所需的行为,需要使用
functools.partial

from functools import partial
...
sections[sectionNumber].getButton().config(command = partial(removeSpecificSection, sections[sectionNumber])))

然后调用removeSpecificSection方法中的
getSectionNumber

这是一个非常常见的初学者陷阱
lambda
是后期绑定,这意味着它在调用时使用sectionNumber中的值,而不是在定义时使用sectionNumber中的值。要获得所需的行为,需要使用
functools.partial

from functools import partial
...
sections[sectionNumber].getButton().config(command = partial(removeSpecificSection, sections[sectionNumber])))

然后调用removeSpecificSection方法中的
getSectionNumber

我的建议是停止使用lambda。这使得任何类型的调试都非常困难。使用适当的功能。只有在没有其他方法解决您的问题时才使用lambda。如果你使用lambda,只调用一个函数。我的建议是停止使用lambda。这使得任何类型的调试都非常困难。使用适当的功能。只有在没有其他方法解决您的问题时才使用lambda。如果使用lambda,则只调用单个函数。