Search code examples
pythontkintertkinter-canvastoplevelphotoimage

Python- tkinter: Opening One Another image in another window?


Hello I am doing a job that I need (from a tkinter window containing an image) call another window that contains another imagem.I tried the following:

from tkinter import*

def abrir1():
    b =Tk()
    imagen = PhotoImage(file= "F2.png")
    la = Label(b,image =imagen)
    la.pack()

def abrir2():
    b =Toplevel()
    imagen = PhotoImage(file= "F2.png")
    la = Label(b,image =imagen)
    la.pack() 

a = Tk()
canvas = Canvas(a, bg ="black",width = 512,height =512)
canvas.pack()

imagem = PhotoImage(file = "E2.png")
a1 = canvas.create_image(256,256,image = imagem)

btu1 = Button(a,text ="Abri1!",command = abrir1)
btu1.place(x = 150,y=400)
btu2 = Button(a,text ="Abri2!",command = abrir2)
btu2.place(x = 300,y=400)

But when I press the first button ( btu1 ) it returns the following error message:

_tkinter.TclError: image "pyimage2" doesn't exist

And when when I press the second button ( btu2 ) does not happen error but does not show the image, only the new window is created ;

I've tried several ways including placing * with canvas and without canvas* ;


Solution

  • You have two problems in your code.

    The first problem is that you are creating two instances of Tk. A tkinter program needs to have exactly one instance.

    The second problem is that the image you are creating is saved as a local variable. When the function returns, the variable is garbage collected. When a tkinter image is garbage collected the image data is discarded even though the widget still exists.

    A very basic search of the internet yields this page: http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm