Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I close an image shown to the user with the Python Imaging Library?

I have several images which I would like to show the user with Python. The user should enter some description and then the next image should be shown.

This is my code:

#!/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

It is working, but the user has to close the image himself. Could I get python to close the image after the description has been entered?

I don't need PIL. If you have another idea with another library / bash-program (with subprocess), it'll be also fine.

like image 434
Martin Thoma Avatar asked Jul 17 '11 16:07

Martin Thoma


People also ask

How do I close an image?

You can also use the keyboard shortcut, Ctrl+W (Win) / Command+W (Mac): To close a single image, go to File > Close. Another way to close a single image is by clicking the small "x" icon in the document's tab.

How do I display an image in Python?

Python – Display Image using PIL To show or display an image in Python Pillow, you can use show() method on an image object. The show() method writes the image to a temporary file and then triggers the default program to display that image. Once the program execution is completed, the temporary file will be deleted.


1 Answers

psutil can get the pid of the display process created by im.show() and kill the process with that pid on every operating system:

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()
like image 141
Bengt Avatar answered Sep 19 '22 08:09

Bengt