100% found this document useful (3 votes)
443 views17 pages

PySimpleGUI Basic Window Examples

This document contains code snippets demonstrating various GUI features in PySimpleGUI, including: - Returning values from a window as a list or dictionary - Getting a filename from the user - Creating a window with many different elements like menus, text, buttons, sliders etc. - Creating a non-blocking form using async functions - Adding button images - Creating a script launcher to run programs from a GUI - Building a custom progress meter The snippets show how to build basic to more complex GUIs and retrieve input from the user in PySimpleGUI.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
443 views17 pages

PySimpleGUI Basic Window Examples

This document contains code snippets demonstrating various GUI features in PySimpleGUI, including: - Returning values from a window as a list or dictionary - Getting a filename from the user - Creating a window with many different elements like menus, text, buttons, sliders etc. - Creating a non-blocking form using async functions - Adding button images - Creating a script launcher to run programs from a GUI - Building a custom progress meter The snippets show how to build basic to more complex GUIs and retrieve input from the user in PySimpleGUI.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Recipe and Window Output
  • Front-End File Handling
  • All Graphical Widgets
  • Non-Blocking Form (Async)
  • Media File Player
  • Script Launcher
  • Custom Progress Meter and Multiple Columns
  • Updating and Canvas Elements
  • Graph Element and Input
  • Keypad and Animated Matplotlib Graph
  • Floating Widgets and Timers
  • CPU Widget and Menus
  • Sine Graph

Recipe Window Produced

Result as List
import PySimpleGUI as sg

# Very basic window. Return values as a list

layout = [
[[Link]('Please enter your Name, Address, Phone')],
[[Link]('Name', size=(15, 1)), [Link]()],
[[Link]('Address', size=(15, 1)), [Link]()],
[[Link]('Phone', size=(15, 1)), [Link]()],
[[Link](), [Link]()]
]

window = [Link]('Simple data entry window').Layout(layout)


button, values = [Link]()

Result as Dictionary
import PySimpleGUI as sg

# Very basic window. Return values as a dictionary

layout = [
[[Link]('Please enter your Name, Address, Phone')],
[[Link]('Name', size=(15, 1)), [Link]('name',
key='name')],
[[Link]('Address', size=(15, 1)), [Link]('address',
key='address')],
[[Link]('Phone', size=(15, 1)), [Link]('phone',
key='phone')],
[[Link](), [Link]()]
]

window = [Link]('Simple data entry GUI').Layout(layout)

button, values = [Link]()

print(button, values['name'], values['address'], values['phone'])

Single-Line Front-End Get Filename


import PySimpleGUI as sg

button, (filename,) = [Link]('Get filename example').Layout(


[[[Link]('Filename')], [[Link](), [Link]()], [[Link](),
[Link]()]]).Read()

Front-End Get Filename


import PySimpleGUI as sg

layout = [
[[Link]('SHA-1 and SHA-256 Hashes for the file')],
[[Link](), [Link]()],
[[Link](), [Link]()]
]

