如何在 Tkinter 畫布專案中插入一張圖片?


Tkinter 畫布是 Tkinter 庫中最通用的部件。它用於建立影像、形狀、弧形、動畫物件以及許多其他作品。為了處理和處理影像,Python 支援 Pillow 包或 PIL。我們可以使用 **create_image(width, height, image_location, options)** 方法在畫布中新增影像作為專案。我們還可以透過定義錨 (options) 屬性等位置引數,指定影像應在視窗中開啟的位置。

示例

#Import the required Libraries
from tkinter import *
from PIL import Image,ImageTk

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

#Set the geometry of tkinter frame
win.geometry("750x250")

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

#Load an image in the script
img= ImageTk.PhotoImage(Image.open("download.png"))

#Add image to the Canvas Items
canvas.create_image(10,10,anchor=NW,image=img)

win.mainloop()

輸出

執行以上程式碼,在畫布中顯示影像。

更新時間:04-May-2021

25000+ 瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告