pythonpython-3.xinsert-image

How to display an image as result of true in a function


So I'm playing around with some code and I'm trying to design a program that displays an image if a true statement results from the input. An example would be as follows:

name = input('name: ')
if name == 'Sammi':
   # Here is where I would put the command to open an image. In place of print or whatever.
   # I need some help with exactly what function to put here though.

The idea is that if the input string matches 'Sammi', then an image of me will be displayed preferably in a separate window, but I'm not exactly sure if that's possible or practical.

I've seen some guides that use PIL but the process of downloading and installing the required software is really tedious and I just have to wonder if it is actually required. I primarily use PyCharm for my code and occasionally ill go over to Notepad++ but it's mostly PyCharm. I'm not sure if that information is helpful but I thought I would provide it.

The image I want to use is located on my desktop and ideally would use the path C:\users\sammi\OneDrive\Desktop\B&W_2.jpg

My question as stated before is: exactly what function will allow me to do this? When you answer I would also really appreciate it if you explain the purpose of certain operators like fromand or for example, or whatever other operators or functions are used. I'm still fairly new to this stuff but I want to get really good at it.


Solution

  • Short reply, if you are running Python from the Standard Library, you can't, directly. The Standard Library is mostly a back-end library, so it works with logic, but doesn't "show" anything. This means that there's no way with the Standard Library to show images, you can however launch a process which opens the images.

    E.g. Microsoft Paint

    import subprocess
    def open_image(path:str) -> None:
        command = f'mspaint {path}'
        subprocess.Popen(command)
    
    open_image(input('Type your path: '))
    

    If you don't want paint or another application, you should find a library that does it, be it Pillow or others.