pythoncanvastkintertk-toolkitphotoimage

Canvas won't show a PhotoImage pic if the code is in a method


New to python and so far mostly love it but this issue is odd. The exact same code works from the root but not in a method.

This does not render the image:

from tkinter import *      
root = Tk() 

def draw():
    print("does not work")
    canvas = Canvas(root, width = 300, height = 300)      
    canvas.pack()      
    img = PhotoImage(file="Db.png")      
    canvas.create_image(20,20, anchor=NW, image=img)      

draw()
mainloop()  

But this works fine:

from tkinter import *      
root = Tk() 

print("This works fine")
canvas = Canvas(root, width = 300, height = 300)      
canvas.pack()      
img = PhotoImage(file="Db.png")      
canvas.create_image(20,20, anchor=NW, image=img)      

mainloop()

Any help would be appreciated.


Solution

  • As martineau explains in the comments above the problem with the code is that the img variable only exists while the function is processing, it is deleted after the function returns and it's required that I keep a reference to the image object. Making it a global variable corrects the issue.

    Many Thanks!