英文:
is there a way to make a file picker that only accepts wave files in python/tkinter?
问题
我正在用Python制作一个“波形生成器”,它需要波形文件才能工作。目前,我有一个文件选择器和GUI的路径,但我需要一种方法来让文件选择器专门选择波形文件。最好的方法是什么?
以下是我的代码:
from tkinter import *
from tkinter.filedialog import askopenfilename # 文件选择器
# 创建一个窗口
mainwindow = Tk()
# 给窗口一个标题
mainwindow.title("波形生成器工作窗口")
# 设置窗口大小(宽x高)
mainwindow.geometry('640x480')
# 添加一些文本/标签
txt = Label(mainwindow, text="波形生成器")
txt.grid()
# 按钮和其他内容
# 文件选择器函数
def filepicker():
filename = askopenfilename()
print(filename) # 打印文件名到控制台(这只是一个占位,用来确保它实际上能工作)
btn = Button(mainwindow, text="打开文件选择器", command=filepicker) # 打开文件选择器/选择音频文件的按钮
# 设置网格顺序
btn.grid(column=0, row=2)
# 执行
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:
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()
答案1
得分: 1
在您的 askopenfilename()
函数中,您可以使用 filetypes
选项来指定文件对话框中的文件类型。
filename = askopenfilename(filetypes=(("Wave files", "*.wav"),))
如果您想要添加一个 "All files" 选项,您可以这样做:
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.
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", "*.*")))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论