2

I'm using Tkinter for the code below.

Goal

Use filedialog to input the path of a folder to search and return the list of "mp3" files from the folder and put all the "mp3" in one OptionMenu.

from tkinter import StringVar, filedialog
import os 
import tkinter
 
root = tkinter.Tk()
path = filedialog.askdirectory()

try:
    if not path:
        print('Canceled')
    else:    
        mp3 = [fn for fn in os.listdir(path) if fn.lower().endswith('.mp3') and os.path.isfile(os.path.join(path, fn))]
        for filename in mp3:    
            clicked = StringVar()
            tkinter.OptionMenu(root, clicked, filename).pack()
except:
    pass

root.mainloop()

The code works.

But It's giving me more than 1 OptionMenu.

iamjaydev
  • 142
  • 8
walo net
  • 31
  • 2

1 Answers1

0

The first argument of OptionMenu is the widget to put itself in, the second the StringVar to put the currently selected value in, the third the default value for the OptionMenu, and any other positional arguments will be displayed as options.

So, you need just one OptionMenu instance, to which you pass mp3 as arguments, which you can do with argument expansion by using mp3 as an argument but prefixing it with an asterisk (*).

Something else to be mentioned is that you usually shoudn't silently ignore any errors - which is why I removed the try/except. This is the correct code:

from tkinter import StringVar, filedialog
import os 
import tkinter
 
root = tkinter.Tk()
path = filedialog.askdirectory()

if not path:
    print('Canceled')
else:    
    mp3 = [fn for fn in os.listdir(path) if fn.lower().endswith('.mp3') and os.path.isfile(os.path.join(path, fn))]
    clicked = StringVar()
    tkinter.OptionMenu(root, clicked, mp3[0], *mp3).pack()

root.mainloop()
TheEagle
  • 5,808
  • 3
  • 11
  • 39