0

I want to add an image as background to my windows in Tkinter Python which are interlinked to each other using buttons. When I run the code by default my first window opens with image and on pressing the button to another window it opens as well, but when I press the back button to first window it gives me pyimage3 does not exists error.

tkinter.TclError: image "pyimage3" doesn't exist

I have tried the solutions posted on above link but none worked for me.

from tkinter import *


def win1():

    global window1
    global window2

    def goto2():
        window1.withdraw()
        win2()

    window1=Tk()
    window1.title('Window1')
    window1.geometry('300x300')


    img1=PhotoImage(file='wood.png')
    l1=Label(window1,image=img1,width=160,height=300)

    l1.image = img1

    l1.place(x=0,y=0)


    b=Button(window1,text='go to 2',command=goto2)
    b.pack()
    window1.mainloop()


def win2():
    global window2
    global window1

    def goto1():
        window2.withdraw()
        win1()



    window2=Toplevel()
    window2.title('Window2')
    window1.geometry('300x300')

    img2=PhotoImage(file='for.png')
    l2=Label(window2,image=img2,width=160,height=300)
    l2.image = img2

    l2.place(x=0,y=0)


    b1=Button(window2,text='go to  1',command=goto1)
    b1.pack()
    window2.mainloop()


win1()


error


File "/usr/lib/python3.7/tkinter/__init__.py", line 2299, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage3" doesn't exist
Rasgel
  • 152
  • 1
  • 1
  • 13
Lucy Nerd
  • 5
  • 3
  • Among other things, the way you're switching windows is broken. Suggest you use a different architecture, see [this answer](https://stackoverflow.com/questions/7546050/switch-between-two-frames-in-tkinter/7557028#7557028) for one alternative. – martineau Apr 15 '19 at 07:42

1 Answers1

0

It is better to use a different approach as martineau suggested, but yours can also work with two minor changes.

Firstly, you don't have to call window2.mainloop() as you are using Toplevel.

Secondly, since you called withdraw on your window1 - just use deiconify() to recall it back.

def win2():
    global window2
    global window1

    def goto1():
        window2.destroy()
        #win1()
        window1.deiconify()


    window2=Toplevel()
    window2.title('Window2')
    window1.geometry('300x300')

    img2=PhotoImage(file='clear.png')
    l2=Label(window2,image=img2,width=160,height=300)
    l2.image = img2

    l2.pack()


    b1=Button(window2,text='go to  1',command=goto1)
    b1.pack()
    #window2.mainloop()
Henry Yik
  • 22,275
  • 4
  • 18
  • 40