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

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

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", "*.*")))

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:

确定