Search code examples
pythontkinterpathdirectoryoptionmenu

Adding Multiple Folder Names From Directory To OptionMenu Python


I am trying to add multiple folder names to an options menu. The code below adds only one folder name to the list but I want to add all folder names in the directory.

var = StringVar()
os.chdir('C:\\Users\\mhoban')
all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
for dirs in all_subdirs:
    dir = os.path.join('C:\\Users\\mhoban', dirs)
    os.chdir(dir)
    current = os.getcwd()
    new = str(current).split("\\")[3]

opt1 = OptionMenu(app, var, new)
opt1.grid(row=0, column=1, padx=10, pady=10)
opt1.configure(width = 40, bg = "White")

Solution

  • You need to build a list of menu options and then unpack it where you're passing new at the moment:

    options = []
    for dirs in all_subdirs:
        ...  # same
        options.append(str(current).split("\\")[3])
    

    Unpacking options:

    opt1 = OptionMenu(app, var, *options)
    

    Note: options will be the same as all_subdirs, so your processing doesn't seem to achieve anything. Just use all_subdirs instead.