Python 画布上的Tkinter图像导致错误消息

Python 画布上的Tkinter图像导致错误消息,python,image,canvas,tkinter,Python,Image,Canvas,Tkinter,我已经阅读了所有关于如何保存图像以使其不被垃圾收集的帖子。在下面的代码中,我添加了self.mapimage.image=self.map。这是可行的,但我收到了以下回调错误: AttributeError:“int”对象没有属性“image”。程序在此错误后继续工作。我们将非常感谢来自世界各地的Tkinter专家的任何帮助 类OpenClose: def __init__(self, pullcat, pullitem): self.pullcat = pullcat sel

我已经阅读了所有关于如何保存图像以使其不被垃圾收集的帖子。在下面的代码中,我添加了self.mapimage.image=self.map。这是可行的,但我收到了以下回调错误: AttributeError:“int”对象没有属性“image”。程序在此错误后继续工作。我们将非常感谢来自世界各地的Tkinter专家的任何帮助

类OpenClose:

def __init__(self, pullcat, pullitem):

    self.pullcat = pullcat
    self.pullitem = pullitem

def openfile(self):
    if self.pullitem == 'Watershed':
        self.watfile = filedialog.askopenfilename(filetypes = (("Watershed Files", "*.wshed"), ("All files", "*.*")))
    elif self.pullitem == 'Devices':
        self.devfile = filedialog.askopenfilename(filetypes = (("Devices", "*.dev"), ("All files", "*.*")))
    elif self.pullitem == 'ModelSettings':
        self.setfile = filedialog.askopenfilename(filetypes = (("Settings", "*.set"), ("All files", "*.*")))
    elif self.pullitem == 'Map':
        self.mapfile = filedialog.askopenfilename(filetypes = (("Map", "*.gif"), ("All files", "*.*")))
        self.map = PhotoImage(file = self.mapfile)
        self.mapimage = guiset.getcanob().create_image(640,480, image = self.map)
        self.mapimage.image = self.map

create_image
返回用作画布图像标识符的int。您需要对图像进行不同的引用。线路

self.map = PhotoImage(file = self.mapfile)
这就足够了。它为您提供对图像的永久引用,因此不会对其进行垃圾收集。删除这行就行了

self.mapimage.image = self.map

你应该没事的。(如果您只是使用
map
而不是
self.map
,那么当
openfile
完成时,这将是一个局部变量,它将超出范围,并且您的图像将被垃圾收集。但是由于
self.map
是您的属性
OpenClose
您将拥有对图像的引用,直到对象被删除为止为什么你认为
self.mapimage
有一个名为
image
的属性?布莱恩,谢谢你的回答。我将通过下面的链接,我现在看到你大约2年前发布的。如果取出最后一行代码,图像不会出现。任何建议都很好。