Home >Backend Development >Python Tutorial >Why Aren't My Tkinter Images Displaying When Created in a Function?
Tkinter Image Not Displaying When Created in a Function
In Tkinter, creating an image within a function can result in the image not being displayed. This issue occurs because the variable that references the image (photo in this case) is a local variable within the function. Once the function completes, the local variables are garbage collected, and the reference to the image is lost.
To resolve this issue, you need to save a reference to the image within the class that instantiated the function. This will ensure that the image is not garbage collected and remains accessible throughout the lifetime of the class.
For example, you can modify the code as follows:
class Test: def __init__(self, master): canvas = tkinter.Canvas(master) canvas.grid(row = 0, column = 0) self.photo = tkinter.PhotoImage(file = './test.gif') canvas.create_image(0, 0, image=self.photo)
By assigning the photo variable to self, we are creating an instance variable that will persist throughout the lifetime of the Test class.
The above is the detailed content of Why Aren't My Tkinter Images Displaying When Created in a Function?. For more information, please follow other related articles on the PHP Chinese website!