Image loading problem
Gary Herron
gherron at digipen.edu
Sat May 21 13:16:48 EDT 2016
On 05/21/2016 08:22 AM, sweating_ant at yahoo.com wrote:
> Hi All,
>
>
> 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!
>
I believe this the problem (However It's been long since I used Tkinter,
so be warned ... ):
The function load_img creates a local variable named img which goes out
of scope and is deleted immediately when the function returns. However,
Tkinter needs you to keep that image around as long as the Label uses
it. So, some solutions are:
keep_me = [] # Global for keeping references to images
def load_img(win):
img = PhotoImage(file="xxx.gif")
keep_me.append(img)
Label(win, image=img).pack()
or
def load_img(win):
img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()
return img
saved_img = load_img(win)
...
Gary Herron
--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418
More information about the Python-list
mailing list