如何為 Tkinter 檔案對話方塊提供焦點?


Tkinter Python 庫可以用來建立有功能有特色的應用程式。它有許多用於不同功能的包和函式。Tkinter 中的 filedialog 包提供與本地計算機中的檔案系統進行互動的訪問許可權。使用 filedialog,我們可以從系統獲取任何檔案,並用它來執行 CRUD 操作。

為了給檔案對話方塊提供焦點,我們可以有一個與該對話方塊關聯的父視窗。如果主視窗在頂部全域性定義,則關聯的小工具將自動在其他小工具頂部獲得焦點。

示例

在此示例中,我們建立了一個按鈕,該按鈕將開啟一個對話方塊,以便從本地系統中選擇檔案。

# Import the tkinter library
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the Tkinter window
win.geometry("700x350")

# Set the title of the window
win.title("File Explorer")

# Define the function to open the file dialog
def open_file():
   win.filename = filedialog.askopenfilename(title="Select the file", filetypes=(("jpg files", "*.jpg"), ("all files", "*.*")))]

# Create a Button widget
b1 = Button(win, text="Open", command=open_file)
b1.place(relx=.5, rely=.5, anchor=CENTER)
win.mainloop()

輸出

執行上述程式碼會顯示一個帶有按鈕的視窗。

單擊按鈕後,它將顯示一個對話方塊,使用者可以在其中從本地系統選擇一個檔案。

更新於: 07-06-2021

809 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.