1

The code

def OpenDocument(Doc):
    file = "./Account Data/Saved Docs/" + Doc
    with open(file, 'r') as f:
        content = f.readlines()
    print("Document context: " + str(content))
    Space()


def BringUpDocs():
    global globUser
    a = 0
    i = 1
    e = os.listdir("./Account Data/Saved Docs")
    text = "." + globUser

    for index in range(len(e)):
        if text in e[a]:
            if i == 1:
                Value = e[a]
                SaveData(Value)

            else:
                Value = e[a]
                SaveData(Value)

            Button(master, text=e[a],command=lambda *args: OpenDocument(Value)).grid(row=1,column=i)

            i = i + 1
            a = a + 1`

The problem is that when I run this, all buttons created by this set the variable to the same thing. How would I have them set it to the correct values rather than setting it to the last button created by this function's value? I think that this will help many people who are struggling with this type of question.

Octopusghost
  • 59
  • 1
  • 1
  • 10
  • The short answer is to add an extra parameter with a default argument, like `Value=Value`, to your `lambda`. For the long answer… I'll find a duplicate question that already has a good explanation. – abarnert May 03 '18 at 22:09
  • Also see [the official Python FAQ entry on this](https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result). – abarnert May 03 '18 at 22:11

0 Answers0