Apr-05-2021, 05:40 PM
The difference is the context. Literally.
When you run the code in a function and create variables like this:
When you run the same code outside a function the new image is reverenced by a variable in the GLOBAL namespace. Global variables hang around as long as the module containing them, essentially forever as far as you program is concerned. If you were to del the variable the reference count for the image would go to zero and your image would get tossed in the trash and garbage collected.
If you want to use an image in tkinter you need a variable to reference the image and the variable must be a GLOBAL variable, a CLASS variable, or an INSTANCE variable. FUNCTION variables are not good for this.
When you run the code in a function and create variables like this:
newimage = ImageTk.PhotoImage(Image.open(imgstring))the new image is only referenced by a variable (newimage) in the FUNCTION namespace. When the function is done and cleans up after itself the function variables are tossed in the trash and garbage collected. Since there are now no references to the image, the image is also tossed in the trash for garbage collection.
When you run the same code outside a function the new image is reverenced by a variable in the GLOBAL namespace. Global variables hang around as long as the module containing them, essentially forever as far as you program is concerned. If you were to del the variable the reference count for the image would go to zero and your image would get tossed in the trash and garbage collected.
If you want to use an image in tkinter you need a variable to reference the image and the variable must be a GLOBAL variable, a CLASS variable, or an INSTANCE variable. FUNCTION variables are not good for this.