如何用Python Imaging Library关闭显示给用户的图像?

19 投票
4 回答
40789 浏览
提问于 2025-04-16 21:43

我有几张图片想用Python展示给用户。用户需要输入一些描述,然后下一张图片就会显示出来。

这是我的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, glob
from PIL import Image

path = '/home/moose/my/path/'
for infile in glob.glob( os.path.join(path, '*.png') ):
    im = Image.open(infile)
    im.show()
    value = raw_input("Description: ")
    # store and do some other stuff. Now the image-window should get closed

这个代码是能工作的,但用户需要自己关闭图片。我能不能让Python在用户输入描述后自动关闭图片呢?

我不需要用PIL库。如果你有其他库或者用bash程序(通过subprocess)的方法也可以。

4 个回答

6

我之前修改过这个例子,用来在Python中处理一些图片。它使用了Tkinter,所以除了PIL这个模块之外,不需要其他的模块。

'''This will simply go through each file in the current directory and
try to display it. If the file is not an image then it will be skipped.
Click on the image display window to go to the next image.

Noah Spurrier 2007'''
import os, sys
import Tkinter
import Image, ImageTk

def button_click_exit_mainloop (event):
    event.widget.quit() # this will cause mainloop to unblock.

root = Tkinter.Tk()
root.bind("<Button>", button_click_exit_mainloop)
root.geometry('+%d+%d' % (100,100))
dirlist = os.listdir('.')
old_label_image = None
for f in dirlist:
    try:
        image1 = Image.open(f)
        root.geometry('%dx%d' % (image1.size[0],image1.size[1]))
        tkpi = ImageTk.PhotoImage(image1)
        label_image = Tkinter.Label(root, image=tkpi)
        label_image.place(x=0,y=0,width=image1.size[0],height=image1.size[1])
        root.title(f)
        if old_label_image is not None:
            old_label_image.destroy()
        old_label_image = label_image
        root.mainloop() # wait until user clicks the window
    except Exception, e:
        # This is used to skip anything not an image.
        # Warning, this will hide other errors as well.
        pass
18

psutil 是一个可以获取由 im.show() 创建的 display 进程的进程ID(pid),并且可以在所有操作系统上用这个进程ID来结束这个进程的工具。

import time

import psutil
from PIL import Image

# open and show image
im = Image.open('myImageFile.jpg')
im.show()

# display image for 10 seconds
time.sleep(10)

# hide image
for proc in psutil.process_iter():
    if proc.name() == "display":
        proc.kill()
15

show 方法“主要是为了调试目的”,它会启动一个外部进程,而你无法获得这个进程的控制权,所以你不能以正确的方式结束它。

如果你使用PIL(Python图像库),你可能想用它的一些图形用户界面模块,比如 ImageTkImageQt 或者 ImageWin

否则,你可以用 subprocess 模块手动从Python启动一个图像查看器:

for infile in glob.glob( os.path.join(path, '*.png')):
    viewer = subprocess.Popen(['some_viewer', infile])
    viewer.terminate()
    viewer.kill()  # make sure the viewer is gone; not needed on Windows

撰写回答