Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.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:tag_bind in for循环仅将最后一个标记作为lambda事件函数中的参数传递_Python_Tkinter_Tags_Bind - Fatal编程技术网

Python tkinter:tag_bind in for循环仅将最后一个标记作为lambda事件函数中的参数传递

Python tkinter:tag_bind in for循环仅将最后一个标记作为lambda事件函数中的参数传递,python,tkinter,tags,bind,Python,Tkinter,Tags,Bind,在过去的几个小时里,我一直在努力处理这部分代码,所以我决定询问stackoverflow 首先,这是我的代码: def place_checkers_init(self): for i,player_piece in enumerate(self.player_pieces): tag = "p"+str(i) square = self.frame.grid_slaves(player_piece.row, player_piece.col)[0]

在过去的几个小时里,我一直在努力处理这部分代码,所以我决定询问stackoverflow

首先,这是我的代码:

def place_checkers_init(self):  
    for i,player_piece in enumerate(self.player_pieces):
        tag = "p"+str(i)
        square = self.frame.grid_slaves(player_piece.row, player_piece.col)[0]
        piece = square.create_oval(10,10,90,90,fill=player_piece.color)
        square.itemconfig(piece, tags = tag)
        print(square.gettags(piece))
        square.tag_bind(tag, '<1>', lambda event: self.player_move(tag))
无论我点击哪个棋子,它都只打印(4,5),这是self.player_棋子列表中的最后一个棋子

我猜我的tag_bind(lambda函数)的最后一个参数出了问题,但我不知道该怎么办


我能得到一些帮助吗?谢谢大家!

您的问题的最低表述可以写成:

for f in [lambda: print(n, end=' ') for n in range(5)]:
    f()
输出:

4 4 4 4 4 # why do the lambdas only print the last value of 'n' ?
现在替换为:

for f in [lambda n=n: print(n, end=' ') for n in range(5)]:
    f()
输出

0 1 2 3 4 # yeah!

与lambda和loops相关的类似问题已经在这个网站上被问了几十次,甚至几百次。这是一个非常常见的问题,有一个简单的解决方案。在提问之前,你做过任何研究吗?@BryanOakley我查看了所有包含标记绑定和循环的帖子,并尝试根据解决方案编辑我的代码,但我的标记绑定行仍然只将最后一个标记传递到函数中。似乎传递的事件指向了正确的片段,所以我很困惑为什么标签也没有指向正确的片段。啊,是的,我意识到我忘记了什么。非常感谢。
0 1 2 3 4 # yeah!