如何在 Python tkinter 畫布上繪製一張 png 圖片?


要在 tkinter 中使用圖片,Python 提供了 PIL 或 Pillow 工具包。它有許多內建函式可用於操作不同格式的圖片。

要在畫布視窗小部件中開啟圖片,我們需要使用 create_image(x, y, image, **options) 建構函式。當我們將圖片值傳遞給該建構函式時,它將在畫布中顯示該圖片。

示例

# 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("700x600")

# Create a canvas widget
canvas=Canvas(win, width=700, height=600)
canvas.pack()

# Load the image
img=ImageTk.PhotoImage(file="Monalisa.png")

# Add the image in the canvas
canvas.create_image(350, 400, image=img, anchor="center")

win.mainloop()

輸出

執行以上程式碼會顯示一個視窗,該視窗包含畫布中的圖片。

更新於: 05-Aug-2021

已瀏覽 3000+ 次

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.