如何更新 Tkinter 画布中的图像?

Canvas 可用于处理图像、动画对象、3D 建模、显示文本等等。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()
输出结果

运行上面的代码将显示一个带有画布的窗口和一个用于更新画布图像的按钮。

现在,单击“更新图像”按钮更新画布图像。