I have a chart function that saves the end figure as a file. After I run the function, I also want it to display the figure at the end. So, I use this:
from PIL import Image
filepath = 'image.png'
img = Image.open(filepath)
img.show()
It works just fine, but when the file opens, it opens with a random file name, not the actual file name.
This can get troublesome as I have a lot of different chart functions that work in a similar fashion, so having logical names is a plus.
Is there a way I can open an image file with Python and have it display it's original file name?
EDIT
I'm using Windows, btw.
EDIT2
Updated the example with code that shows the same behaviour.
CodePudding user response:
Instead of PIL
you could use this:-
import os
filepath = "path"
os.startfile(filepath)
Using this method will open the file using system editor.
Or with PIL
,
import Tkinter as tk
from PIL import Image, ImageTk # Place this at the end (to avoid any conflicts/errors)
window = tk.Tk()
#window.geometry("500x500") # (optional)
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()
CodePudding user response:
The function img.show() opens a Windows utility to display the image. The image is first written to a temporary file before it is displayed. Here is the section from the PIL docs. https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.show
" Image.show(title=None, command=None)[source] Displays this image. This method is mainly intended for debugging purposes.
This method calls PIL.ImageShow.show() internally. You can use PIL.ImageShow.register() to override its default behaviour.
The image is first saved to a temporary file. By default, it will be in PNG format.
On Unix, the image is then opened using the display, eog or xv utility, depending on which one can be found.
On macOS, the image is opened with the native Preview application.
On Windows, the image is opened with the standard PNG display utility.
Parameters title – Optional title to use for the image window, where possible. "
The issue is that PIL uses a quick-and-dirty method for showing your image, and it's not intended for serious application use.