Tkinter Image Button Bug

Russell E. Owen no at spam.invalid
Wed Jul 2 14:47:45 EDT 2003


In article <mailman.1057155723.30289.python-list at python.org>,
 Erhan Ekici <erhan at uzem.itu.edu.tr> wrote:

>There is a problem in my code.I think it is Tkinter bug....
>it works but doesn't display image. Instead of 
>image, only a square with color=#dddddd comes on screen.

I think you are running into a common Tkinter pitfall (it is an 
intentional design decision, but I do not recall the argument for it): 
you need to explicitly maintain references to images; putting them in a 
Tkinter widget is not sufficient.

In your code "icon" is garbage-collected when the function exits because 
using it to set the icon of the label b does not increment its reference 
count.

I am almost certain it suffices to assign b._iconref = icon (_iconref 
being an attribute that the Label b is not likely to already have).

I've appended your code suitably modified. I've not tested it.

-- Russell

>from Tkinter import *
>
>main=Tk()
>
>def toolbar(master):
>    toolbar= Frame(master)
>    pfile ="C:\\Python22\\samples\\ftp\\images\\help.gif"
>    icon = PhotoImage(file=pfile)
>    b=Label(toolbar, image=icon, width=10)
      b._iconref = icon
>    b.config(background="#dddddd", bd=1, relief=FLAT)
>    b.pack(side=LEFT, padx=2, pady=2)
>    #toolbar.config(background="#ffffff", bd=2, relief=GROOVE)
>    toolbar.pack(side=TOP, expand=YES, fill=X)
>       
>
>toolbar(main)
>main.mainloop()




More information about the Python-list mailing list