Python Forum

Full Version: Image with pillow on macos not showing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there,

I'm fairly new to programming in Python and was going through a tutorial which came across GUI programming with tkinter (Python3).

I was entering the code, pressed the button which should, as per the tutorial, show the image on the canvas, but it failed. the image (size) was drawn and removed quickly, I only saw a slight black square being drawn before everything was white again.

As this is no new issue, I found I had to keep a reference to the image for garbage collection not to get rid of it, but that wasn't helping. So I came across this code as shown below as a very simple example showing an image.

To change platform (I'm on MacOS), I installed Python and pillow on a Windows VM of mine and the very same code ran without any problems. So I figured it's got something to do with MacOS and these versions of code.

I'm running:
* MacOS Mojave 10.14.4
* Python 3.7.3
* Pillow 6.0.0

Is this quite the same issue? or is there some difference in platforms how to get the image to show? Any pointers to the solution would be greatly appreciated, thanks in advance.

#!/usr/local/bin/python3
import tkinter
from PIL import Image, ImageTk
img = Image.open('images/img.jpg')
root = tkinter.Tk()
canvas = tkinter.Canvas(root, width=img.width, height=img.height,
    background='blue', borderwidth=0, )
canvas.pack()
tkimg = ImageTk.PhotoImage(img)
imagesprite = canvas.create_image(0, 0, anchor=tkinter.NW, image=tkimg)
root.mainloop()
Result on MacOS:
[Image: tk.png]

Result on Windows:
[Image: tk2.png]
Please attach image file

** Edited **

After thinking about this a bit, I think you just have to anchor your path:

#!/usr/local/bin/python3
import tkinter
from PIL import Image, ImageTk
import os

# Anchor path
os.chdir(os.path.abspath(os.path.dirname(__file__)))

img = Image.open('images/img.jpg')
root = tkinter.Tk()
canvas = tkinter.Canvas(root, width=img.width, height=img.height,
    background='blue', borderwidth=0, )
canvas.pack()
tkimg = ImageTk.PhotoImage(img)
imagesprite = canvas.create_image(0, 0, anchor=tkinter.NW, image=tkimg)
root.mainloop()
Larz60+ thanks for your response. I can confirm that the image is found, as I see the rectangle, resembling the image, is being drawn to be erased soon after that (eg. file is found and processed). When I select a different image, another shape is quickly drawn and removed.

Yet, I tried your suggestion (programs can surprise you sometimes, so you never know...) But to no avail.

Once again, thanks for the suggestion...

Oh, about the image file to be added, it's the python logo taken from the top left on pythonprogramming.net website, merely as an example.
It must be something peculiar to the MAC then because it runs on Linux Mint as well .