如何在 Tkinter 視窗中繪製圖像?


要使用 Tkinter 和其他 Python 包處理影像,我們通常會參考在 Python 中使用 Pillow 包或 PIL。它提供了一種在程式中載入和處理影像的方式,無論我們何時何地需要。最初,我們將影像轉換為 PhotoImage 物件的一個例項,這樣就可以在許多用例中進一步使用影像。此外,Tkinter 中的畫布小部件有助於在 Tkinter 應用程式中繪製圖像,我們可以使用 create_image(x,y, image_file) 方法在特定應用程式中顯示影像。

示例

#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("750x270")
#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()

輸出

執行以上程式碼將顯示一個視窗,其中會在畫布小部件中顯示一張影像。

為了替換或更改給定輸出中的影像檔案,只需在 Image.Open(檔名) 方法中匯入該影像即可。

更新時間:03-May-2021

1 千以上瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.