askopenfilename(**options) 傳回打開的檔案名
askopenfilenames(**options) 傳回打開的多個檔案名清單
askopenfile(**options) 傳回打開檔案對象
askopenfiles(**options) 傳回打開的檔案對象的清單
askdirectory(**options) 傳回目錄名
asksaveasfile(**options) 傳回儲存的檔案對象
asksaveasfilename(**options) 傳回儲存的檔案名
參數options的常見值如下:
defaultextension 預設字尾:.xxx 使用者沒有輸入則自動添加
filetypes=[(label1,pattern1),(labe2,patt ern2)] 檔案顯示過濾器
initialdir 初始目錄
initialfile 初始檔案
parent 父視窗,預設根視窗
title 視窗标題
#coding=utf-8
from tkinter import *
from tkinter.filedialog import *
class Application(Frame):
def __init__(self,master):
super().__init__(master)
self.master=master
self.pack()
self.createWidget()
def createWidget(self):
self.btn=Button(self,text="選擇檔案",command=self.test1)
self.btn.pack()
self.label=Label(self,bg='green',width=200,height=2)
self.label.pack()
def test1(self):
#選擇檔案後傳回檔案名稱-字元串
'''
initialdir='f:\\電影1' 表示預設打開F盤裡的'電影1'目錄
filetypes=[("視訊檔案","mp4")] 表示隻過濾出MP4的視訊檔案
'''
#askopenfilename()不是一個元件,是以不能傳遞目前對象self
self.af=askopenfilename(title="上傳檔案",initialdir='f:\\電影1',filetypes=[("視訊檔案","mp4")])
#将選擇的檔案擷取的檔案名稱指派給标簽元件的text屬性,用于回顯出來
self.label["text"]=self.af
if __name__=="__main__":
root=Tk()
root.title("選擇檔案")
root.geometry("350x300")
app=Application(root)
root.mainloop()
選擇檔案1.png
選擇檔案2.png
#coding=utf-8
from tkinter import *
from tkinter.filedialog import *
class Application(Frame):
def __init__(self,master):
super().__init__(master)
self.master=master
self.pack()
self.createWidget()
def createWidget(self):
self.btn=Button(self,text="選擇檔案",command=self.test1)
self.btn.pack()
self.label=Label(self,bg='green',width=200,height=10)
self.label.pack()
def test1(self):
#選打開檔案後傳回檔案對象
'''
initialdir='E:\\HDCZU_Test\\Test' 表示預設打開E盤裡的'HDCZU_Test\Test'目錄
filetypes=[("文本檔案","txt")] 表示隻過濾出txt的文本檔案
'''
#askopenfile()不是一個元件,是以不能傳遞目前對象self
with askopenfile(title="讀取檔案",initialdir='E:\\HDCZU_Test\\Test',filetypes=[("文本檔案","txt")]) as f:
self.label["text"] = f.read() #将選擇打開的檔案擷取的檔案對象讀取出來指派給Label标簽的text屬性,用于回顯出來
if __name__=="__main__":
root=Tk()
root.title("選擇檔案")
root.geometry("350x300")
app=Application(root)
root.mainloop()
選擇檔案3.png
選擇檔案4.png