如何在 Tkinter Canvas 中更新圖片?
畫布可以用來處理圖片、動態物件、三維建模、顯示文字等等。此外,我們還可以使用 create_image() 建構函式顯示影像檔案。
然後,讓我們建立一個可以在本地更新畫布圖片的應用程式。我們可以新增一個按鈕來觸發事件,當按鈕被按下時,畫布圖片將發生變化。
要更改特定圖片,我們可以使用 itemconfig() 建構函式來配置畫布。它獲取需要更新的影像檔案,並在視窗中顯示這些檔案。
使用三張你選擇的圖片,並將它們儲存在同一個專案目錄中。
示例
#Import the required library
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
#Create an instance of tkinter frame
win= Tk()
#Set the geometry
win.geometry("750x400")
#Define function to update the image
def update_image():
canvas.itemconfig(image_container,image=img2)
#Create a canvas and add the image into it
canvas= Canvas(win, width=650, height= 350)
canvas.pack()
#Create a button to update the canvas image
button= ttk.Button(win, text="Update",
command=lambda:update_image())
button.pack()
#Open an Image in a Variable
img1= PhotoImage(file="logo.png")
img2= PhotoImage(file="logo2.png")
img3= PhotoImage(file="logo3.png")
#Add image to the canvas
image_container =canvas.create_image(0,0, anchor="nw",image=img1)
win.mainloop()輸出
執行以上程式碼會顯示一個帶有畫布和按鈕的視窗,該按鈕用於更新畫布圖片。

現在,單擊“更新圖片”按鈕,更新畫布圖片。

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP