This code works:
JavaScript
x
9
1
import tkinter
2
3
root = tkinter.Tk()
4
canvas = tkinter.Canvas(root)
5
canvas.grid(row = 0, column = 0)
6
photo = tkinter.PhotoImage(file = './test.gif')
7
canvas.create_image(0, 0, image=photo)
8
root.mainloop()
9
It shows me the image.
Now, this code compiles but it doesn’t show me the image, and I don’t know why, because it’s the same code, in a class:
JavaScript
1
13
13
1
import tkinter
2
3
class Test:
4
def __init__(self, master):
5
canvas = tkinter.Canvas(master)
6
canvas.grid(row = 0, column = 0)
7
photo = tkinter.PhotoImage(file = './test.gif')
8
canvas.create_image(0, 0, image=photo)
9
10
root = tkinter.Tk()
11
test = Test(root)
12
root.mainloop()
13
Advertisement
Answer
The variable photo
is a local variable which gets garbage collected after the class is instantiated. Save a reference to the photo, for example:
JavaScript
1
2
1
self.photo = tkinter.PhotoImage( )
2
If you do a Google search on “tkinter image doesn’t display”, the first result is this:
Why do my Tkinter images not appear? (The FAQ answer is currently not outdated)