Sunday, June 06, 2010

[Py] To show or update images of label

To show or update images in a label, there is one thing important: You have to keep a reference for the image objects or they will be cleared so you won't see them on your label widgets.

I totally had no idea about this fact and tried for several hours until I read the following note:
Note: When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.

To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute, like this:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()

It's also true if you want to show images in sequence and then want to keep the last image when the update stops. Without the ``keep reference'' line, you will see the images updated sequentially and disappear after the last image being showed.

No comments:

Post a Comment