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

Mar*_*oma 15 python python-imaging-library

我有几个图像,我想用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
Run Code Online (Sandbox Code Playgroud)

它正在工作,但用户必须自己关闭图像.在输入描述后,我可以让python关闭图像吗?

我不需要PIL.如果你对另一个库/ bash程序(使用子进程)有另一个想法,那也没关系.

Ben*_*ngt 15

psutil可以获取displayim.show()每个操作系统上的pid 创建的进程的pid并终止进程:

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()
Run Code Online (Sandbox Code Playgroud)

  • 这似乎不适用于mac osx (6认同)
  • @GyörgySolymosi @IDelgadoYes,在较新版本的 psutil 中,`proc.name` 是一种方法而不是字符串属性。如果检查 name 属性,则脚本退出无效,因为它们看起来像这样:`<bound method Process.name of <psutil.Process(pid=14358,name='display') at 19774288>>` 谢谢为了指出这一点,我更新了我的答案。希望将来没有人会因此而绊倒。 (2认同)

Fre*_*Foo 13

show方法"主要用于调试目的",并产生一个您无法获得句柄的外部进程,因此您无法以正确的方式终止它.

使用PIL,您可能希望使用其GUI模块之一,例如ImageTk,ImageQtImageWin.

否则,只需使用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
Run Code Online (Sandbox Code Playgroud)

  • 我如何在OSX上将预览用作“ some_viewer”? (2认同)

Nic*_*k T 5

我之前修改过这个食谱,用 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
Run Code Online (Sandbox Code Playgroud)