(button, (source_filename,)) = [Link]('SHA-1 & 256


Hash').Layout(layout).Read()

print(button, source_filename)

Browse for Filename


import PySimpleGUI as sg

gui_rows = [
[[Link]('Enter 2 files to comare')],
[[Link]('File 1', size=(8, 1)), [Link](),
[Link]()],
[[Link]('File 2', size=(8, 1)), [Link](),
[Link]()],
[[Link](), [Link]()]
]

window = [Link]('File Compare').Layout(gui_rows)

button, values = [Link]()

print(button, values)

Many Elements on One Window


import PySimpleGUI as sg

[Link]('GreenTan')

# ------ Menu Definition ------ #


menu_def = [
['File', ['Open', 'Save', 'Exit', 'Properties']],
['Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ],
['Help', 'About...']
]

# ------ Column Definition ------ #


column1 = [
[[Link]('Column 1', background_color='#F7F3EC',
justification='center', size=(10, 1))],
[[Link](values=('Spin Box 1', '2', '3'), initial_value='Spin Box
1')],
[[Link](values=('Spin Box 1', '2', '3'), initial_value='Spin Box
2')],
[[Link](values=('Spin Box 1', '2', '3'), initial_value='Spin Box
3')]
]

layout = [
[[Link](menu_def, tearoff=True)],
[[Link]('All graphic widgets in one window!', size=(30, 1),
justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE)],
[[Link]('Here is some text.... and a place to enter text')],
[[Link]('This is my text')],
[[Link](layout=[
[[Link]('Checkbox', size=(10 ,1)), [Link]('My second
checkbox!', default=True)],
[[Link]('My first Radio! ', "RADIO1", default=True, size=(10
,1)), [Link]('My second Radio!', "RADIO1")]], title='Options'
,title_color='red', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set
flags')],
[[Link](default_text='This is the default Text should you decide
not to type anything', size=(35, 3)),
[Link](default_text='A second multi-line', size=(35, 3))],
[[Link](('Combobox 1', 'Combobox 2'), size=(20, 1)),
[Link](range=(1, 100), orientation='h', size=(34, 20),
default_value=85)],
[[Link](('Menu Option 1', 'Menu Option 2', 'Menu Option
3'))],
[[Link](values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30,
3)),
[Link]('Labelled Group' ,[[
[Link](range=(1, 100), orientation='v', size=(5, 20),
default_value=25),
[Link](range=(1, 100), orientation='v', size=(5, 20),
default_value=75),
[Link](range=(1, 100), orientation='v', size=(5, 20),
default_value=10),
[Link](column1, background_color='#F7F3EC')]])],
[[Link]('_' * 80)],
[[Link]('Choose A Folder', size=(35, 1))],
[[Link]('Your Folder', size=(15, 1), auto_size_text=False,
justification='right'),
[Link]('Default Folder'), [Link]()],
[[Link](tooltip='Click to submit this window'), [Link]()]
]

window = [Link]('Everything bagel', default_element_size=(40, 1),


grab_anywhere=False).Layout(layout)

button, values = [Link]()

[Link]('Title',
'The results of the window.',
'The button clicked was "{}"'.format(button),
'The values are', values)

Non-Blocking Form (Async)


import PySimpleGUI as sg
import time

gui_rows = [[[Link]('Stopwatch', size=(20, 2), justification='center')],


[[Link]('', size=(10, 2), font=('Helvetica', 20),
justification='center', key='output')],
[sg.T(' ' * 5), [Link]('Start/Stop', focus=True),
[Link]()]]

window = [Link]('Running Timer').Layout(gui_rows)

timer_running = True
i = 0
while True: # Event Loop
i += 1 * (timer_running is True)
button, values = [Link]()

if values is None or button == 'Quit': # if user closed the window using


X or clicked Quit button
break
elif button == 'Start/Stop':
timer_running = not timer_running

[Link]('output').Update('{:02d}:{:02d}.{:02d}'.format((i //
100) // 60, (i // 100) % 60, i % 100))
[Link](.01)
Using Button Images
import PySimpleGUI as sg

background = '#F0F0F0'
# Set the backgrounds the same as the background on the buttons
[Link](background_color=background,
element_background_color=background)
# Images are located in a subfolder in the Demo Media [Link] folder
image_pause = './ButtonGraphics/[Link]'
image_restart = './ButtonGraphics/[Link]'
image_next = './ButtonGraphics/[Link]'
image_exit = './ButtonGraphics/[Link]'

# define layout of the rows


layout = [[[Link]('Media File Player', size=(17, 1), font=("Helvetica",
25))],
[[Link]('', size=(15, 2), font=("Helvetica", 14), key='output')],
[[Link]('Restart Song', button_color=(background,
background),
image_filename=image_restart, image_size=(50, 50),
image_subsample=2, border_width=0),
[Link](' ' * 2),
[Link]('Pause', button_color=(background, background),
image_filename=image_pause, image_size=(50, 50),
image_subsample=2, border_width=0),
[Link](' ' * 2),
[Link]('Next', button_color=(background, background),
image_filename=image_next, image_size=(50, 50),
image_subsample=2, border_width=0),
[Link](' ' * 2),
[Link](' ' * 2), [Link]('Exit', button_color=(background,
background),
image_filename=image_exit,
image_size=(50, 50), image_subsample=2,
border_width=0)],
[[Link]('_' * 30)],
[[Link](' ' * 30)],
[
[Link](range=(-10, 10), default_value=0, size=(10, 20),
orientation='vertical',
font=("Helvetica", 15)),
[Link](' ' * 2),
[Link](range=(-10, 10), default_value=0, size=(10, 20),
orientation='vertical',
font=("Helvetica", 15)),
[Link](' ' * 8),
[Link](range=(-10, 10), default_value=0, size=(10, 20),
orientation='vertical',
font=("Helvetica", 15))],
[[Link]('Bass', font=("Helvetica", 15), size=(6, 1)),
[Link]('Treble', font=("Helvetica", 15), size=(10, 1)),
[Link]('Volume', font=("Helvetica", 15), size=(7, 1))]
]

window = [Link]('Media File Player', auto_size_text=True,


default_element_size=(20, 1),
font=("Helvetica", 25)).Layout(layout)
# Our event loop
while (True):
# Read the window (this call will not block)
button, values = [Link]()
if button == 'Exit' or values is None:
break
# If a button was pressed, display it on the GUI by updating the text
element
if button:
[Link]('output').Update(button)

Script Launcher
import PySimpleGUI as sg
import subprocess

# Please check Demo programs for better examples of launchers


def ExecuteCommandSubprocess(command, *args):
try:
sp = [Link]([command, *args], shell=True,
stdout=[Link], stderr=[Link])
out, err = [Link]()
if out:
print([Link]("utf-8"))
if err:
print([Link]("utf-8"))
except:
pass

layout = [
[[Link]('Script output....', size=(40, 1))],
[[Link](size=(88, 20), font='Courier 10')],
[[Link]('script1'), [Link]('script2'), [Link]('EXIT')],
[[Link]('Manual command', size=(15, 1)), [Link](focus=True),
[Link]('Run', bind_return_key=True)]
]

window = [Link]('Script launcher').Layout(layout)

# ---===--- Loop taking in user input and using it to call scripts --- #
while True:
(button, value) = [Link]()
if button == 'EXIT' or button is None:
break # exit button clicked
if button == 'script1':
ExecuteCommandSubprocess('pip', 'list')
elif button == 'script2':
ExecuteCommandSubprocess('python', '--version')
elif button == 'Run':
ExecuteCommandSubprocess(value[0])

Custom Progress Meter


import PySimpleGUI as sg

# layout the Window


layout = [[[Link]('A custom progress meter')],
[[Link](10000, orientation='h', size=(20, 20),
key='progbar')],
[[Link]()]]

# create the Window


window = [Link]('Custom Progress Meter').Layout(layout)
# loop that would normally do something useful
for i in range(10000):
# check to see if the cancel button was clicked and exit loop if clicked
button, values = [Link]()
if button == 'Cancel' or values == None:
break
# update bar with loop value +1 so that bar eventually reaches the maximum
[Link]('progbar').UpdateBar(i + 1)
# done with loop... need to destroy the window as it's still open
[Link]()

Multiple Columns
import PySimpleGUI as sg

# Demo of how columns work


# GUI has on row 1 a vertical slider followed by a COLUMN with 7 rows
# Prior to the Column element, this layout was not possible
# Columns layouts look identical to GUI layouts, they are a list of lists of
elements.

[Link]('BlueMono')

# Column layout
col = [[[Link]('col Row 1', text_color='white', background_color='blue')],
[[Link]('col Row 2', text_color='white', background_color='blue'),
[Link]('col input 1')],
[[Link]('col Row 3', text_color='white', background_color='blue'),
[Link]('col input 2')]]

layout = [[[Link](values=('Listbox Item 1', 'Listbox Item 2', 'Listbox


Item 3'), select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, size=(20,3)),
[Link](col, background_color='blue')],
[[Link]('Last input')],
[[Link]()]]

# Display the Window and get values

button, values = [Link]('Compact 1-line Window with


column').Layout(layout).Read()

[Link](button, values, line_width=200)

Updating Elements (Text Element)


import PySimpleGUI as sg

layout = [ [[Link]('Enter values to calculate')],


[[Link](size=(8,1), key='numerator')],
[[Link]('_' * 10)],
[[Link](size=(8,1), key='denominator')],
[[Link]('', size=(8,1), key='output') ],
[[Link]('Calculate', bind_return_key=True)]]

window = [Link]('Math').Layout(layout)

while True:
button, values = [Link]()

if button is not None:


try:
numerator = float(values['numerator'])
denominator = float(values['denominator'])
calc = numerator / denominator
except:
calc = 'Invalid'

[Link]('output').Update(calc)
else:
break

Canvas Element
import PySimpleGUI as sg

layout = [
[[Link](size=(100, 100), background_color='red', key= 'canvas')],
[sg.T('Change circle color to:'), [Link]('Red'),
[Link]('Blue')]
]

window = [Link]('Canvas test')


[Link](layout)
[Link]()

canvas = [Link]('canvas')
cir = [Link].create_oval(50, 50, 100, 100)

while True:
button, values = [Link]()
if button is None:
break
if button == 'Blue':
[Link](cir, fill="Blue")
elif button == 'Red':
[Link](cir, fill="Red")

Graph Element
import PySimpleGUI as sg

layout = [
[[Link](canvas_size=(400, 400), graph_bottom_left=(0,0),
graph_top_right=(400, 400), background_color='red', key='graph')],
[sg.T('Change circle color to:'), [Link]('Red'),
[Link]('Blue'), [Link]('Move')]
]

window = [Link]('Graph test')


[Link](layout)
[Link]()

graph = [Link]('graph')
circle = [Link]((75,75), 25, fill_color='black',line_color='white')
point = [Link]((75,75), 10, color='green')
oval = [Link]((25,300), (100,280), fill_color='purple',
line_color='purple' )
rectangle = [Link]((25,300), (100,280), line_color='purple' )
line = [Link]((0,0), (100,100))

while True:
button, values = [Link]()
if button is None:
break
if button is 'Blue':
[Link](circle, fill = "Blue")
elif button is 'Red':
[Link](circle, fill = "Red")
elif button is 'Move':
[Link](point, 10,10)
[Link](circle, 10,10)
[Link](oval, 10,10)
[Link](rectangle, 10,10)

Keypad – Inserting Into Input


Element
import PySimpleGUI as sg

# Demonstrates a number of PySimpleGUI features including:


# Default element size
# auto_size_buttons
# ReadButton
# Dictionary return values
# Update of elements in window (Text, Input)
# do_not_clear of Input elements

layout = [[[Link]('Enter Your Passcode')],


[[Link](size=(10, 1), do_not_clear=True, justification='right',
key='input')],
[[Link]('1'), [Link]('2'), [Link]('3')],
[[Link]('4'), [Link]('5'), [Link]('6')],
[[Link]('7'), [Link]('8'), [Link]('9')],
[[Link]('Submit'), [Link]('0'),
[Link]('Clear')],
[[Link]('', size=(15, 1), font=('Helvetica', 18),
text_color='red', key='out')],
]

window = [Link]('Keypad', default_button_element_size=(5, 2),


auto_size_buttons=False, grab_anywhere=False).Layout(layout)

# Loop forever reading the window's values, updating the Input field
keys_entered = ''
while True:
button, values = [Link]() # read the window
if button is None: # if the X button clicked, just exit
break
if button == 'Clear': # clear keys if clear button
keys_entered = ''
elif button in '1234567890':
keys_entered = values['input'] # get what's been entered so far
keys_entered += button # add the new digit
elif button == 'Submit':
keys_entered = values['input']
[Link]('out').Update(keys_entered) # output the final
string

[Link]('input').Update(keys_entered) # change the window to


reflect current key string

Animated Matplotlib Graph


from random import randint
import PySimpleGUI as g
from [Link].backend_tkagg import FigureCanvasTkAgg,
FigureCanvasAgg
from [Link] import Figure
import [Link] as tkagg
import tkinter as Tk

fig = Figure()

ax = fig.add_subplot(111)
ax.set_xlabel("X axis")
ax.set_ylabel("Y axis")
[Link]()

layout = [[[Link]('Animated Matplotlib', size=(40, 1),


justification='center', font='Helvetica 20')],
[[Link](size=(640, 480), key='canvas')],
[[Link]('Exit', size=(10, 2), pad=((280, 0), 3),
font='Helvetica 14')]]

# create the window and show it without the plot

window = [Link]('Demo Application - Embedding Matplotlib In


PySimpleGUI').Layout(layout)
[Link]() # needed to access the canvas element prior to reading
the window

canvas_elem = [Link]('canvas')

graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas)


canvas = canvas_elem.TKCanvas

dpts = [randint(0, 10) for x in range(10000)]


# Our event loop
for i in range(len(dpts)):
button, values = [Link]()
if button == 'Exit' or values is None:
break

[Link]()
[Link]()

[Link](range(20), dpts[i:i + 20], color='purple')


[Link]()
figure_x, figure_y, figure_w, figure_h = [Link]
figure_w, figure_h = int(figure_w), int(figure_h)
photo = [Link](master=canvas, width=figure_w, height=figure_h)
canvas.create_image(640 / 2, 480 / 2, image=photo)

figure_canvas_agg = FigureCanvasAgg(fig)
figure_canvas_agg.draw()

[Link](photo, figure_canvas_agg.get_renderer()._renderer,
colormode=2)

Floating Widget with No Border -


Timer
import PySimpleGUI as sg
import time

"""
Timer Desktop Widget Creates a floating timer that is always on top of other
windows You move it by grabbing anywhere on the window Good example of how to
do a non-blocking, polling program using PySimpleGUI Can be used to poll
hardware when running on a Pi NOTE - you will get a warning message
printed when you exit using exit button. It will look something like: invalid
command name \"1616802625480StopMove\"
"""

# ---------------- Create window ----------------


[Link]('Black')
[Link](element_padding=(0, 0))

layout = [[[Link]('')],
[[Link]('', size=(8, 2), font=('Helvetica', 20),
justification='center', key='text')],
[[Link]('Pause', key='button', button_color=('white',
'#001480')),
[Link]('Reset', button_color=('white', '#007339'),
key='Reset'),
[Link](button_color=('white', 'firebrick4'), key='Exit')]]

window = [Link]('Running Timer', no_titlebar=True,


auto_size_buttons=False, keep_on_top=True, grab_anywhere=True).Layout(layout)

# ---------------- main loop ----------------


current_time = 0
paused = False
start_time = int(round([Link]() * 100))
while (True):
# --------- Read and update window --------
if not paused:
button, values = [Link]()
current_time = int(round([Link]() * 100)) - start_time
else:
button, values = [Link]()
if button == 'button':
button = [Link](button).GetText()
# --------- Do Button Operations --------
if values is None or button == 'Exit':
break
if button is 'Reset':
start_time = int(round([Link]() * 100))
current_time = 0
paused_time = start_time
elif button == 'Pause':
paused = True
paused_time = int(round([Link]() * 100))
element = [Link]('button')
[Link](text='Run')
elif button == 'Run':
paused = False
start_time = start_time + int(round([Link]() * 100)) - paused_time
element = [Link]('button')
[Link](text='Pause')

# --------- Display timer in window --------

[Link]('text').Update('{:02d}:{:02d}.{:02d}'.format((current_time
// 100) // 60,

(current_time // 100) % 60,

current_time % 100))
[Link](.01)

# --------- After loop --------

# Broke out of main loop. Close the window.


[Link]()

CPU Widget Using psutil


import PySimpleGUI as sg
import psutil

# ---------------- Create Window ----------------


[Link]('Black')
layout = [[[Link]('')],
[[Link]('', size=(8, 2), font=('Helvetica', 20),
justification='center', key='text')],
[[Link](button_color=('white', 'firebrick4'), pad=((15,0), 0)),
[Link]([x+1 for x in range(10)], 1, key='spin')]]

window = [Link]('Running Timer', no_titlebar=True,


auto_size_buttons=False, keep_on_top=True, grab_anywhere=True).Layout(layout)

# ---------------- main loop ----------------


while (True):
# --------- Read and update window --------
button, values = [Link]()

# --------- Do Button Operations --------


if values is None or button == 'Exit':
break
try:
interval = int(values['spin'])
except:
interval = 1

cpu_percent = psutil.cpu_percent(interval=interval)

# --------- Display timer in window --------

[Link]('text').Update(f'CPU {cpu_percent:02.0f}%')

# Broke out of main loop. Close the window.


[Link]()

Menus in 25 Lines of Code!


import PySimpleGUI as sg

[Link]('LightGreen')
[Link](element_padding=(0, 0))

# ------ Menu Definition ------ #


menu_def = [['File', ['Open', 'Save', 'Exit' ]],
['Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ],
['Help', 'About...'], ]

# ------ GUI Defintion ------ #


layout = [
[[Link](menu_def)],
[[Link](size=(60, 20))]
]

window = [Link]("Windows-like program", default_element_size=(12, 1),


auto_size_text=False, auto_size_buttons=False,
default_button_element_size=(12, 1)).Layout(layout)

# ------ Loop & Process button menu choices ------ #


while True:
button, values = [Link]()
if button == None or button == 'Exit':
break
print('Button = ', button)
# ------ Process menu choices ------ #
if button == 'About...':
[Link]('About this program', 'Version 1.0', 'PySimpleGUI rocks...')
elif button == 'Open':
filename = [Link]('file to open', no_window=True)
print(filename)

Graph Element
import math
import PySimpleGUI as sg

layout = [[[Link](canvas_size=(400, 400), graph_bottom_left=(-100,-100),


graph_top_right=(100,100), background_color='white', key='graph')],]

window = [Link]('Graph of Sine Function').Layout(layout)


[Link]()
graph = [Link]('graph')

[Link]((-100,0), (100,0))
[Link]((0,-100), (0,100))

for x in range(-100,100):
y = [Link](x/20)*50
[Link]((x,y), color='red')

button, values = [Link]()

Recipe 
 
Window Produced 
Result as List 
 
import PySimpleGUI as sg 
 
# Very basic window.  Return values as a list
import PySimpleGUI as sg 
 
button, (filename,) = sg.Window('Get filename example').Layout( 
    [[sg.Text('Filename')],
import PySimpleGUI as sg 
 
sg.ChangeLookAndFeel('GreenTan') 
 
# ------ Menu Definition ------ # 
menu_def =  [
sg.Slider(range=(1, 100), orientation='v', size=(5, 20), 
default_value=10), 
         sg.Column(column1, background
Using Button Images 
 
import PySimpleGUI as sg 
 
background = '#F0F0F0' 
# Set the backgrounds the same as the background o
sg.Text('Treble', font=("Helvetica", 15), size=(10, 1)), 
           sg.Text('Volume', font=("Helvetica", 15), siz
while True: 
  (button, value) = window.Read() 
  if button == 'EXIT'  or button is None: 
      break # exit button clicked
sg.Input('col input 1')], 
       [sg.Text('col Row 3', text_color='white', background_color='blue'), 
sg.Input('col input 2'
import PySimpleGUI as sg 
 
layout = [ 
    [sg.Canvas(size=(100, 100), background_color='red', key= 'canvas')], 
    [sg.T('
import PySimpleGUI as sg 
 
layout = [ 
           [sg.Graph(canvas_size=(400, 400), graph_bottom_left=(0,0), 
graph_top_righ

You might also like