1

Im trying to make a file edit programm and in it it will list the file and a button to go to the edit screen by picking from a list of files but it will only choose the last file in the list

I tried to make it a variable in the list but that wouldnt work and anything else i tried wouldnt work. heres the code

import tkinter as tk
root = tk.Tk()

root.geometry("400x400")
root.resizable(False, False)

def test(file):
    print(file)

list = ["test.txt","test1.txt","test2.txt","test3.txt"]


for i in range(len(list)):
    file = list[i]
    print(file)
    label = tk.Label(root, text=f"{file}")
    button = tk.Button(root, command=lambda: test(file), text=f"{file}")
    label.pack()
    button.pack()

root.mainloop()
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • 3
    This is a "gotcha" with lambdas. Your lambda captures the NAME `file`, not the VALUE. By the time the loop ends, `file` has the final name. The trick is to capture it as a default argument: `lambda file=file: test(file)`. BTW, `file` and `list` are both bad names for variables, because they hide Python types. – Tim Roberts Jan 24 '23 at 03:55
  • @TimRoberts Thank you this worked and this was a test for another program so I wasn't actually gonna use file and list. TY for your answer – thecodepro90 Jan 24 '23 at 03:58
  • 1
    Does this answer your question? [tkinter creating buttons in for loop passing command arguments](https://stackoverflow.com/questions/10865116/tkinter-creating-buttons-in-for-loop-passing-command-arguments) – Delrius Euphoria Jan 24 '23 at 05:30

0 Answers0