使用Python打开显示原始文件名的图像?

2024-04-26 10:06:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个图表功能,可以将最终图形保存为文件。运行该函数后,我还希望它在末尾显示图形。所以,我用这个:

from PIL import Image

filepath = 'image.png'
img = Image.open(filepath)
img.show()

它工作正常,但是当文件打开时,它会以随机文件名打开,而不是实际的文件名

random file name

这可能会很麻烦,因为我有很多不同的图表函数,它们以类似的方式工作,所以有逻辑名称是一个加号

有没有一种方法可以用Python打开一个图像文件并让它显示它的原始文件名

编辑

顺便说一句,我正在使用Windows

EDIT2

使用显示相同行为的代码更新了示例


Tags: 文件函数fromimageimport功能图形img
2条回答

函数img.show()打开一个Windows实用程序来显示图像。图像在显示之前首先写入临时文件。以下是PIL文档中的部分。 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. "

问题是,PIL使用了一种快速而肮脏的方法来显示图像,它不适合于严肃的应用程序使用

您可以使用以下命令来代替PIL

import os
filepath = "path"
os.startfile(filepath)

使用此方法将使用系统编辑器打开文件

或与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()

相关问题 更多 >