简体   繁体   English

尝试将tkinter中的图像正确显示为类的方法

[英]Try to correctly show image in tkinter into a method of a class

I am writing a class that builds a canvas and positionate elements containing Title, Description and an Icon. 我正在编写一个类,该类构建画布并定位包含Title,Description和Icon的元素。 Everything works well except the part of showing the icon. 除了显示图标的部分以外,其他所有东西都正常运行。

The class itself build the canvas and it have a method to add elements. 类本身会构建canvas ,并且具有添加元素的方法。

The problem comes when this function into the class. 当这个函数进入类时,问题就来了。

def addElement(self, title='Element title', description='Element description' icon='*')
    if self.elementnumber != 10:
        self.elementnumber = self.elementnumber+1
    else:
        raise Exception("The maximum number of elements permitted is 10.")
    element=Frame(self.iconframe.interior, name=str(self.elementnumber))
    if icon != '*':
        self.iconimage = PhotoImage(file=icon)
        elementicon = Label(element, image=self.iconimage,name='icon')
    else:
        elementicon = Label(element, name='icon')
    elementtitle = Label(element, text=title, name='title')
    elementdescription = Label(element, text=description, name='description', wraplength=155,justify=LEFT)

So, when I call the function and put an icon, if I put self. 因此,当我调用函数并放置一个图标时,如果我放置了self. to iconimage , I keep the reference and the image show correctly, but only the image for the last element. 对于iconimage ,我保留引用和图像正确显示,但仅显示最后一个元素的图像。 I know that this is because self. 我知道这是因为self. is the reference for the main class and not for the element of the function, so this element keeps updating everytime I call the function, leaving only the last icon. 是对主类的引用,而不是对函数元素的引用,因此,每次我调用该函数时,此元素都会不断更新,仅保留最后一个图标。

But, if I call the PhotoImage function without self. 但是,如果我不带self.调用PhotoImage函数self. , anyone of the images shows it correctly. ,任何图像都可以正确显示。

So i don't know how to dow it to show the images correctly. 所以我不知道该怎么做才能正确显示图像。

self.iconimage has to be a list and for each new element, you have to manage the Index of that list. self.iconimage必须是一个列表,对于每个新元素,您都必须管理该列表的Index。

Updating the self.iconimage to a list, try to use the append mehtod when adding New elements. self.iconimage更新为列表,添加新元素时尝试使用append方法。 Then, in elementicon , inform the new item appended of self.iconimage list. 然后,在elementicon ,将self.iconimage列表通知附加的新项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM