在Tkinter中使用askopenfilename開啟和讀取檔案?
當用戶想要從目錄中開啟檔案時,首選方法是顯示一個彈出視窗,讓使用者選擇要開啟的檔案。與大多數工具和視窗部件一樣,Tkinter 提供了一種方法來開啟一個開啟檔案的對話方塊、讀取檔案和儲存檔案。所有這些功能都是 Python 中 **filedialog** 模組的一部分。與其他視窗部件一樣,需要在筆記本中顯式匯入 filedialog。某些其他模組包含 filedialog,例如 askdirectory、askopenfilename、askopenfile、askopenfilenames、asksaveasfilename 等。
示例
在這個示例中,我們將定義一個函式,使用 **askopenfilename** 開啟並讀取檔案。
我們將定義一個應用程式,其中包含一個開啟檔案的按鈕,並將檔案的內容打包到一個 Label 視窗部件中。為了讀取檔案內容,我們將使用 **read()** 方法以及檔名。
#Import tkinter library from tkinter import * from tkinter import ttk from tkinter import filedialog #Create an instance of tkinter frame or window win= Tk() win.geometry("750x150") #Define a function to Opening the specific file using filedialog def open_files(): path= filedialog.askopenfilename(title="Select a file", filetypes=(("text files","*.txt"), ("all files","*.*"))) file= open(path,'r') txt= file.read() label.config(text=txt, font=('Courier 13 bold')) file.close() button.config(state=DISABLED) win.geometry("750x450") #Create an Empty Label to Read the content of the File label= Label(win,text="", font=('Courier 13 bold')) label.pack() #Create a button for opening files button=ttk.Button(win, text="Open",command=open_files) button.pack(pady=30) win.mainloop()
輸出
執行上述程式碼將顯示一個視窗,其中包含一個按鈕,單擊該按鈕將開啟一個新視窗來載入和讀取檔案內容。
單擊“開啟”按鈕以開啟視窗中的檔案(文字,“*”)。
廣告