Skip to content

Instantly share code, notes, and snippets.

Last active May 31, 2022
What would you like to do?
Tweaking a PySimpleGUI Image viewer example
# For use with /home/villares/GitHub/sketch-a-day/2022/sketch_2022_05_29
import PySimpleGUI as sg
# import PySimpleGUIQt as sg
import os.path
import PIL.Image
import io
Based on: Demo for displaying any format of image file.
Copyright 2020
def image_as_png_bytes(file_path, resize=None):
Open an image file and convert it into PNG formated bytes, resize optional.
Return tuple (bytes, <dict from>)
img =
cur_width, cur_height = img.size
if resize:
new_width, new_height = resize
scale = min(new_height/cur_height, new_width/cur_width)
img = img.resize((int(cur_width*scale), int(cur_height*scale)),
with io.BytesIO() as bio:, format="PNG")
return bio.getvalue(),
# --------------------------------- Define Layout ---------------------------------
# First the window layout...
left_col = [
[sg.Text('Folder'), sg.In(size=(25,1), enable_events=True ,key='-FOLDER-'),
sg.FolderBrowse()], # PSG will put FolderBrowser() result into "In" field!
[sg.Listbox(values=[], enable_events=True, size=(40,20), key='-FILE LIST-')],
[sg.Text('Resize to'),
sg.In(key='-W-', size=(5,1), default_text='500'), # I added the 500 default
sg.In(key='-H-', size=(5,1), default_text='500')]
images_col = [
[sg.Text('Loaded from the list:')],
[sg.Text(size=(40,1), key='-TOUT-')],
[sg.Image(key='-IMAGE-')] # Produces a "no data" warning at first
third_col = [
[sg.Multiline(key='-CODE-', size=(50, 20), disabled=True)],
[sg.Multiline(key='-OTHER-', size=(50, 20), disabled=True)]
# ----- Full layout -----
layout = [
[sg.Column(left_col, element_justification='c'),
sg.Column(images_col, element_justification='c'),
sg.Column(third_col, element_justification='c')]
# --------------------------------- Create Window ---------------------------------
window = sg.Window('Multiple Format Image Viewer', layout,resizable=True)
while True: # run the event loop
event, values =
if event in (sg.WIN_CLOSED, 'Exit'):
if event == '-FOLDER-': # Folder name was filled in, make a list of files in the folder
folder = values['-FOLDER-']
file_list = os.listdir(folder) # get list of files in folder
file_list = []
fnames = [f for f in file_list if os.path.isfile(os.path.join(folder, f))
and f.lower().endswith((".png", ".jpg", "jpeg", ".tiff", ".bmp"))]
window['-FILE LIST-'].update(fnames)
elif event == '-FILE LIST-' and values['-FILE LIST-']: # A file was chosen
filename = os.path.join(values['-FOLDER-'], values['-FILE LIST-'][0])
if values['-W-'] and values['-H-']:
new_size = int(values['-W-']), int(values['-H-'])
new_size = None
png_bytes, metadata = image_as_png_bytes(filename, resize=new_size)
window['-CODE-'].update(metadata.pop('code', ''))
window['-OTHER-'].update('\n'.join(f'{k}: {v}' for k, v in metadata.items()))
except Exception as e:
print(f'** Error {e} **') # failed loading the file or updating the image
window.close() # Close & Exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment