Python, why def() is not working in this case?

Viewed 36

This code runs OK and displays resized_image:


# replicates "def place_image()" steps,
# image correctly displayed on canvas:
img = resized_image
widget  = canvas
x = 0
y = 0
anch = NW
photo = ImageTk.PhotoImage(img) #Convert To photoimage
widget.create_image(x, y, anchor = anch, image=photo)

This one just displays a black canvas:

# this does nothing, just a black canvas
def place_image(widget, x, y, anch, img):
    photo = ImageTk.PhotoImage(img) #Convert To photoimage
    widget.create_image(x, y, anchor = anch, image=photo)

place_image(canvas, 0, 0, NW, resized_image)

What is the difference?

1 Answers

This happens because it has stored the variable containing the image in a local variable which is removed immediately afterwards, so my advice is to store the variable globally.

so:

photo = ImageTk.PhotoImage(img) #Convert To photoimage
def place_image(widget, x, y, anch):
    widget.create_image(x, y, anchor = anch, image=photo)

place_image(canvas, 0, 0, NW)
Related