Tkinter: don't deallocate images that are in use

,

tkinter has a weird gotcha:

[…] Tk will not keep a reference to [image objects]. When the last Python reference to the image object is deleted, the image data is deleted as well, and Tk will display an empty box wherever the image was used.
tkinter — Python interface to Tcl/Tk — Python 3.14.4 documentation

I am wondering what prevents Python from fixing this.

The Tk image command has the inuse option, which can be used to determine if an image is in use in any widget. Is it unsuitable for this purpose?

Or is it necessary to keep this behavior to maintain backwards compatibility? That would make sense, but Python doesn’t guarantee when garbage collection happens. That means that programs already can’t expect that removing all references to an image will lead to immediate graphical effects.

So, is there a reason why this behavior can’t be fixed/made more intuitive?

1 Like

What to do if it is still in use when the last Python reference to the image object is deleted? Keep it forever? This would be a resource leak.