Tkinter 背景图报错: TclError: image "pyimage8" doesn't exist 的解决方法
这个错误通常是由于创建图像对象时没有保持对它的引用而导致的。可能是在函数或类中的局部变量中创建了图像对象,这些变量在函数或方法执行结束后就被销毁了。为了解决这个问题,可以在创建图像对象后将其保持为全局变量或类变量,这样它就不会被销毁。
在这个特定的例子中,可以将 'background_img' 保持为全局变量,如下所示:
import tkinter as tk
from PIL import Image, ImageTk
# 创建窗口
window = tk.Tk()
window.title('背景图演示')
# 加载背景图
img = Image.open('数据科学.jpg')
img = img.resize((600, 400), Image.ANTIALIAS)
background_img = ImageTk.PhotoImage(img)
# 创建Canvas组件并插入背景图
canvas = tk.Canvas(window, width=600, height=400)
canvas.pack(fill='both', expand=True)
canvas.create_image(0, 0, image=background_img, anchor='nw')
# 保持background_img为全局变量
window.background_img = background_img
# 运行窗口
window.mainloop()
原文地址: https://www.cveoy.top/t/topic/oshn 著作权归作者所有。请勿转载和采集!