Search code examples
pythontkinteroptionmenu

Problem with python tkinter optionmenu: selecting just the last item


I have a code as the following from this link:

from tkinter import *
from tkinter.filedialog import askdirectory
import os

def onEnterDir(dropdown, var):
    path = askdirectory()
    if not path:
        return
    filenames = os.listdir(path)
    dropdown.configure(state='active')  # Enable drop down
    menu = dropdown['menu']

    # Clear the menu.
    menu.delete(0, 'end')
    for name in filenames:
        # Add menu items.
        menu.add_command(label=name, command=lambda: var.set(name))


root = Tk()
dropdownVar = StringVar()
dropdown = OptionMenu(root, dropdownVar, "Select SED...")
dropdown.grid(column=0, row=1)
dropdown.configure(state="disabled")
b = Button(root, text='Change directory',
           command=lambda: onEnterDir(dropdown, dropdownVar))
b.grid(column=1, row=1)
root.mainloop()

After running the program we get a GUI where we can select a directory then its contents are shown in the option menu. When we choose one of the items, just the last item is selected.

Would anybody help me to figure out what is the issue?


Solution

  • If you use lambda in for loop then you may have to assign value to variable before you use it inside lambda:

    command=lambda x=name: var.set(x)
    

    This way every lambda has own variable x with different value from name.

    Without this all lambdas use reference to the same place in memory - name - and get value when you click button/menu. But when you click button/menu then name has last value from for loop - so all buttons/menu uses the same value .