Search code examples
pythontkinteraudiowavfilepicker

is there a way to make a file picker that only accepts wave files in python/tkinter?


i'm making a "waveform generator" in python that requires wave files to work. currently, i have a filepicker and path for my gui, but i need a way to make the file picker exclusively pick wave files. what would be the best way to do that?

below is my code:

​from tkinter import * 

from tkinter.filedialog import askopenfilename #filepicker

#make a window 
mainwindow = Tk()

#give it a title
mainwindow.title("wfg working window")

# set size (wxl)
mainwindow.geometry('640x480')

# add some text/a label
txt = Label(mainwindow, text = "waveform generator")
txt.grid()

#button and stuff
    #file picker function
def filepicker():
    filename = askopenfilename()
    print(filename) #print filename to the console (this is just a standin to make sure it actually works)

btn = Button(mainwindow, text = "open file picker", command = filepicker) #button to open file picker/choose audiofile

#set grid order
btn.grid(column = 0, row = 2)

#execute
mainwindow.mainloop()

Solution

  • In your askopenfilename() function, you can specify file types in the file dialog by using the filetypes option.

    filename = askopenfilename(filetypes=(("Wave files", "*.wav"),))
    

    In case you want to add an option for All files, u can do sth like that

    filename = askopenfilename(filetypes=(("Wave files", "*.wav"), ("All files", "*.*")))
    

    Reference