Python3 Tkinter error

Asked

Viewed 25 times

0

good night, The idea of this code is to insert an image in a graphical interface but this always giving the error and says that can not open the image

Someone knows what’s going on?

this is my code

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()
     self.photo=PhotoImage(file='imagem.png')

root = Tk()
root.geometry('800x600')
janela(root)
root.mainloop()

1 answer

0


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.