Reputation: 313
Tkinter doesn't draw image to canvas from another method.
Example 1 works, example 2 does not work. Can someone please explain why?
def init_gui(self):
window = tkinter.Tk()
self.canvas = tkinter.Canvas(self.window, width=1000, height=500)
photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(self.img))
self.canvas.create_image(0, 0, image=photo, anchor=tkinter.NW)
self.canvas.pack()
window.mainloop()
pass
def init_gui(self):
window = tkinter.Tk()
self.canvas = tkinter.Canvas(self.window, width=1000, height=500)
self._draw_img() # the exact same code, only in another method
window.mainloop()
pass
def _draw_img(self):
photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(self.img))
self.canvas.create_image(0, 0, image=photo, anchor=tkinter.NW)
self.canvas.pack()
pass
Upvotes: 2
Views: 1016
Reputation: 6369
If I remember correctly, there's a problem in Tkinter when the image you're displaying goes out of scope (because it's a local variable). Try to make photo
an attribute of your class (by replacing photo
with self.photo
in your _draw_image
function) and see if that solves the issue.
Does this help?
Edit
For a more complete explanation, see this website: http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm
Upvotes: 4