1

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?

Rec
  • 53
  • 6
  • Please post a [mre]. There must be a difference in the way you're using the code in each case. – Barmar Jun 13 '22 at 21:17

1 Answers1

3

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)
Matte
  • 114
  • 7
  • I get it, but I need to move def place_image(widget, x, y, anch): etc. to another module, being able to call it from the main python file with: place_image(canvas, 0, 0, NW, resized_image) How can I do it? – Rec Jun 13 '22 at 21:33
  • @Rec if you have to use a few images I suggest you import them too, else i suggest you to store them in a data structure (depending on your code) and then import it. – Matte Jun 13 '22 at 21:37