-2

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* ;

Bruno.
  • 3
  • 3
  • All questions on StackOverflow should be posted in English so that everyone can understand the question and provide potential solutions. – Suever Jun 04 '16 at 13:32
  • The problem is that you're creating two instances of `Tk`: `a=Tk()` and `b=Tk()`. You must only create one instance. – Bryan Oakley Jun 04 '16 at 13:32
  • Yes, I figured it out so I made the function `def abir2():` creating a `Toplevel ( )` there is no problem with the second instance of tkinter. If you could suggest an alternative way I would appreciate it . – Bruno. Jun 04 '16 at 13:41
  • Suever I corrected the language. – Bruno. Jun 04 '16 at 13:42

1 Answers1

0

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

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685