Home > Software engineering >  PySimpleGUI can't display a .jpg, only a .png. How can I temporarily convert the .jpg to a .png
PySimpleGUI can't display a .jpg, only a .png. How can I temporarily convert the .jpg to a .png

Time:04-02

The code is very simple.

If I use this code (...{file_name}.jpg"), it gives me: "couldn't recognize data in image file ".\downloaded_cards\27551.jpg". Only if I use a .png version of the image and the code, then it works.

However, I don't want to change my actual files or duplicate them in my folder. Is there a way to do it temporarily when clicking "Show", without changing the original folder in anyway?

import PySimpleGUI as sg

layout = [
    [sg.Button("Show")],
    [sg.Image(key="myimg")],
]

window = sg.Window("Test", layout)

while True:
    event, values = window.read()
    if event == "Exit" or event == sg.WIN_CLOSED:
        break

    if event == "Show":
        file_name = "27551"
        file_image = f".\\downloaded_cards\\{file_name}.jpg"
        window["myimg"].update(file_image)

CodePudding user response:

You can use a package call Pillow (Install it via pip install pillow). It's a fork of PIL.

First, import pillow like this: from PIL import Image, ImageTk

Then, you can open an image file like this: img = Image.open('file_path_here')

Finally, you can make it like

window['myimg'].update(
    data=ImageTk.PhotoImage(img),
)

Full code:

import PySimpleGUI as sg
from PIL import Image, ImageTk #Image for open, ImageTk for display

layout = [
    [sg.Button("Show")],
    [sg.Image(key="myimg")],
]

window = sg.Window("Test", layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED: #There is no key call Exit so event == "Exit" is unimportant
        break

    if event == "Show":
        file_name = "27551"
        image = Image.open(f"./downloaded_cards/{file_name}.jpg") #I prefer /
        window["myimg"].update(
            data = ImageTk.PhotoImage(file_image)
        ) #update the myimg key
  • Related