Py Simple GUI
Py Simple GUI
Result as List
import PySimpleGUI as sg
layout = [
[sg.Text('Please enter your Name, Address, Phone')],
[sg.Text('Name', size=(15, 1)), sg.InputText()],
[sg.Text('Address', size=(15, 1)), sg.InputText()],
[sg.Text('Phone', size=(15, 1)), sg.InputText()],
[sg.Submit(), sg.Cancel()]
]
Result as Dictionary
import PySimpleGUI as sg
layout = [
[sg.Text('Please enter your Name, Address, Phone')],
[sg.Text('Name', size=(15, 1)), sg.InputText('name',
key='name')],
[sg.Text('Address', size=(15, 1)), sg.InputText('address',
key='address')],
[sg.Text('Phone', size=(15, 1)), sg.InputText('phone',
key='phone')],
[sg.Submit(), sg.Cancel()]
]
layout = [
[sg.Text('SHA-1 and SHA-256 Hashes for the file')],
[sg.InputText(), sg.FileBrowse()],
[sg.Submit(), sg.Cancel()]
]
print(button, source_filename)
gui_rows = [
[sg.Text('Enter 2 files to comare')],
[sg.Text('File 1', size=(8, 1)), sg.InputText(),
sg.FileBrowse()],
[sg.Text('File 2', size=(8, 1)), sg.InputText(),
sg.FileBrowse()],
[sg.Submit(), sg.Cancel()]
]
print(button, values)
sg.ChangeLookAndFeel('GreenTan')
layout = [
[sg.Menu(menu_def, tearoff=True)],
[sg.Text('All graphic widgets in one window!', size=(30, 1),
justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE)],
[sg.Text('Here is some text.... and a place to enter text')],
[sg.InputText('This is my text')],
[sg.Frame(layout=[
[sg.Checkbox('Checkbox', size=(10 ,1)), sg.Checkbox('My second
checkbox!', default=True)],
[sg.Radio('My first Radio! ', "RADIO1", default=True, size=(10
,1)), sg.Radio('My second Radio!', "RADIO1")]], title='Options'
,title_color='red', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set
flags')],
[sg.Multiline(default_text='This is the default Text should you decide
not to type anything', size=(35, 3)),
sg.Multiline(default_text='A second multi-line', size=(35, 3))],
[sg.InputCombo(('Combobox 1', 'Combobox 2'), size=(20, 1)),
sg.Slider(range=(1, 100), orientation='h', size=(34, 20),
default_value=85)],
[sg.InputOptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option
3'))],
[sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30,
3)),
sg.Frame('Labelled Group' ,[[
sg.Slider(range=(1, 100), orientation='v', size=(5, 20),
default_value=25),
sg.Slider(range=(1, 100), orientation='v', size=(5, 20),
default_value=75),
sg.Slider(range=(1, 100), orientation='v', size=(5, 20),
default_value=10),
sg.Column(column1, background_color='#F7F3EC')]])],
[sg.Text('_' * 80)],
[sg.Text('Choose A Folder', size=(35, 1))],
[sg.Text('Your Folder', size=(15, 1), auto_size_text=False,
justification='right'),
sg.InputText('Default Folder'), sg.FolderBrowse()],
[sg.Submit(tooltip='Click to submit this window'), sg.Cancel()]
]
sg.Popup('Title',
'The results of the window.',
'The button clicked was "{}"'.format(button),
'The values are', values)
timer_running = True
i = 0
while True: # Event Loop
i += 1 * (timer_running is True)
button, values = window.ReadNonBlocking()
window.FindElement('output').Update('{:02d}:{:02d}.{:02d}'.format((i //
100) // 60, (i // 100) % 60, i % 100))
time.sleep(.01)
Using Button Images
import PySimpleGUI as sg
background = '#F0F0F0'
# Set the backgrounds the same as the background on the buttons
sg.SetOptions(background_color=background,
element_background_color=background)
# Images are located in a subfolder in the Demo Media Player.py folder
image_pause = './ButtonGraphics/Pause.png'
image_restart = './ButtonGraphics/Restart.png'
image_next = './ButtonGraphics/Next.png'
image_exit = './ButtonGraphics/Exit.png'
Script Launcher
import PySimpleGUI as sg
import subprocess
layout = [
[sg.Text('Script output....', size=(40, 1))],
[sg.Output(size=(88, 20), font='Courier 10')],
[sg.ReadButton('script1'), sg.ReadButton('script2'), sg.Button('EXIT')],
[sg.Text('Manual command', size=(15, 1)), sg.InputText(focus=True),
sg.ReadButton('Run', bind_return_key=True)]
]
# ---===--- Loop taking in user input and using it to call scripts --- #
while True:
(button, value) = window.Read()
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])
Multiple Columns
import PySimpleGUI as sg
sg.ChangeLookAndFeel('BlueMono')
# Column layout
col = [[sg.Text('col Row 1', text_color='white', background_color='blue')],
[sg.Text('col Row 2', text_color='white', background_color='blue'),
sg.Input('col input 1')],
[sg.Text('col Row 3', text_color='white', background_color='blue'),
sg.Input('col input 2')]]
window = sg.Window('Math').Layout(layout)
while True:
button, values = window.Read()
window.FindElement('output').Update(calc)
else:
break
Canvas Element
import PySimpleGUI as sg
layout = [
[sg.Canvas(size=(100, 100), background_color='red', key= 'canvas')],
[sg.T('Change circle color to:'), sg.ReadButton('Red'),
sg.ReadButton('Blue')]
]
canvas = window.FindElement('canvas')
cir = canvas.TKCanvas.create_oval(50, 50, 100, 100)
while True:
button, values = window.Read()
if button is None:
break
if button == 'Blue':
canvas.TKCanvas.itemconfig(cir, fill="Blue")
elif button == 'Red':
canvas.TKCanvas.itemconfig(cir, fill="Red")
Graph Element
import PySimpleGUI as sg
layout = [
[sg.Graph(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:'), sg.ReadButton('Red'),
sg.ReadButton('Blue'), sg.ReadButton('Move')]
]
graph = window.FindElement('graph')
circle = graph.DrawCircle((75,75), 25, fill_color='black',line_color='white')
point = graph.DrawPoint((75,75), 10, color='green')
oval = graph.DrawOval((25,300), (100,280), fill_color='purple',
line_color='purple' )
rectangle = graph.DrawRectangle((25,300), (100,280), line_color='purple' )
line = graph.DrawLine((0,0), (100,100))
while True:
button, values = window.Read()
if button is None:
break
if button is 'Blue':
graph.TKCanvas.itemconfig(circle, fill = "Blue")
elif button is 'Red':
graph.TKCanvas.itemconfig(circle, fill = "Red")
elif button is 'Move':
graph.MoveFigure(point, 10,10)
graph.MoveFigure(circle, 10,10)
graph.MoveFigure(oval, 10,10)
graph.MoveFigure(rectangle, 10,10)
# Loop forever reading the window's values, updating the Input field
keys_entered = ''
while True:
button, values = window.Read() # 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']
window.FindElement('out').Update(keys_entered) # output the final
string
fig = Figure()
ax = fig.add_subplot(111)
ax.set_xlabel("X axis")
ax.set_ylabel("Y axis")
ax.grid()
canvas_elem = window.FindElement('canvas')
ax.cla()
ax.grid()
figure_canvas_agg = FigureCanvasAgg(fig)
figure_canvas_agg.draw()
tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer,
colormode=2)
"""
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\"
"""
layout = [[sg.Text('')],
[sg.Text('', size=(8, 2), font=('Helvetica', 20),
justification='center', key='text')],
[sg.ReadButton('Pause', key='button', button_color=('white',
'#001480')),
sg.ReadButton('Reset', button_color=('white', '#007339'),
key='Reset'),
sg.Exit(button_color=('white', 'firebrick4'), key='Exit')]]
window.FindElement('text').Update('{:02d}:{:02d}.{:02d}'.format((current_time
// 100) // 60,
current_time % 100))
time.sleep(.01)
cpu_percent = psutil.cpu_percent(interval=interval)
window.FindElement('text').Update(f'CPU {cpu_percent:02.0f}%')
sg.ChangeLookAndFeel('LightGreen')
sg.SetOptions(element_padding=(0, 0))
Graph Element
import math
import PySimpleGUI as sg
graph.DrawLine((-100,0), (100,0))
graph.DrawLine((0,-100), (0,100))
for x in range(-100,100):
y = math.sin(x/20)*50
graph.DrawPoint((x,y), color='red')