This answer did not work for me, nor for some Mac users, and I did not find a working solution among the following similar questions:
- How to open an image in Python and close afterwards?
- How to Close an Image?
- How can I close an image shown to the user with the Python Imaging Library?
- How do I close figure in matplotlib?
- How can I close an image shown to the user with the Python Imaging Library?
- How to use user input to display image?
How can one open an image in Python, then let the user answer questions about it in the CLI, and close the image afterwards?
Contstaints
- Don't use sub-process.
- Don't start killing processes that happen to match a substring.
- In essence, use a Python-only method that opens an image and then closes that, and only that image, with control, whilst allowing other code (that allows user interaction) to be executed in between.
This answer did not work for me, nor for some Mac users, and I did not find a working solution among the following similar questions:
- How to open an image in Python and close afterwards?
- How to Close an Image?
- How can I close an image shown to the user with the Python Imaging Library?
- How do I close figure in matplotlib?
- How can I close an image shown to the user with the Python Imaging Library?
- How to use user input to display image?
How can one open an image in Python, then let the user answer questions about it in the CLI, and close the image afterwards?
Contstaints
- Don't use sub-process.
- Don't start killing processes that happen to match a substring.
- In essence, use a Python-only method that opens an image and then closes that, and only that image, with control, whilst allowing other code (that allows user interaction) to be executed in between.
1 Answer
Reset to default 1The answer below opens an image from a file path in a separate Window, then asks the questions in the CLI. After the questions are answered by the user, the image is closed.
Requirements
pip install tensorflow
pip install matplotlib
Solution
def make_receipt_label(img_filepath):
"""
Opens an image, asks the user questions about it, and returns the answers.
Args:
img_filepath: The path to the image file.
Returns:
A dictionary containing the user's answers to the questions.
Returns None if there is an issue opening the image.
"""
from tensorflow import io
from tensorflow import image as img
from matplotlib import pyplot as plt
tensor_img = io.read_file(img_filepath)
tensor_img = img.decode_png(tensor_img, channels=3)
plt.ion()
plt.imshow(tensor_img)
plt.show(block=False)
root=tk.Tk()
root.withdraw()
answers = {}
answers["image_colour"] = input("0. What is the image colour? ")
answers["total"] = input("1. Another question? ")
plt.close()
plt.ioff()
root.destroy()
return answers
Satisfied constraints
It does not use subproces
it does not try to kill processes with a pid
that matches some string, it uses pure Python.