Tkinter: button image not displayed!?

Tomasz Lisowski lisowski.tomasz at sssa.NOSPAM.com.pl
Wed Jan 31 01:25:54 EST 2001


U¿ytkownik "John Grayson" <johngrayson at home.com> napisa³ w wiadomo¶ci
news:95744c$j00$1 at nnrp1.deja.com...
> In article <956h9g$5gl$1 at news.tpi.pl>,
>   "Tomasz Lisowski" <lisowski.tomasz at sssa.NOSPAM.com.pl> wrote:
>
> ## ------  the problem  lies somewhere below -------
> Button(fr, image=PhotoImage(file="H:\\Back.gif", master=fr), command =
> f).grid(row=0, column=3, padx=2)
> Button(fr, text="Add", width=7, command=f).grid(row=1, column=0, padx=2)
> Button(fr, text="Walk", width=7, command=f).grid(row=1, column=1,
> padx=2) Button(fr, text="Exit", width=7,
> command=master.destroy).grid(row=1, column=2, padx=2)
> Button(fr, image=PhotoImage(file="H:\\Forward.gif", master=fr), command
> = f).grid(row=1, column=3, padx=2)
> fr.grid(row=0, column=4, rowspan=2, sticky=E, pady=4)
> >
> >
>
> Yes, it does!
>
> You have to keep the image you create aroung, so that
> it does not go out of scope and get garbage-collected: fix the code
> something like this:
>
> img1 = PhotoImage(file="H:\\Back.gif", master=fr)
> Button(fr, image=img1, command = f).grid(row=0, column=3, padx=2)
>
> Button(fr, text="Add", width=7, command=f).grid(row=1, column=0, padx=2)
> Button(fr, text="Walk", width=7, command=f).grid(row=1, column=1,
>        padx=2)
> Button(fr, text="Exit", width=7,
>        command=master.destroy).grid(row=1, column=2, padx=2)
> img2 = PhotoImage(file="H:\\Forward.gif", master=fr)
> Button(fr, image=img2, command = f).grid(row=1, column=3, padx=2)
>
> fr.grid(row=0, column=4, rowspan=2, sticky=E, pady=4)
>
>   John

Thanks, John, now it works fine.

BTW, don't you guys find it strange, that all widgets are registered in
their parents, when they are created (so that I don't need to keep another
variable to reference them to keep them away from the garbage collector),
but the images seem to be an exception here.

I was so sure, that the image instance MUST be registered within the Button
(so that it does not get garbage collected)! If it is not, I wonder, how the
Button knows, which image to display!?

Tomasz Lisowski





More information about the Python-list mailing list