filedialog
是文件对话框,在程序运行该过程中,当你需要手动选择文件或手动选择文件存储路径时,就需要用到tkinter库中filedialog提供的函数。
函数及用法
filedialog.askopenfilename(***options)
filedialog.askopenfilenames(**options)
filedialog.asksaveasfile(**options)
filedialog.askdirectory(**options)
基本案例 -选择视频文件
from tkinter import *
from tkinter.filedialog import *
root = Tk();root.geometry("400x100")
def test1():
f = askopenfilename(title="上传文件",
initialdir="f:",filetypes=[("视频文件",".mp4")])
show["text"]=f
Button(root,text="选择编辑的视频文件",command=test1).pack()
show = Label(root,width=40,height=3,bg="pink")
show.pack()
root.mainloop()
打开后即可选择:
延展-打开excel文件
from tkinter import *
from tkinter import filedialog
import tkinter.messagebox
def main():
def selectExcelfile():
sfname = filedialog.askopenfilename(title='选择Excel文件', filetypes=[('Excel', '*.xlsx'), ('All Files', '*')])
print(sfname)
text1.insert(INSERT,sfname)
def closeThisWindow():
root.destroy()
def doProcess():
tkinter.messagebox.showinfo('提示','处理Excel文件的示例程序。')
#初始化
root=Tk()
#设置窗体标题
root.title('Python GUI Learning')
#设置窗口大小和位置
root.geometry('500x300+570+200')
label1=Label(root,text='请选择文件:')
text1=Entry(root,bg='white',width=45)
button1=Button(root,text='浏览',width=8,command=selectExcelfile)
button2=Button(root,text='处理',width=8,command=doProcess)
button3=Button(root,text='退出',width=8,command=closeThisWindow)
label1.pack()
text1.pack()
button1.pack()
button2.pack()
button3.pack()
label1.place(x=30,y=30)
text1.place(x=100,y=30)
button1.place(x=390,y=26)
button2.place(x=160,y=80)
button3.place(x=260,y=80)
root.mainloop()
if __name__=="__main__":
main()
增加浏览,处理与退出按钮,更加方便使用: