Home>
  1. Specific folder (this timeDesktop \ new) Is stored in
    Randomly acquire image files with either JPG or PNG extension
  2. Resize the image to the proper size
  3. Display on screen

I'd like to realize that with PySimpleGUI, but I'm having trouble solving the following error.
We would appreciate it if you could lend us your help.

Supplement

Basically, most of them are JPG images, but I want to display images with both extensions.
Since tkinter has a limited display extension, it uses ImageTk from the Pillow library.

Exception occurred: TclError
couldn't recognize image data
Corresponding source code
#! python3.7
import glob
import random
import tkinter as tk
import PySimpleGUI as sg
from PIL import Image, ImageTk
dir_name = r'C: \ Users \ USER \ Desktop \ new'
img_types = (".jpg", ".png")
#Function that takes one image at random
def random_pick ():
    global dir_name
    global img_types
    while True:
        img_list = glob.glob (dir_name +'\\ *')
        pickfile = random.choice (img_list)
        if pickfile.lower (). endswith (img_types):
            return pickfile
# Find the magnification to resize the image
def set_magnification (iw, ih):
    rew = iw
    reh = ih
    n = 1
    while rew>600 and reh>600:
        rew = iw/n
        reh = ih/n
        n + = 0.5
    return n
def get_img_data (f):
    "" "Generate image data using PIL" ""
    print ("open file:", f)
    img = Image.open (f)
    magf = set_magnification (img.width, img.height)
    img_resize = img.resize ((int (img.width/magf), int (img.height/magf)))
    return ImageTk.PhotoImage (img_resize)

def main ():
    sg.ChangeLookAndFeel ('BlueMono')
    pfile = random_pick ()
    image_elem = sg.Image (data = get_img_data (pfile))
    filename_display_elem = sg.Text (pfile, size = (80, 3))
    layout = [[filename_display_elem], [image_elem], [sg.OK ()]]
    window = sg.Window ('display images', layout, return_keyboard_events = True,
                        location = (0, 0), use_default_focus = False)
#event loop
    while True:
        event, value = window.read () #
					
				
								
				
				
	
  • Answer # 1

    The actual error occurs in the following places.

    image_elem = sg.Image (data = get_img_data (pfile))

    The value taken by the argument data is the bytes type data.

    : param data: Raw or Base64 representation of the image to put on button. Choose either filename or data
    : type data: Union [bytes, str]

    In the get_img_data function

    return ImageTk.PhotoImage (img_resize)

    However, in the article of the reference URL, first = True, so
    Try to return the data in bytes.