如何使用 photoimage 物件在 Tkinter 中使用影像?
Python 支援 PIL 或 Pillow 包,這是一個開源庫,用於在 Python 專案中開啟、處理和儲存不同格式的影像。我們可以在 Tkinter 應用程式中使用它來處理和顯示影像。
Tkinter 中的 Label 元件用於在 Tkinter 應用程式中渲染文字和影像。要使用 Tkinter 應用程式中的 Label 元件顯示影像,我們可以按照以下步驟操作:
確保系統中已安裝 Pillow 或 PIL 包。
使用 ImageTk.PhotoImage(file=file_location) 函式在變數中載入影像。
建立一個 Label 元件,將影像值分配為影像。
執行程式碼以顯示影像。
示例
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x470")
# load the image and convert it into Tkinter Photoimage
bg=ImageTk.PhotoImage(file="baseball.png")
# Add a label widget to display the image
label=Label(win, image=bg)
label.place(x=0, y=0)
win.mainloop()輸出
執行程式碼以在 Tkinter 視窗中顯示影像。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP