Why Doesn't A Local Name With A PhotoImage Object Work, For A Tkinter Label Image?
Solution 1:
PhotoImage
reads the image data from file and stores it in memory as a pixel buffer. The reference of this buffer has to be persistent as long as the application runs (or at least, as long the Label widget showing the image exists).
If you put the result of PhotoImage in a local variable (e.g. img
, as in the second code), the garbage collector is likely to destroy the data referenced by this local variable. On the other hand, if you store the reference of your pixel buffer in an attribute (e.g. self.img
, as in the first code) the garbage collector will not destroy your data as long as self
exists, which means as long as the application runs...
If your GUI uses many images, a usual practice is to create an attribute self.images
that puts all required images either in a tuple or a dictionary (whether you prefer indexing them by numbers or by strings), that ensures that all images will be kept in memory.
Post a Comment for "Why Doesn't A Local Name With A PhotoImage Object Work, For A Tkinter Label Image?"