Tkinter Askopenfilename

Salman Mehmood 2024年2月15日
Tkinter Askopenfilename

本文將演示如何使用檔案對話方塊使用 filedialog 類中的 askopenfilename() 方法開啟檔案。無論檔案在你的計算機上的什麼位置。

當我們處理現實世界的 GUI 應用程式並希望新增一個檔案對話方塊功能來開啟檔案(影象、PDF 檔案或任何東西)時,你如何使用 Tkinter 做到這一點?使用稱為 filedialog 類的東西真的很容易。

在 Tkinter 中使用 askopenfilename() 方法開啟檔案對話方塊

askopenfilename() 負責在 Tkinter GUI 應用程式中開啟和讀取檔案;此方法存在於 filedialog 類中。

所以首先,我們需要匯入這個類,如下所示。

from tkinter import filedialog

建立 Tk() 類的例項後,我們需要在我們的 GUI 中新增一個按鈕,因此當我們單擊此按鈕時,它將啟動一個檔案對話方塊,我們可以選擇我們的檔案。

open_btn = Button(text="Open", command=openFile)
open_btn.pack()

我們建立了一個幫助開啟檔案對話方塊的 openFile() 函式。我們正在使用 filedialog 類中的方法。

def openFile():
    # takes file location and its type
    file_location = filedialog.askopenfilename(
        initialdir=r"F:\python\pythonProject\files",
        title="Dialog box",
        filetypes=(("text files", "*.txt"), ("all files", "*.*")),
    )
    # read selected file by dialog box
    file = open(file_location, "r")
    print(file.read())
    file.close()

在這個方法中,我們必須傳遞一堆不同的選項。

  1. initialdir:此選項告訴對話方塊要從哪個目錄開始,因此該框會彈出你要顯示的目錄,因此你應該使用此選項。
  2. title:這只是彈出框的標題。它的頂部會有一個小標題,你可以放任何你想要的東西。
  3. filetypes:此選項有助於選擇要顯示的檔案型別。你可以只放置所有檔案,特別是 .txt 檔案或其他副檔名。

askopenfilename() 方法返回一個字串,該字串是你的檔案所在的檔案路徑,因此我們將檔案路徑儲存在一個名為 file_location 的變數中。

現在我們將開啟並讀取該檔案的內容以建立一個檔案變數,並且我們使用了接受檔案路徑和模式的 open 函式。

我們使用 "r" 模式以閱讀模式開啟檔案。read() 方法有助於讀取整個內容並將其顯示在控制檯中。

完整的原始碼在這裡。

from tkinter import *
from tkinter import filedialog


def openFile():
    # takes file location and its type
    file_location = filedialog.askopenfilename(
        initialdir=r"F:\python\pythonProject\files",
        title="Dialog box",
        filetypes=(("text files", "*.txt"), ("all files", "*.*")),
    )
    # read selected file by dialog box
    file = open(file_location, "r")
    print(file.read())
    file.close()


gui_win = Tk()
gui_win.geometry("200x200")
gui_win.title("Delftstack")
open_btn = Button(text="Open", command=openFile)
open_btn.pack()
gui_win.mainloop()

輸出:

tkinter askopenfilename

作者: Salman Mehmood
Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

LinkedIn