Error happens because there is no attribution for the attribute photo
class janela
, he is simply called the first time in self.photo(file='imagem.png')
.
To add an image with tkinter
, one of the possible ways is:
from tkinter import *
from PIL import ImageTk,Image
class janela:
def __init__(self,master=None): #master refere se ha janela principal
#criaçao do conteiner pai
self.frame=Frame(master)
self.frame.pack()
photo = ImageTk.PhotoImage(Image.open("imagem.png"))
self.label = Label(image=photo)
self.label.photo = photo # necessário para manter referência
self.label.pack()
if __name__ == '__main__':
root = Tk()
root.geometry('800x600')
janela(root)
root.mainloop()
Comments on the solution:
- Use the PIL (Python Imaging Library) to work with an image in format
.png
and save this in a variable photo
;
- Put this variable
photo
in some component, here we opted for a label;
- Save extra image reference;
- And finally, I don’t think it’s the most beautiful solution, but it achieves the goal of presenting an image :)
For more information, including why it is necessary to keep reference to the image, I recommend the reading.