How to know if an object is still be referenced?

jfong at ms4.hinet.net jfong at ms4.hinet.net
Tue Mar 1 21:35:10 EST 2016


Recently I was puzzled by a tkinter problem. The codes below (from a book) can display the picture correctly.

    gifdir = "../gifs/"
    from tkinter import *
    win = Tk()
    photo = PhotoImage(file=gifdir + "ora-pp.gif")
    Button(win, image=photo).pack()
    win.mainloop()

And the codes below (from another book) will also work.

    class DrumMachine:
        ....
        ....
        def create_play_bar(self):
            ....
            ....
            photo = PhotoImage(file='images/signature.gif')
            label = Label(playbar_frame, image=photo)
            label.image = photo
            label.grid(row=start_row, column=50, padx=1, sticky='w')
        ....
        ....

In the second example, I noticed that the "photo" was referenced two times and I think it might be a redundancy so I remove the line "label.image = photo". But it fails then.

How can it be? one works and the other not.

I search for answers on the web and here are some links talking about it:

http://stackoverflow.com/questions/20812579/why-it-shows-blank-instead-of-picture-in-my-tkinter-program
http://effbot.org/tkinterbook/photoimage.htm

They all said that you have to keep a reference to the "photo" or else it will be garbage collected. Now, as I had learn Python so far, I know that a keyword argument passed in an object instantiation will bind this object to its attribute name, i.e. create a reference to this object. (and it should or the whole language will be in disaster)

Can anyone help me out?




More information about the Python-list mailing list