Python 图片显示

2 投票
4 回答
19216 浏览
提问于 2025-04-16 00:44

我该如何创建一个Python脚本,让它在Mac上浏览一个文件夹里的图片(1.jpeg到n.jpeg),并在浏览器中显示这些图片,或者通过另一个Python程序来显示呢?

我是不是先把文件导入到Python里,然后再在浏览器中显示?

我是不是要提取文件名1、2、3、4、5,然后把它们放到一个列表里,再把这个列表传给另一个函数,让它调用浏览器来显示?

任何帮助都非常感谢。

谢谢!

4 个回答

1

muksie的回答已经提供了非常有用的建议。如果你不想自己写HTML文件,或者想要一些更花哨的东西,你可以使用我为MDP库写的一个小脚本。这个脚本基本上让你只需要做以下操作:

import slideshow
slideshow.show_image_slideshow(filenames, image_size=(80,60))

这样就会创建一个HTML幻灯片,并在你的浏览器中打开。你可以在这里下载所需的文件(只需要templet.py和两个slideshow文件),这可能比下载整个库对你来说更合适。

4

首先,你需要找到所有的图片文件名。你可以用 os.listdir(...) 来获取某个文件夹里的所有文件,或者用 glob.glob(...) 来找到符合特定模式的所有文件。

展示这些图片是第二步,也是更具挑战性的部分。第一种方法是用外部程序打开图片,比如说用网页浏览器。在大多数平台上,你可以用命令 firefox 1.jpeg 来在Firefox浏览器中打开图片1.jpeg。你可以使用 subprocess 模块来执行这样的命令。如果你想用一个好看的图形界面来展示图片,你需要用某个框架创建一个图形界面并使用它。不过如果你是初学者,这可能会有点难。

例如:

import glob
import subprocess
files = glob.glob('dir/*.jpeg')
for file in files:
    subprocess.call(['firefox', file])
5

使用Tkinter和PIL来实现这个功能其实非常简单。可以把muskies的例子和这个帖子里的信息结合起来,这个帖子里有这个例子

# use a Tkinter label as a panel/frame with a background image
# note that Tkinter only reads gif and ppm images
# use the Python Image Library (PIL) for other image formats
# free from [url]http://www.pythonware.com/products/pil/index.htm[/url]
# give Tkinter a namespace to avoid conflicts with PIL
# (they both have a class named Image)

import Tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
root.title('background image')

# pick an image file you have .bmp  .jpg  .gif.  .png
# load the file and covert it to a Tkinter image object
imageFile = "Flowers.jpg"
image1 = ImageTk.PhotoImage(Image.open(imageFile))

# get the image size
w = image1.width()
h = image1.height()

# position coordinates of root 'upper left corner'
x = 0
y = 0

# make the root window the size of the image
root.geometry("%dx%d+%d+%d" % (w, h, x, y))

# root has no image argument, so use a label as a panel
panel1 = tk.Label(root, image=image1)
panel1.pack(side='top', fill='both', expand='yes')

# put a button on the image panel to test it
button2 = tk.Button(panel1, text='button2')
button2.pack(side='top')

# save the panel's image from 'garbage collection'
panel1.image = image1

# start the event loop
root.mainloop()

当然,如果你对其他图形界面更熟悉,也可以根据自己的需要调整这个例子,应该不会花太多时间。

撰写回答