This is kind of complicated to explain. So I am making a program that opens certain files in a directory. I want to achieve this by making the files options in a submenu within a Menu. The first half (adding the menu labels) does work, but the other half (adding the menu commands) does not. In this case, the file opened is always 'file3' regardless of which file you choose via the submenu. I expected for the 'file1' option to open 'file1' etc.
Here is the hypothetical code (which was simplified on purpose; hence the file opening is just a print function for the sake of debugging):
from tkinter import *
import os
root = Tk()
def openFile(file):
print(file)
menubar = Menu(root, tearoff=0)
menubar_open = Menu(menubar, tearoff=0)
for i in ["file1", "file2", "file3"]:
i = os.path.splitext(i)[0]
menubar_open.add_command(label=i, command=lambda: openFile(file=i))
menubar.add_cascade(label="Open...", menu=menubar_open)
root.config(menu=menubar)
root.mainloop()
So the question is: What is causing this discrepancy and what can I do to solve it so it could open the file of its respective option?