def RemoteControlExample(): # Make a form, but don't use context manager sg.SetOptions(element_padding=(0, 0)) back = '#eeeeee' image_forward = 'ButtonGraphics/RobotForward.png' image_backward = 'ButtonGraphics/RobotBack.png' image_left = 'ButtonGraphics/RobotLeft.png' image_right = 'ButtonGraphics/RobotRight.png' sg.SetOptions(border_width=0, button_color=('black', back), background_color=back, element_background_color=back, text_element_background_color=back) layout = [[sg.Text('Robotics Remote Control')], [sg.T('', justification='center', size=(19, 1), key='status')], [ sg.RealtimeButton('Forward', image_filename=image_forward, pad=((50, 0), 0)) ], [ sg.RealtimeButton('Left', image_filename=image_left), sg.RealtimeButton('Right', image_filename=image_right, pad=((50, 0), 0)) ], [ sg.RealtimeButton('Reverse', image_filename=image_backward, pad=((50, 0), 0)) ], [sg.T('')], [sg.Quit(button_color=('black', 'orange'))]] window = sg.Window('Robotics Remote Control', auto_size_text=True, grab_anywhere=False).Layout(layout) # # Some place later in your code... # You need to perform a ReadNonBlocking on your form every now and then or # else it won't refresh. # # your program's main loop while (True): # This is the code that reads and updates your window button, values = window.ReadNonBlocking() if button is not None: window.FindElement('status').Update(button) else: window.FindElement('status').Update('') # if user clicked quit button OR closed the form using the X, then break out of loop if button == 'Quit' or values is None: break window.CloseNonBlocking()
def table_example(): sg.SetOptions(auto_size_buttons=True) filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files", "*.csv"),)) # --- populate table with file contents --- # if filename == '': sys.exit(69) data = [] header_list = [] button = sg.PopupYesNo('Does this file have column names already?') if filename is not None: try: df = pd.read_csv(filename, sep=',', engine='python', header=None) # Header=None means you directly pass the columns names to the dataframe data = df.values.tolist() # read everything else into a list of rows if button == 'Yes': # Press if you named your columns in the csv header_list = df.iloc[0].tolist() # Uses the first row (which should be column names) as columns names data = df[1:].values.tolist() # Drops the first row in the table (otherwise the header names and the first row will be the same) elif button == 'No': # Press if you didn't name the columns in the csv header_list = ['column' + str(x) for x in range(len(data[0]))] # Creates columns names for each column ('column0', 'column1', etc) except: sg.PopupError('Error reading file') sys.exit(69) # sg.SetOptions(element_padding=(0, 0)) col_layout = [[sg.Table(values=data, headings=header_list, display_row_numbers=True, auto_size_columns=False, size=(None, len(data)))]] canvas_size = (13*10*len(header_list), 600) # estimate canvas size - 13 pixels per char * 10 per column * num columns layout = [[sg.Column(col_layout, size=canvas_size, scrollable=True)]] window = sg.Window('Table', grab_anywhere=False) b, v = window.LayoutAndRead(layout) sys.exit(69)
def main(): global g_exit, g_response_time # start ping measurement thread sg.ChangeLookAndFeel('Black') sg.SetOptions(element_padding=(0, 0)) layout = [ [ sg.Quit(button_color=('white', 'black')), sg.T('', pad=((100, 0), 0), font='Any 15', key='output') ], [ sg.Graph(CANVAS_SIZE, (0, 0), (SAMPLES, SAMPLE_MAX), background_color='black', key='graph') ], ] window = sg.Window('CPU Graph', grab_anywhere=True, keep_on_top=True, background_color='black', no_titlebar=True, use_default_focus=False).Layout(layout) graph = window.FindElement('graph') output = window.FindElement('output') # start cpu measurement thread thread = Thread(target=CPU_thread, args=(None, )) thread.start() last_cpu = i = 0 prev_x, prev_y = 0, 0 while True: # the Event Loop time.sleep(.5) button, values = window.ReadNonBlocking() if button == 'Quit' or values is None: # always give ths user a way out break # do CPU measurement and graph it current_cpu = int(g_cpu_percent * 10) if current_cpu == last_cpu: continue output.Update(current_cpu / 10) # show current cpu usage at top if current_cpu > SAMPLE_MAX: current_cpu = SAMPLE_MAX new_x, new_y = i, current_cpu if i >= SAMPLES: graph.Move(-STEP_SIZE, 0) # shift graph over if full of data prev_x = prev_x - STEP_SIZE graph.DrawLine((prev_x, prev_y), (new_x, new_y), color='white') prev_x, prev_y = new_x, new_y i += STEP_SIZE if i < SAMPLES else 0 last_cpu = current_cpu
def main(): global g_exit, g_response_time # start ping measurement thread thread = Thread(target=ping_thread, args=(None, )) thread.start() sg.ChangeLookAndFeel('Black') sg.SetOptions(element_padding=(0, 0)) layout = [ [ sg.T('Ping times to Google.com', font='Any 12'), sg.Quit(pad=((100, 0), 0), button_color=('white', 'black')) ], [ sg.Graph(CANVAS_SIZE, (0, 0), (SAMPLES, 500), background_color='black', key='graph') ], ] window = sg.Window('Canvas test', grab_anywhere=True, background_color='black', no_titlebar=False, use_default_focus=False).Layout(layout) graph = window.FindElement('graph') prev_response_time = None i = 0 prev_x, prev_y = 0, 0 while True: time.sleep(.2) button, values = window.ReadNonBlocking() if button == 'Quit' or values is None: break if g_response_time is None or prev_response_time == g_response_time: continue new_x, new_y = i, g_response_time[0] prev_response_time = g_response_time if i >= SAMPLES: graph.Move(-STEP_SIZE, 0) prev_x = prev_x - STEP_SIZE graph.DrawLine((prev_x, prev_y), (new_x, new_y), color='white') # window.FindElement('graph').DrawPoint((new_x, new_y), color='red') prev_x, prev_y = new_x, new_y i += STEP_SIZE if i < SAMPLES else 0 # tell thread we're done. wait for thread to exit g_exit = True thread.join()
def main(): global g_exit, g_response_time layout = [[sg.T('Enter width, height of graph')], [sg.In(size=(6, 1)), sg.In(size=(6, 1))], [sg.Ok(), sg.Cancel()]] window = sg.Window('Enter graph size').Layout(layout) b,v = window.Read() if b is None or b == 'Cancel': sys.exit(69) w, h = int(v[0]), int(v[1]) CANVAS_SIZE = (w,h) # start ping measurement thread sg.ChangeLookAndFeel('Black') sg.SetOptions(element_padding=(0,0)) layout = [ [sg.Quit( button_color=('white','black'))], [sg.Graph(CANVAS_SIZE, (0,0), (SAMPLES,SAMPLE_MAX),background_color='black', key='graph')],] window = sg.Window('Canvas test', grab_anywhere=True, background_color='black', no_titlebar=False, use_default_focus=False).Layout(layout).Finalize() graph = window.FindElement('graph') prev_response_time = None i=0 prev_x, prev_y = 0, 0 graph_value = 250 while True: # time.sleep(.2) button, values = window.ReadNonBlocking() if button == 'Quit' or values is None: break graph_offset = random.randint(-10, 10) graph_value = graph_value + graph_offset if graph_value > SAMPLE_MAX: graph_value = SAMPLE_MAX if graph_value < 0: graph_value = 0 new_x, new_y = i, graph_value prev_value = graph_value if i >= SAMPLES: graph.Move(-STEP_SIZE,0) prev_x = prev_x - STEP_SIZE graph.DrawLine((prev_x, prev_y), (new_x, new_y), color='white') # window.FindElement('graph').DrawPoint((new_x, new_y), color='red') prev_x, prev_y = new_x, new_y i += STEP_SIZE if i < SAMPLES else 0
def table_example(): filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files", "*.csv"), )) # --- populate table with file contents --- # if filename == '': sys.exit(69) data = [] header_list = [] button = sg.PopupYesNo('Does this file have column names already?') if filename is not None: with open(filename, "r") as infile: reader = csv.reader(infile) if button == 'Yes': header_list = next(reader) try: data = list(reader) # read everything else into a list of rows if button == 'No': header_list = [ 'column' + str(x) for x in range(len(data[0])) ] except: sg.PopupError('Error reading file') sys.exit(69) sg.SetOptions(element_padding=(0, 0)) col_layout = [[ sg.Table(values=data, headings=header_list, max_col_width=25, auto_size_columns=True, justification='right', size=(None, len(data))) ]] canvas_size = ( 13 * 10 * len(header_list), 600 ) # estimate canvas size - 13 pixels per char * 10 char per column * num columns layout = [ [sg.Column(col_layout, size=canvas_size, scrollable=True)], ] window = sg.Window('Table', grab_anywhere=False).Layout(layout) b, v = window.Read() sys.exit(69)
def getEvent(): # variables database = '/Users/DavidBailey/db/pythonsqlite.db' table = "events_pt" value = 'urban' # connect to sqlite conn = sqlite3.connect(database) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) db_path = os.path.join(BASE_DIR, database) with sqlite3.connect(db_path) as db: # gui layout sg.SetOptions( button_color=sg.COLOR_SYSTEM_DEFAULT , text_color=sg.COLOR_SYSTEM_DEFAULT ) layout = [[sg.Text('Enter text here', size=(40, 1), font=800)], [sg.Text('What type of event?', size=(15, 1), font=800), # values in event column in database sg.InputCombo(('urban', 'outdoors - hike', 'outdoors - no hike', 'outdoors - hard hike', '13er', '14er', 'backpacking'), size=(20, 1))], [sg.Button('Submit')]] window = sg.Window('Digital Bucket').Layout(layout) button, values = window.Read() value = ''.join(values) # select query on database cursor = conn.cursor() cursor.execute("SELECT event FROM %s where complete = 'N' and type = '%s'" % (table, value)) event_list = [] for record in cursor: event_list.append(record) main_value_list = random.choice(event_list) main_value = ''.join(main_value_list) print value print main_value # update query on database cursor.execute("UPDATE %s SET complete = 'Y' where event = '%s' and type = '%s'" % (table, main_value, value)) conn.commit() # show value in gui popup sg.Popup('You are going to....', main_value, font='800', size=(40, 1))
def TestMenus(): import PySimpleGUI as sg sg.ChangeLookAndFeel('LightGreen') sg.SetOptions(element_padding=(0, 0)) # ------ Menu Definition ------ # menu_def = [ ['File', ['Open', 'Save', 'Properties']], [ 'Edit', ['Paste', [ 'Special', 'Normal', ], 'Undo'], ], ['Help', 'About...'], ] # ------ GUI Defintion ------ # layout = [[sg.Menu(menu_def, tearoff=True)], [sg.Output(size=(60, 20))], [sg.In('Test', key='input', do_not_clear=True)]] window = sg.Window("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 = window.Read() if button is None or button == 'Exit': return print('Button = ', button) # ------ Process menu choices ------ # if button == 'About...': sg.Popup('About this program', 'Version 1.0', 'PySimpleGUI rocks...') elif button == 'Open': filename = sg.PopupGetFile('file to open', no_window=True) print(filename) elif button == 'Properties': SecondForm()
def Launcher(): # def print(line): # window.FindElement('output').Update(line) sg.ChangeLookAndFeel('Dark') namesonly = [f for f in os.listdir(ROOT_PATH) if f.endswith('.py')] sg.SetOptions(element_padding=(0, 0), button_element_size=(12, 1), auto_size_buttons=False) layout = [[ sg.Combo(values=namesonly, size=(35, 30), key='demofile'), sg.ReadButton('Run', button_color=('white', '#00168B')), sg.ReadButton('Program 1'), sg.ReadButton('Program 2'), sg.ReadButton('Program 3', button_color=('white', '#35008B')), sg.Button('EXIT', button_color=('white', 'firebrick3')) ], [sg.T('', text_color='white', size=(50, 1), key='output')]] window = sg.Window('Floating Toolbar', no_titlebar=True, keep_on_top=True).Layout(layout) # ---===--- Loop taking in user input and executing appropriate program --- # while True: (button, value) = window.Read() if button is 'EXIT' or button is None: break # exit button clicked if button is 'Program 1': print('Run your program 1 here!') elif button is 'Program 2': print('Run your program 2 here!') elif button is 'Run': file = value['demofile'] print('Launching %s' % file) ExecuteCommandSubprocess('python', os.path.join(ROOT_PATH, file)) else: print(button)
def TableSimulation(): """ Display data in a table format """ sg.SetOptions(element_padding=(0, 0)) sg.PopupNoWait('Give it a few seconds to load please...', auto_close=True) menu_def = [ ['File', ['Open', 'Save', 'Exit']], [ 'Edit', ['Paste', [ 'Special', 'Normal', ], 'Undo'], ], ['Help', 'About...'], ] columm_layout = [[]] MAX_ROWS = 60 MAX_COL = 10 for i in range(MAX_ROWS): inputs = [sg.T('{}'.format(i), size=(4, 1), justification='right')] + [ sg.In(size=(10, 1), pad=(1, 1), justification='right', key=(i, j), do_not_clear=True) for j in range(MAX_COL) ] columm_layout.append(inputs) layout = [ [sg.Menu(menu_def)], [sg.T('Table Using Combos and Input Elements', font='Any 18')], [ sg. T('Type in a row, column and value. The form will update the values in realtime as you type' ), sg.In(key='inputrow', justification='right', size=(8, 1), pad=(1, 1), do_not_clear=True), sg.In(key='inputcol', size=(8, 1), pad=(1, 1), justification='right', do_not_clear=True), sg.In(key='value', size=(8, 1), pad=(1, 1), justification='right', do_not_clear=True) ], [sg.Column(columm_layout, size=(800, 600), scrollable=True)] ] window = sg.Window('Table', return_keyboard_events=True, grab_anywhere=False).Layout(layout) while True: button, values = window.Read() # --- Process buttons --- # if button is None or button == 'Exit': break elif button == 'About...': sg.Popup('Demo of table capabilities') elif button == 'Open': filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files", "*.csv"), )) # --- populate table with file contents --- # if filename is not None: with open(filename, "r") as infile: reader = csv.reader(infile) try: data = list( reader) # read everything else into a list of rows except: sg.PopupError('Error reading file') continue # clear the table [ window.FindElement((i, j)).Update('') for j in range(MAX_COL) for i in range(MAX_ROWS) ] for i, row in enumerate(data): for j, item in enumerate(row): location = (i, j) try: # try the best we can at reading and filling the table target_element = window.FindElement(location) new_value = item if target_element is not None and new_value != '': target_element.Update(new_value) except: pass # if a valid table location entered, change that location's value try: location = (int(values['inputrow']), int(values['inputcol'])) target_element = window.FindElement(location) new_value = values['value'] if target_element is not None and new_value != '': target_element.Update(new_value) except: pass
#!/usr/bin/env python import sys if sys.version_info[0] < 3: import PySimpleGUI27 as sg else: import PySimpleGUI as sg """ Demonstrates using a "tight" layout with a Dark theme. Shows how button states can be controlled by a user application. The program manages the disabled/enabled states for buttons and changes the text color to show greyed-out (disabled) buttons """ sg.ChangeLookAndFeel('Dark') sg.SetOptions(element_padding=(0, 0)) layout = [[ sg.T('User:'******'User 1', 'User 2'), size=(20, 1)), sg.T('0', size=(8, 1)) ], [ sg.T('Customer:', pad=((3, 0), 0)), sg.OptionMenu(values=('Customer 1', 'Customer 2'), size=(20, 1)), sg.T('1', size=(8, 1)) ], [ sg.T('Notes:', pad=((3, 0), 0)), sg.In(size=(44, 1), background_color='white', text_color='black') ], [ sg.ReadButton('Start',
'wheat3': '#CDBA96', 'wheat4': '#8B7E66', 'white': '#FFFFFF', 'white smoke': '#F5F5F5', 'WhiteSmoke': '#F5F5F5', 'yellow': '#FFFF00', 'yellow green': '#9ACD32', 'yellow1': '#FFFF00', 'yellow2': '#EEEE00', 'yellow3': '#CDCD00', 'yellow4': '#8B8B00', 'YellowGreen': '#9ACD32', } sg.SetOptions(button_element_size=(12, 1), element_padding=(0, 0), auto_size_buttons=False, border_width=1) layout = [[ sg.Text('Hover mouse to see RGB value, click for white & black text', text_color='blue', font='Any 15', relief=sg.RELIEF_SUNKEN, justification='center', size=(100, 1), background_color='light green', pad=(0, (0, 20))), ]] row = [] # -- Create primary color viewer window -- for i, color in enumerate(color_map):
def MediaPlayerGUI(): 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' # A text element that will be changed to display messages in the GUI # define layout of the rows layout = [[ sg.Text('Media File Player', size=(17, 1), font=("Helvetica", 25)) ], [sg.Text('', size=(15, 2), font=("Helvetica", 14), key='output')], [ sg.ReadButton('Restart Song', button_color=(background, background), image_filename=image_restart, image_size=(50, 50), image_subsample=2, border_width=0), sg.Text(' ' * 2), sg.ReadButton('Pause', button_color=(background, background), image_filename=image_pause, image_size=(50, 50), image_subsample=2, border_width=0), sg.Text(' ' * 2), sg.ReadButton('Next', button_color=(background, background), image_filename=image_next, image_size=(50, 50), image_subsample=2, border_width=0), sg.Text(' ' * 2), sg.Text(' ' * 2), sg.Button('Exit', button_color=(background, background), image_filename=image_exit, image_size=(50, 50), image_subsample=2, border_width=0) ], [sg.Text('_' * 20)], [sg.Text(' ' * 30)], [ sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', font=("Helvetica", 15)), sg.Text(' ' * 2), sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', font=("Helvetica", 15)), sg.Text(' ' * 2), sg.Slider(range=(-10, 10), default_value=0, size=(10, 20), orientation='vertical', font=("Helvetica", 15)) ], [ sg.Text(' Bass', font=("Helvetica", 15), size=(9, 1)), sg.Text('Treble', font=("Helvetica", 15), size=(7, 1)), sg.Text('Volume', font=("Helvetica", 15), size=(7, 1)) ]] # Open a form, note that context manager can't be used generally speaking for async forms window = sg.Window('Media File Player', auto_size_text=True, default_element_size=(20, 1), font=("Helvetica", 25), no_titlebar=True).Layout(layout) # Our event loop while (True): # Read the form (this call will not block) button, values = window.ReadNonBlocking() if button == 'Exit': break # If a button was pressed, display it on the GUI by updating the text element if button: window.FindElement('output').Update(button)
def MachineLearningGUI(): sg.SetOptions(text_justification='right') flags = [ [ sg.Checkbox('Normalize', size=(12, 1), default=True), sg.Checkbox('Verbose', size=(20, 1)) ], [ sg.Checkbox('Cluster', size=(12, 1)), sg.Checkbox('Flush Output', size=(20, 1), default=True) ], [ sg.Checkbox('Write Results', size=(12, 1)), sg.Checkbox('Keep Intermediate Data', size=(20, 1)) ], [ sg.Checkbox('Normalize', size=(12, 1), default=True), sg.Checkbox('Verbose', size=(20, 1)) ], [ sg.Checkbox('Cluster', size=(12, 1)), sg.Checkbox('Flush Output', size=(20, 1), default=True) ], [ sg.Checkbox('Write Results', size=(12, 1)), sg.Checkbox('Keep Intermediate Data', size=(20, 1)) ], ] loss_functions = [ [ sg.Radio('Cross-Entropy', 'loss', size=(12, 1)), sg.Radio('Logistic', 'loss', default=True, size=(12, 1)) ], [ sg.Radio('Hinge', 'loss', size=(12, 1)), sg.Radio('Huber', 'loss', size=(12, 1)) ], [ sg.Radio('Kullerback', 'loss', size=(12, 1)), sg.Radio('MAE(L1)', 'loss', size=(12, 1)) ], [ sg.Radio('MSE(L2)', 'loss', size=(12, 1)), sg.Radio('MB(L0)', 'loss', size=(12, 1)) ], ] command_line_parms = [ [ sg.Text('Passes', size=(8, 1)), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1)), sg.Text('Steps', size=(8, 1), pad=((7, 3))), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1)) ], [ sg.Text('ooa', size=(8, 1)), sg.In(default_text='6', size=(8, 1)), sg.Text('nn', size=(8, 1)), sg.In(default_text='10', size=(10, 1)) ], [ sg.Text('q', size=(8, 1)), sg.In(default_text='ff', size=(8, 1)), sg.Text('ngram', size=(8, 1)), sg.In(default_text='5', size=(10, 1)) ], [ sg.Text('l', size=(8, 1)), sg.In(default_text='0.4', size=(8, 1)), sg.Text('Layers', size=(8, 1)), sg.Drop(values=('BatchNorm', 'other'), auto_size_text=True) ], ] layout = [[ sg.Frame('Command Line Parameteres', command_line_parms, title_color='green', font='Any 12') ], [sg.Frame('Flags', flags, font='Any 12', title_color='blue')], [ sg.Frame('Loss Functions', loss_functions, font='Any 12', title_color='red') ], [sg.Submit(), sg.Cancel()]] window = sg.Window('Machine Learning Front End', font=("Helvetica", 12)).Layout(layout) button, values = window.Read() sg.SetOptions(text_justification='left') print(button, values)