Demo Cookbook both shows the code and executes it!
This commit is contained in:
parent
c1de1938c1
commit
7b26ccb809
195
Demo_Cookbook.py
195
Demo_Cookbook.py
|
@ -1,12 +1,12 @@
|
|||
|
||||
# import PySimpleGUI as sg
|
||||
import inspect
|
||||
|
||||
def SimpleDataEntry():
|
||||
"""Simple Data Entry - Return Values As List
|
||||
Same GUI screen except the return values are in a list instead of a dictionary and doesn't have initial values.
|
||||
"""
|
||||
|
||||
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
# Very basic form. Return values as a list
|
||||
form = sg.FlexForm('Simple data entry form') # begin with a blank form
|
||||
|
||||
|
@ -22,6 +22,7 @@ button, values = form.LayoutAndRead(layout)
|
|||
|
||||
print(button, values[0], values[1], values[2])
|
||||
|
||||
def SimpleReturnAsDict():
|
||||
"""
|
||||
Simple data entry - Return Values As Dictionary
|
||||
A simple form with default values. Results returned in a dictionary. Does not use a context manager
|
||||
|
@ -43,7 +44,7 @@ button, values = form.LayoutAndRead(layout)
|
|||
|
||||
print(button, values['name'], values['address'], values['phone'])
|
||||
|
||||
|
||||
def FileBrowse():
|
||||
"""
|
||||
Simple File Browse
|
||||
Browse for a filename that is populated into the input field.
|
||||
|
@ -58,7 +59,7 @@ with sg.FlexForm('SHA-1 & 256 Hash') as form:
|
|||
|
||||
print(button, source_filename)
|
||||
|
||||
|
||||
def GUIAddOn():
|
||||
"""
|
||||
Add GUI to Front-End of Script
|
||||
Quickly add a GUI allowing the user to browse for a filename if a filename is not supplied on the command line using this 1-line GUI. It's the best of both worlds.
|
||||
|
@ -77,7 +78,7 @@ if not fname:
|
|||
sg.MsgBox("Cancel", "No filename supplied")
|
||||
# raise SystemExit("Cancelling: no filename supplied")
|
||||
|
||||
|
||||
def Compare2Files():
|
||||
"""
|
||||
Compare 2 Files
|
||||
Browse to get 2 file names that can be then compared. Uses a context manager
|
||||
|
@ -94,10 +95,12 @@ with sg.FlexForm('File Compare') as form:
|
|||
|
||||
print(button, values)
|
||||
|
||||
def AllWidgetsWithContext():
|
||||
"""
|
||||
Nearly All Widgets with Green Color Theme with Context Manager
|
||||
Example of nearly all of the widgets in a single form. Uses a customized color scheme. This recipe uses a context manager, the preferred method.
|
||||
"""
|
||||
import PySimpleGUI as sg
|
||||
# Green & tan color scheme
|
||||
sg.SetOptions(background_color='#9FB8AD',
|
||||
text_element_background_color='#9FB8AD',
|
||||
|
@ -132,6 +135,7 @@ with sg.FlexForm('Everything bagel', default_element_size=(40, 1)) as form:
|
|||
|
||||
button, values = form.LayoutAndRead(layout)
|
||||
|
||||
def AllWidgetsNoContext():
|
||||
"""
|
||||
All Widgets No Context Manager
|
||||
"""
|
||||
|
@ -173,7 +177,7 @@ layout = [
|
|||
|
||||
button, values = form.LayoutAndRead(layout)
|
||||
|
||||
|
||||
def NonBlockingWithUpdates():
|
||||
"""
|
||||
Non-Blocking Form With Periodic Update
|
||||
An async form that has a button read loop. A Text Element is updated periodically with a running timer. There is no context manager for this recipe because the loop that reads the form is likely to be some distance away from where the form was initialized.
|
||||
|
@ -206,8 +210,8 @@ while True:
|
|||
time.sleep(.01)
|
||||
# if the loop finished then need to close the form for the user
|
||||
form.CloseNonBlockingForm()
|
||||
del (form)
|
||||
|
||||
def NonBlockingWithContext():
|
||||
"""
|
||||
Async Form (Non-Blocking) with Context Manager
|
||||
Like the previous recipe, this form is an async form. The difference is that this form uses a context manager.
|
||||
|
@ -232,6 +236,7 @@ with sg.FlexForm('Running Timer') as form:
|
|||
# if the loop finished then need to close the form for the user
|
||||
form.CloseNonBlockingForm()
|
||||
|
||||
def CallbackSimulation():
|
||||
"""
|
||||
Callback Function Simulation
|
||||
The architecture of some programs works better with button callbacks instead of handling in-line. While button callbacks are part of the PySimpleGUI implementation, they are not directly exposed to the caller. The way to get the same result as callbacks is to simulate them with a recipe like this one.
|
||||
|
@ -273,6 +278,7 @@ while True:
|
|||
# All done!
|
||||
sg.MsgBoxOK('Done')
|
||||
|
||||
def RealtimeButtons():
|
||||
"""
|
||||
Realtime Buttons (Good For Raspberry Pi)
|
||||
This recipe implements a remote control interface for a robot. There are 4 directions, forward, reverse, left, right. When a button is clicked, PySimpleGUI immediately returns button events for as long as the buttons is held down. When released, the button events stop. This is an async/non-blocking form.
|
||||
|
@ -308,7 +314,7 @@ while (True):
|
|||
|
||||
form.CloseNonBlockingForm()
|
||||
|
||||
|
||||
def EasyProgressMeter():
|
||||
"""
|
||||
Easy Progress Meter
|
||||
This recipe shows just how easy it is to add a progress meter to your code.
|
||||
|
@ -318,6 +324,7 @@ import PySimpleGUI as sg
|
|||
for i in range(1000):
|
||||
sg.EasyProgressMeter('Easy Meter Example', i+1, 1000)
|
||||
|
||||
def TabbedForm():
|
||||
"""
|
||||
Tabbed Form
|
||||
Tabbed forms are easy to make and use in PySimpleGUI. You simple may your layouts for each tab and then instead of LayoutAndRead you call ShowTabbedForm. Results are returned as a list of form results. Each tab acts like a single form.
|
||||
|
@ -340,6 +347,7 @@ with sg.FlexForm('', auto_size_text=True) as form:
|
|||
|
||||
sg.MsgBox(results)
|
||||
|
||||
def MediaPlayer():
|
||||
"""
|
||||
Button Graphics (Media Player)
|
||||
Buttons can have PNG of GIF images on them. This Media Player recipe requires 4 images in order to function correctly. The background is set to the same color as the button background so that they blend together.
|
||||
|
@ -405,6 +413,7 @@ while (True):
|
|||
if button:
|
||||
TextElem.Update(button)
|
||||
|
||||
def ScriptLauncher():
|
||||
"""
|
||||
Script Launcher - Persistent Form
|
||||
This form doesn't close after button clicks. To achieve this the buttons are specified as sg.ReadFormButton instead of sg.SimpleButton. The exception to this is the EXIT button. Clicking it will close the form. This program will run commands and display the output in the scrollable window.
|
||||
|
@ -450,6 +459,7 @@ def ExecuteCommandSubprocess(command, *args):
|
|||
|
||||
Launcher()
|
||||
|
||||
def MachineLearning():
|
||||
"""
|
||||
Machine Learning GUI
|
||||
A standard non-blocking GUI with lots of inputs.
|
||||
|
@ -492,6 +502,7 @@ layout = [[sg.Text('Machine Learning Command Line Parameters', font=('Helvetica'
|
|||
|
||||
button, values = form.LayoutAndRead(layout)
|
||||
|
||||
def CustromProgressMeter():
|
||||
""""
|
||||
Custom Progress Meter / Progress Bar
|
||||
Perhaps you don't want all the statistics that the EasyProgressMeter provides and want to create your own progress bar. Use this recipe to do just that.
|
||||
|
@ -523,6 +534,7 @@ def CustomMeter():
|
|||
|
||||
CustomMeter()
|
||||
|
||||
def OneLineGUI():
|
||||
"""
|
||||
The One-Line GUI
|
||||
For those of you into super-compact code, a complete customized GUI can be specified, shown, and received the results using a single line of Python code. The way this is done is to combine the call to FlexForm and the call to LayoutAndRead. FlexForm returns a FlexForm object which has the LayoutAndRead method.
|
||||
|
@ -538,10 +550,11 @@ button, (number,) = sg.FlexForm('Get filename example').LayoutAndRead(layout)
|
|||
"""
|
||||
you can write this line of code for the exact same result (OK, two lines with the import):
|
||||
"""
|
||||
import PySimpleGUI as sg
|
||||
# import PySimpleGUI as sg
|
||||
|
||||
button, (filename,) = sg.FlexForm('Get filename example'). LayoutAndRead([[sg.Text('Filename')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()] ])
|
||||
|
||||
def MultipleColumns():
|
||||
"""
|
||||
Multiple Columns
|
||||
Starting in version 2.9 (not yet released but you can get from current GitHub) you can use the Column Element. A Column is required when you have a tall element to the left of smaller elements.
|
||||
|
@ -575,6 +588,7 @@ button, values = sg.FlexForm('Compact 1-line form with column').LayoutAndRead(la
|
|||
|
||||
sg.MsgBox(button, values, line_width=200)
|
||||
|
||||
def PersistentForm():
|
||||
"""
|
||||
Persistent Form With Text Element Updates
|
||||
This simple program keep a form open, taking input values until the user terminates the program using the "X" button.
|
||||
|
@ -609,6 +623,7 @@ while True:
|
|||
else:
|
||||
break
|
||||
|
||||
def CanvasWidget():
|
||||
"""
|
||||
tkinter Canvas Widget
|
||||
The Canvas Element is one of the few tkinter objects that are directly accessible. The tkinter Canvas widget itself can be retrieved from a Canvas Element like this:
|
||||
|
@ -638,6 +653,7 @@ while True:
|
|||
elif button is 'Red':
|
||||
canvas.TKCanvas.itemconfig(cir, fill = "Red")
|
||||
|
||||
def InputElementUpdate():
|
||||
"""
|
||||
Input Element Update
|
||||
This Recipe implements a Raspberry Pi touchscreen based keypad entry. As the digits are entered using the buttons, the Input Element above it is updated with the input digits. There are a number of features used in this Recipe including: Default Element Size auto_size_buttons ReadFormButton Dictionary Return values Update of Elements in form (Input, Text) do_not_clear of Input Elements
|
||||
|
@ -687,64 +703,119 @@ while True:
|
|||
|
||||
in_elem.Update(keys_entered) # change the form to reflect current key string
|
||||
|
||||
"""
|
||||
Animated Matplotlib Graph
|
||||
Use the Canvas Element to create an animated graph. The code is a bit tricky to follow, but if you know Matplotlib then this recipe shouldn't be too difficult to copy and modify.
|
||||
"""
|
||||
from tkinter import *
|
||||
from random import randint
|
||||
import PySimpleGUI as g
|
||||
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, FigureCanvasAgg
|
||||
from matplotlib.figure import Figure
|
||||
import matplotlib.backends.tkagg as tkagg
|
||||
import tkinter as Tk
|
||||
# def EverythingInOne():
|
||||
# """
|
||||
# Animated Matplotlib Graph
|
||||
# Use the Canvas Element to create an animated graph. The code is a bit tricky to follow, but if you know Matplotlib then this recipe shouldn't be too difficult to copy and modify.
|
||||
# """
|
||||
# from tkinter import *
|
||||
# from random import randint
|
||||
# import PySimpleGUI as g
|
||||
# from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, FigureCanvasAgg
|
||||
# from matplotlib.figure import Figure
|
||||
# import matplotlib.backends.tkagg as tkagg
|
||||
# import tkinter as Tk
|
||||
#
|
||||
#
|
||||
# def main():
|
||||
# fig = Figure()
|
||||
#
|
||||
# ax = fig.add_subplot(111)
|
||||
# ax.set_xlabel("X axis")
|
||||
# ax.set_ylabel("Y axis")
|
||||
# ax.grid()
|
||||
#
|
||||
# canvas_elem = g.Canvas(size=(640, 480)) # get the canvas we'll be drawing on
|
||||
#
|
||||
# layout = [[g.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20')],
|
||||
# [canvas_elem],
|
||||
# [g.ReadFormButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]]
|
||||
#
|
||||
# # create the form and show it without the plot
|
||||
# form = g.FlexForm('Demo Application - Embedding Matplotlib In PySimpleGUI')
|
||||
# form.Layout(layout)
|
||||
# form.ReadNonBlocking()
|
||||
#
|
||||
# graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas)
|
||||
# canvas = canvas_elem.TKCanvas
|
||||
#
|
||||
# dpts = [randint(0, 10) for x in range(10000)]
|
||||
# for i in range(len(dpts)):
|
||||
# button, values = form.ReadNonBlocking()
|
||||
# if button is 'Exit' or values is None:
|
||||
# exit(69)
|
||||
#
|
||||
# ax.cla()
|
||||
# ax.grid()
|
||||
#
|
||||
# ax.plot(range(20), dpts[i:i + 20], color='purple')
|
||||
# graph.draw()
|
||||
# figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
|
||||
# figure_w, figure_h = int(figure_w), int(figure_h)
|
||||
# photo = Tk.PhotoImage(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()
|
||||
#
|
||||
# tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
|
||||
# # time.sleep(.1)
|
||||
|
||||
|
||||
def main():
|
||||
fig = Figure()
|
||||
# -------------------------------- GUI Starts Here -------------------------------#
|
||||
# fig = your figure you want to display. Assumption is that 'fig' holds the #
|
||||
# information to display. #
|
||||
# --------------------------------------------------------------------------------#
|
||||
|
||||
ax = fig.add_subplot(111)
|
||||
ax.set_xlabel("X axis")
|
||||
ax.set_ylabel("Y axis")
|
||||
ax.grid()
|
||||
# print(inspect.getsource(PyplotSimple))
|
||||
|
||||
canvas_elem = g.Canvas(size=(640, 480)) # get the canvas we'll be drawing on
|
||||
import PySimpleGUI as sg
|
||||
|
||||
layout = [[g.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20')],
|
||||
[canvas_elem],
|
||||
[g.ReadFormButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]]
|
||||
fig_dict = {'Simple Data Entry':SimpleDataEntry, 'Simple Entry Return Data as Dict':SimpleReturnAsDict, 'File Browse' : FileBrowse,
|
||||
'GUI Add On':GUIAddOn, 'Compare 2 Files':Compare2Files, 'All Widgets With Context Manager':AllWidgetsWithContext, 'All Widgets No Context Manager':AllWidgetsNoContext,
|
||||
'Non-Blocking With Updates':NonBlockingWithUpdates, 'Non-Bocking With Context Manager':NonBlockingWithContext, 'Callback Simulation':CallbackSimulation,
|
||||
'Realtime Buttons':RealtimeButtons, 'Easy Progress Meter':EasyProgressMeter, 'Tabbed Form':TabbedForm, 'Media Player':MediaPlayer, 'Script Launcher':ScriptLauncher,
|
||||
'Machine Learning':MachineLearning, 'Custom Progress Meter':CustromProgressMeter, 'One Line GUI':OneLineGUI, 'Multiple Columns':MultipleColumns,
|
||||
'Persistent Form':PersistentForm, 'Canvas Widget':CanvasWidget, 'Input Element Update':InputElementUpdate}
|
||||
|
||||
|
||||
# multiline_elem = sg.Multiline(size=(70,35),pad=(5,(3,90)))
|
||||
# define the form layout
|
||||
listbox_values = [key for key in fig_dict.keys()]
|
||||
multiline_elem = sg.Multiline(size=(70,35), do_not_clear=True)
|
||||
|
||||
while True:
|
||||
sg.ChangeLookAndFeel('LightGreen')
|
||||
col_listbox = [[sg.Listbox(values=listbox_values, size=(max(len(x) for x in listbox_values),len(listbox_values)), key='func')],
|
||||
[sg.SimpleButton('Run'), sg.ReadFormButton('Show Code'), sg.Exit()]]
|
||||
|
||||
layout = [[sg.Text('PySimpleGUI Coookbook', font=('current 18'))],
|
||||
[sg.Column(col_listbox, pad=(5,(3,2))), multiline_elem],
|
||||
]
|
||||
|
||||
# create the form and show it without the plot
|
||||
form = g.FlexForm('Demo Application - Embedding Matplotlib In PySimpleGUI')
|
||||
form.Layout(layout)
|
||||
form.ReadNonBlocking()
|
||||
# form.Layout(layout)
|
||||
|
||||
graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas)
|
||||
canvas = canvas_elem.TKCanvas
|
||||
|
||||
dpts = [randint(0, 10) for x in range(10000)]
|
||||
for i in range(len(dpts)):
|
||||
button, values = form.ReadNonBlocking()
|
||||
if button is 'Exit' or values is None:
|
||||
form = sg.FlexForm('Demo Application - Embedding Matplotlib In PySimpleGUI', default_button_element_size=(8,2),auto_size_buttons=False)
|
||||
button, values = form.LayoutAndRead(layout)
|
||||
print(button, values)
|
||||
# show it all again and get buttons
|
||||
while True:
|
||||
if button is None or button is 'Exit':
|
||||
exit(69)
|
||||
try:
|
||||
choice = values['func'][0]
|
||||
func = fig_dict[choice]
|
||||
except:
|
||||
continue
|
||||
|
||||
ax.cla()
|
||||
ax.grid()
|
||||
|
||||
ax.plot(range(20), dpts[i:i + 20], color='purple')
|
||||
graph.draw()
|
||||
figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
|
||||
figure_w, figure_h = int(figure_w), int(figure_h)
|
||||
photo = Tk.PhotoImage(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()
|
||||
|
||||
tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
|
||||
# time.sleep(.1)
|
||||
|
||||
|
||||
if __name__ == 'main':
|
||||
CustomMeter()
|
||||
if button is 'Show Code':
|
||||
multiline_elem.Update(inspect.getsource(func))
|
||||
button, values = form.Read()
|
||||
elif button is 'Run':
|
||||
sg.ChangeLookAndFeel('SystemDefault')
|
||||
func()
|
||||
break
|
||||
else:
|
||||
button, values = form.Read()
|
||||
|
|
Loading…
Reference in New Issue