使用 Tkinter 建立瀏覽按鈕
為了在 Tkinter 應用程式中建立按鈕,我們可以使用 Button 控制元件。按鈕可用於處理應用程式執行時的事件執行。我們可以透過定義 Button(parent, text, **options) 建構函式來建立一個按鈕。
假設我們想要建立一個瀏覽按鈕,當單擊該按鈕時,它將要求使用者從系統資源管理器中選擇一個檔案。為了建立一個用於選擇檔案的對話方塊,我們可以使用 Tkinter 庫中的 filedialog 包。我們可以使用以下命令將 filedialog 匯入筆記本中,
from tkinter import filedialog
一旦將包匯入到程式中,我們就可以使用它建立一個用於開啟和選擇所有 Python 檔案的對話方塊,並且它將返回該特定檔案中存在的字元數。
示例
# Import the required Libraries from tkinter import * from tkinter import ttk, filedialog from tkinter.filedialog import askopenfile # Create an instance of tkinter frame win = Tk() # Set the geometry of tkinter frame win.geometry("700x350") def open_file(): file = filedialog.askopenfile(mode='r', filetypes=[('Python Files', '*.py')]) if file: content = file.read() file.close() print("%d characters in this file" % len(content)) # Add a Label widget label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13')) label.pack(pady=10) # Create a Button ttk.Button(win, text="Browse", command=open_file).pack(pady=20) win.mainloop()
輸出
現在,執行上述程式碼以瀏覽並從系統資源管理器中選擇檔案。
廣告