Image loading problem
Peter Otten
__peter__ at web.de
Sat May 21 12:54:44 EDT 2016
sweating_ant at yahoo.com wrote:
> I am working on an image project, and I can display my image in main(). I
mean, I can load my image in my main(). Needless, it is awkward. I am trying
to load my image with a function, but got an empty image window popped up,
no image content loaded. Please take a look at code:
>
>
>
> rom Tkinter import *
>
> def load_img(win):
> img = PhotoImage(file="xxx.gif")
> Label(win, image=img).pack()
>
> win = Tk()
> load_img(win)
> win.mainloop()
>
> Somebody can help me out? Thanks!
It's not your fault, there's an odd quirk in the library: you have to keep a
reference of the PhotoImage instance around to prevent the image from being
garbage-collected. For example
from Tkinter import *
def load_img(win):
global img
img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()
win = Tk()
load_img(win)
win.mainloop()
will work because img is now a global that is not deleted until the script
ends (but don't run the function twice -- then the first image will
disappear).
More information about the Python-list
mailing list