Devon M
Devon M

Reputation: 761

Procedure executes differently when imported than when run in its native module

I have this code:

def Annabeth():
    Annabeth= Tk()
    Annabeth.geometry('450x450')
    says = Label(Annabeth,text ='I was just making a general statement!')
    says.pack(side=BOTTOM)
     img = ImageTk.PhotoImage(Image.open('C:/Users/Geekman2/Pictures/Pictures/Annabeth.jpg'))
    image1 = Label(Annabeth,image=img)
    image1.pack()
    Annabeth.mainloop()

it resides in the module

rox

when I invoke

Annabeth()

my window comes up, it displays the image, and everything works fine. and when, from another module I use the code

from rox import*
Annabeth()

it works just fine but when I use this code

def callback():
     Annabeth()

game = Tk()
game.geometry('50x50+700+100')
Button1 = Button(game,text = '1',command =callback )
Button1.pack(side=LEFT)


game.mainloop()

The window displays, but the picture does not show up and I get the error

File "C:\Python27\lib\lib-tk\Tkinter.py", line 1974, in __init__
(widgetName, self._w) + extra + self._options(cnf))
TclError: image "pyimage1" doesn't exist

And for the life of me I cannot figure out what is causing this, apparently I'm not supposed to have more than one mainloop in a GUI program, but how am I supposed to do this then?

Upvotes: 1

Views: 636

Answers (1)

FabienAndre
FabienAndre

Reputation: 4623

You are not supposed to instanciate Tk() several times in your program. You might consider using Toplevel if you want multiple windows.

By the way, it will solve your several mainloop issue since Toplevel instances will run in the same mainloop as game.

What happens exactly is that ImageTk.PhotoImage creates the image in the first Tcl/Tk interpreter that has been created. Thus, your label image1 that run in a second Tcl/Tk instance can not reach the picture.

Upvotes: 2

Related Questions