有办法创建一个在Python/Tkinter中只接受Wave文件的文件选择器吗?

huangapple go评论90阅读模式
英文:

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

问题

我正在用Python制作一个“波形生成器”,它需要波形文件才能工作。目前,我有一个文件选择器和GUI的路径,但我需要一种方法来让文件选择器专门选择波形文件。最好的方法是什么?

以下是我的代码:

  1. from tkinter import *
  2. from tkinter.filedialog import askopenfilename # 文件选择器
  3. # 创建一个窗口
  4. mainwindow = Tk()
  5. # 给窗口一个标题
  6. mainwindow.title("波形生成器工作窗口")
  7. # 设置窗口大小(宽x高)
  8. mainwindow.geometry('640x480')
  9. # 添加一些文本/标签
  10. txt = Label(mainwindow, text="波形生成器")
  11. txt.grid()
  12. # 按钮和其他内容
  13. # 文件选择器函数
  14. def filepicker():
  15. filename = askopenfilename()
  16. print(filename) # 打印文件名到控制台(这只是一个占位,用来确保它实际上能工作)
  17. btn = Button(mainwindow, text="打开文件选择器", command=filepicker) # 打开文件选择器/选择音频文件的按钮
  18. # 设置网格顺序
  19. btn.grid(column=0, row=2)
  20. # 执行
  21. mainwindow.mainloop()

注意:上述代码已经是翻译好的Python代码部分,不包括其他内容。

英文:

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:

  1. from tkinter import *
  2. from tkinter.filedialog import askopenfilename #filepicker
  3. #make a window
  4. mainwindow = Tk()
  5. #give it a title
  6. mainwindow.title("wfg working window")
  7. # set size (wxl)
  8. mainwindow.geometry('640x480')
  9. # add some text/a label
  10. txt = Label(mainwindow, text = "waveform generator")
  11. txt.grid()
  12. #button and stuff
  13. #file picker function
  14. def filepicker():
  15. filename = askopenfilename()
  16. print(filename) #print filename to the console (this is just a standin to make sure it actually works)
  17. btn = Button(mainwindow, text = "open file picker", command = filepicker) #button to open file picker/choose audiofile
  18. #set grid order
  19. btn.grid(column = 0, row = 2)
  20. #execute
  21. mainwindow.mainloop()

答案1

得分: 1

在您的 askopenfilename() 函数中,您可以使用 filetypes 选项来指定文件对话框中的文件类型。

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

如果您想要添加一个 "All files" 选项,您可以这样做:

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

参考链接

英文:

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

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

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

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

Reference

huangapple
  • 本文由 发表于 2023年6月13日 02:18:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76459311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定