I have a pretty complex Tkinter GUI so it's worth while to avoid repeating work assigning controls by using lambda functions. Here the code extract:
def createRightMenu(self, treeName, commands: []):
for cmd in commands:
self.rightMouse[treeName].add_command(label= cmd['label'], command= lambda: self.execCommand(cmd['reqId']))
self.tree[treeName].bind("<Button-3>", lambda event:
self.rightMouse_click(event.x_root, event.y_root, treeName))
def execCommand(self, reqId):
print("execCommand", reqId)
self.tree = {}
treeName = 'a'
self.createTree(root, treeName)
self.createRightMenu(treeName , [
{'label': 'copy', 'reqId': 1},
{'label': 'retrieve', 'reqId': 2},
])
What does work? In my right click menu I get the entries 'copy' and 'retrieve' and execCommand is called.
What does NOT work? execCommand gets ALWAYS the last list element, i.e. 'retrieve', 2 as parameter even if I right click on 'copy'. If I manually add the two .add_command's all is fine. Only using a for loop doesn't work. Any idea why?