Error when an image is loaded into a second Tkinter - Python window

Asked

Viewed 128 times

-2

Hello, I’m developing a small program using tkinter, where, in the first window there is a button that opens a second window where there is an image. However, the program does not carry this image, saying it does not exist. If I run the second program alone, where there is only the image, everything goes well, the problem is when it is opened by another program.

Program 'test'

from tkinter import *

def abrir():
  exec(open('teste2.py').read())

app = Tk()
app.geometry('100x100')
but = Button(app, text='abrir', command=abrir)
but.pack()
app.mainloop()

Program 'teste2'

from tkinter import *

app = Tk()
app.geometry('100x100')
img = PhotoImage(file='img/voltar.png')
lbImagem = Label(app, image=img)
lbImagem.pack()
app.mainloop()

Error message

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
    return self.func(*args)
  File "/home/saulo/PycharmProjects/testes/Construcao/teste.py", line 4, in abrir
    exec(open('teste2.py').read())
  File "<string>", line 6, in <module>
  File "/usr/lib/python3.8/tkinter/__init__.py", line 3143, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "/usr/lib/python3.8/tkinter/__init__.py", line 2567, in __init__
    self.tk.call(
_tkinter.TclError: image "pyimage1" doesn't exist

1 answer

0


The Error is in the program 'teste2', when Voce declares the img with Photoimage, you are not giving as parameter the master, which is where the image will be placed. As you are not declaring, he interprets that there is no picture to be shown.

Another error that is possible to notice, is that Photoimage does not support images .jpg. It is accepted only PGM, PPM, GIF and PNG.

You can fix this by just putting a master and changing your file to one of the accepted formats:

from tkinter import *

app = Tk()
app.geometry('100x100')

# AQUI ESTA O ERRO CORRIGIDO
img = PhotoImage(master=app, file='./img/WAZUP.gif')

lbImagem = Label(app, image=img)
lbImagem.pack()
app.mainloop()
  • Thank you very much, it worked perfectly here. NOTE: In the code I did not use image '.jpg'.

  • Oh cool, I lose I think I changed the format when I went to take the test on my pc.

Browser other questions tagged

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