如何在 Tkinter 中新增影像?
影像在任何應用程式中都是非常有用的物件。我們可以使用 Python 中的 Pillow 或者 PIL 包在 Tkinter 應用程式中處理影像。有若干內建函式,如載入影像、提取影像、配置影像窗格等。
示例
在這個示例中,我們將透過讓使用者從一個對話方塊中選擇一張影像,然後使用 Label 控制元件顯示它來新增影像。
#Import the Tkinter library from tkinter import * from tkinter import ttk from tkinter import filedialog from PIL import Image, ImageTk #Create an instance of Tkinter frame win= Tk() #Define the geometry win.geometry("750x350") win.title("Image Gallery") def select_file(): path= filedialog.askopenfilename(title="Select an Image", filetype=(('image files','*.jpg'),('all files','*.*'))) img= Image.open(path) img=ImageTk.PhotoImage(img) label= Label(win, image= img) label.image= img label.pack() #Create a label and a Button to Open the dialog Label(win, text="Click the Button below to select an Image", font=('Caveat 15 bold')).pack(pady=20) button= ttk.Button(win, text="Select to Open", command= select_file) button.pack(ipadx=5, pady=15) win.mainloop()
輸出
執行上述程式碼將顯示一個視窗,其中包含一個按鈕,用於從目錄中選擇影像檔案,並在視窗上顯示影像。
現在,從本地目錄中選擇任意一張影像,並在螢幕上顯示輸出。
廣告