Python Tkinter 中的 askopenfile() 函式
我們可以使用 GUI 允許使用者瀏覽作業系統資料夾結構,還可以讓使用者選擇檔案,而不是對 Python 程式使用的檔案路徑進行硬編碼。我們使用其中定義畫布並在上面放置按鈕用於瀏覽檔案的 Tkinter 模組來實現這一點。
在下面的程式中,我們定義檔案開啟器函式。我們僅使用此函式開啟一個文字檔案,因為 Python 可以讀取文字檔案的內容,並且能夠以更易讀的方式將其輸出。我們可以讀取任何基於文字的檔案,例如 .txt 或 .csv 檔案。
示例
from tkinter import *
from tkinter import filedialog
base = Tk()
# Create a canvas
base.geometry('150x150')
# Function for opening the file
def file_opener():
input = filedialog.askopenfile(initialdir="/")
print(input)
for i in input:
print(i)
# Button label
x = Button(base, text ='Select a .txt/.csv file', command = lambda:file_opener())
x.pack()
mainloop()下面會彈出一個對話方塊,用於瀏覽檔案。
然後我們選擇一個檔案。
輸出
執行上面的程式碼會得到以下結果−
<_io.TextIOWrapper name='C:/Users/Pradeep/Documents/welcome.txt' mode='r' encoding='cp1252'> Hello There ! Welcome to Tutorialspoint!
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP