1

I am working on a proof of concept app, so the code is not neatly written as of right now, since the final app is not meant to be written in python. I am using PySimpleGUI to create a Button with a callback lambda. The buttons are dynamically created in a for loop like this:

for tag in soup.find_all('g'):
    wantedLayer = tag.get("id")
    print(wantedLayer)
    layout.append([sg.T(tag.get("id")), sg.Input(key=tag.get("id")), sg.Button(
        wantedLayer,
        key=lambda: changeText(
            filePath=file,
            wantedId=wantedLayer,
            values=values)
        )])

I find all the g tags, I retrieve their ID and create a callback function which should change that text from the wantedLayer. As you can see, I have a print function in this for loop which prints the following:

Layer_3
Layer_2
Layer_1

This is good, this is what I want. But the problem is in the changeText func, which looks like this:

def changeText(filePath, wantedId, values):
    print(wantedId)
    return

Whenever this function gets called from any of the buttons, it just prints out Layer_1, which is wrong, it should print out the layer that I passed into it. Any idea what am I doing wrong here? Thanks.

Also, this is how the lambda gets called:

if callable(event):
    event()
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    `key=lambda wantedLayer=wantedLayer: changeText(filePath=file, wantedId=wantedLayer, values=values)` – Jason Yang Mar 04 '21 at 16:13
  • @JasonYang Oh wow, that was simple.. Could you explain why my approach wasn't working? Thanks so much! – randomprogramming Mar 04 '21 at 16:15
  • It just like a function, all variables referred only when function called, so last value used when function called. To get the value, when function defined, only default value for argument. – Jason Yang Mar 04 '21 at 16:51
  • @JasonYang: It would be good idea to write that as an answer for this question. Add a little explanation what is happening there. May be useful for others as well. – ex4 Mar 04 '21 at 18:29
  • It's duplicate issue for Lambda expression, so it's not necessary to post as an answer. – Jason Yang Mar 05 '21 at 04:27

0 Answers0