def pong(): # ------------- Define GUI layout ------------- layout = [[ sg.Canvas(size=(700, 400), background_color='black', key='canvas') ], [sg.T(''), sg.ReadButton('Quit')]] # ------------- Create window ------------- window = sg.Window('The Classic Game of Pong', return_keyboard_events=True).Layout(layout).Finalize() # window.Finalize() # TODO Replace with call to window.Finalize once code released # ------------- Get the tkinter Canvas we're drawing on ------------- canvas = window.FindElement('canvas').TKCanvas # ------------- Create line down center, the bats and ball ------------- canvas.create_line(350, 0, 350, 400, fill='white') bat1 = pongbat(canvas, 'white') bat2 = pongbat2(canvas, 'white') ball1 = Ball(canvas, bat1, bat2, 'green') # ------------- Event Loop ------------- while True: # ------------- Draw ball and bats ------------- ball1.draw() bat1.draw() bat2.draw() # ------------- Read the form, get keypresses ------------- button, values = window.ReadNonBlocking() # ------------- If quit ------------- if button is None and values is None or button == 'Quit': exit(69) # ------------- Keypresses ------------- if button is not None: if button.startswith('Up'): bat2.up(2) elif button.startswith('Down'): bat2.down(2) elif button == 'w': bat1.up(1) elif button == 's': bat1.down(1) if ball1.checkwin(): sg.Popup('Game Over', ball1.checkwin() + ' won!!') break # ------------- Bottom of loop, delay between animations ------------- # time.sleep(.01) canvas.after(10)
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()
print(sep_line) message = [ "Now executing Nuitka as follows. Please be patient and let it finish!\n", cmd, ] print("\n".join(message)) print(sep_line) compile_start = time.time() # start stop watch for the compile rc = sp.Popen(cmd, shell=True) sg.Popup( message[0], message[1], "Auto-closing this window ...", auto_close=True, auto_close_duration=5, non_blocking=False, ) return_code = rc.wait() compile_stop = time.time() # start stop watch for the compile if return_code != 0: message = ["Nuitka compile failed!", "Check its output!"] print("\n".join(message)) sg.Popup(message[0], message[1]) raise SystemExit() print(sep_line)
break elif values[0] != '' and values[5] != '': folder = values[0] name = values[5] os.system(('mkdir ' + (folder + "/" + name))) print(folder + "," + name) elif values[0] != '' and values[6] != '': folder = values[0] name = values[6] os.system("touch " + (folder + "/" + name)) print("hello") elif values[1] != '': folder = values[1] os.system("rm -r " + (folder)) print("hello") elif values[2] != '': folder = values[1] name = values[2] os.system("rm " + name) print("hello") elif values[3] != '' and values[4] != '': folder = values[3] path = values[4] os.system("cp " + folder + " " + path + "/") elif values[7] != '' and values[0] != '': path = values[0] namefile = values[7] listfile = dir_list(path, namefile) sg.Popup("The File Found in :", [i for i in listfile]) #By Miss.Robot
def main(): RemoteControlExample() StatusOutputExample() sg.Popup('End of non-blocking demonstration')
print('\n') print('Creating BOM for OLT: ' + olt + '\n') get_olt_features(olt) fiber() strand_conduit() naps() peds_vaults() slack_anchors() fn = output + "\\{0}_BOM_{1}.xlsx".format(olt, str(time.strftime("%Y%m%d"))) wb.save(fn) print('BOM Created.') if __name__ == '__main__': # Created simple gui application for user ease of use. Initialized in config.py. while True: try: event, values = window.Read() if event is None or event == 'Exit': break input_gdb = values[0] output = values[1] olts = values[2] main(olts) sg.Popup('BOM(s) created.') except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() sg.Popup('Error in creating BOM(s)!', "Error : " + str(e), "LINE NO: {0}".format(exc_tb.tb_lineno))
#!/usr/bin/env python import sys if sys.version_info[0] < 3: import PySimpleGUI27 as sg else: 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 layout layout = [[sg.Listbox(values=('Listbox Item 1', 'Listbox Item 2', 'Listbox Item 3'), select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, size=(20, 3)), sg.Column(col, background_color='blue')], [sg.Input('Last input')], [sg.OK()]] # Display the window and get values button, values = sg.Window('Compact 1-line form with column').Layout(layout).Read() sg.Popup(button, values, line_width=200)
#!/usr/bin/env python import sys if sys.version_info[0] < 3: import PySimpleGUI27 as sg else: import PySimpleGUI as sg """ Simple Form showing how to use keys on your input fields """ layout = [[sg.Text('Please enter your Name, Address, Phone')], [sg.Text('Name', size=(15, 1)), sg.InputText('1', key='name')], [sg.Text('Address', size=(15, 1)), sg.InputText('2', key='address')], [sg.Text('Phone', size=(15, 1)), sg.InputText('3', key='phone')], [sg.Submit(), sg.Cancel()]] window = sg.Window('Simple Data Entry Window').Layout(layout) button, values = window.Read() sg.Popup(button, values, values['name'], values['address'], values['phone'])
# PIL supported image types img_types = (".png", ".jpg", "jpeg", ".tiff", ".bmp") # get list of files in folder flist0 = os.listdir(folder) # create sub list of image files (no sub folders, no wrong file types) fnames = [ f for f in flist0 if os.path.isfile(os.path.join(folder, f)) and f.lower().endswith(img_types) ] num_files = len(fnames) # number of iamges found if num_files == 0: sg.Popup('No files in folder') raise SystemExit() del flist0 # no longer needed #------------------------------------------------------------------------------ # use PIL to read data of one image #------------------------------------------------------------------------------ def get_img_data(f, maxsize=(1200, 850), first=False): """Generate image data using PIL """ img = Image.open(f) img.thumbnail(maxsize) if first: # tkinter is inactive the first time bio = io.BytesIO()
precision_a = np.append(precision_a, precision_v) f1_a = np.append(f1_a, get_f1(recall_v, precision_v)) mae_a = np.append(mae_a, get_mae(final, test_final)) rmse_a = np.append(rmse_a, get_rmse(final, test_final)) print "recall ", recall_a print "precision ", precision_a print "f1 ", f1_a print "mae ", mae_a print "rmse ", rmse_a new_recall = np.nanmean(recall_a) new_precision = np.nanmean(precision_a) new_f1 = np.nanmean(f1_a) new_mae = np.nanmean(mae_a) new_rmse = np.nanmean(rmse_a) sg.Popup( "Hotel Recommendations:", 'precision----------------------------------------------------------------------------------------', new_precision, 'recall-------------------------------------------------------------------------------------------', new_recall, 'f1-----------------------------------------------------------------------------------------------', new_f1, 'mae----------------------------------------------------------------------------------------------', new_mae, 'rmse---------------------------------------------------------------------------------------------', new_rmse, line_width=500)
if button != 'Submit': if button == 'Copy Original Tweet': pyperclip.copy(text) if button == 'Copy Russian translation': pyperclip.copy(russian_trans) if button == 'Copy English translation': pyperclip.copy(english_trans) if button == 'Cancel': break else: i += 1 if values[5] != '': i = int(values[5]) - 1 with open('tagged_spain.json', 'a') as fout: writeMiddle(name, profile_geolocation, text.encode('utf8'), tweet_geolocation, RT, fout) fout.write('\t\t\t\"Tag \": \"g' + str(values[0]) + 'r' + str(values[1]) + str(values[2]) + "\",\n") fout.write('\t\t\t\"Spain \": \"%s \"\n' % str(values[3])) if i < total: fout.write("\t\t},") else: fout.write("\t\t}") sg.Popup(button, values) writeEnding() f.close()
#!/usr/bin/env python import sys if sys.version_info[0] < 3: import PySimpleGUI27 as sg else: import PySimpleGUI as sg import sys ''' Quickly add a GUI to your script! This simple script shows a 1-line-GUI addition to a typical Python command line script. Previously this script accepted 1 parameter on the command line. When executed, that parameter is read into the variable fname. The 1-line-GUI shows a form that allows the user to browse to find the filename. The GUI stores the result in the variable fname, just like the command line parsing did. ''' if len(sys.argv) == 1: button, (fname, ) = sg.Window('My Script').LayoutAndRead( [[sg.T('Document to open')], [sg.In(), sg.FileBrowse()], [sg.Open(), sg.Cancel()]]) else: fname = sys.argv[1] if not fname: sg.Popup("Cancel", "No filename supplied") raise SystemExit("Cancelling: no filename supplied")
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 form'), sg.Cancel()] ] window = sg.Window('Everything bagel', default_element_size=(40, 1), grab_anywhere=False).Layout(layout) button, values = window.Read() sg.Popup('Title', 'The results of the window.', 'The button clicked was "{}"'.format(button), 'The values are', values)
from sys import exit as exit # Simple Image Browser based on PySimpleGUI # Get the folder containing the images from the user folder = sg.PopupGetFolder('Image folder to open') if folder is None: sg.PopupCancel('Cancelling') exit(0) # get list of PNG files in folder png_files = [folder + '\\' + f for f in os.listdir(folder) if '.png' in f] filenames_only = [f for f in os.listdir(folder) if '.png' in f] if len(png_files) == 0: sg.Popup('No PNG images in folder') exit(0) # define menu layout menu = [['File', ['Open Folder', 'Exit']], ['Help', ['About',]]] # define layout, show and read the window col = [[sg.Text(png_files[0], size=(80, 3), key='filename')], [sg.Image(filename=png_files[0], key='image')], [sg.ReadButton('Next', size=(8,2)), sg.ReadButton('Prev', size=(8,2)), sg.Text('File 1 of {}'.format(len(png_files)), size=(15,1), key='filenum')]] col_files = [[sg.Listbox(values=filenames_only, size=(60,30), key='listbox')], [sg.ReadButton('Read')]] layout = [[sg.Menu(menu)], [sg.Column(col_files), sg.Column(col)]]
#!/usr/bin/env python import sys if sys.version_info[0] < 3: import PySimpleGUI27 as sg else: import PySimpleGUI as sg # Here, have some windows on me.... [sg.PopupNoWait(location=(10 * x, 0)) for x in range(10)] print(sg.PopupYesNo('Yes No')) print(sg.PopupGetText('Get text', location=(1000, 200))) print(sg.PopupGetFile('Get file')) print(sg.PopupGetFolder('Get folder')) sg.Popup('Simple popup') sg.PopupNonBlocking('Non Blocking', location=(500, 500)) sg.PopupNoTitlebar('No titlebar') sg.PopupNoBorder('No border') sg.PopupNoFrame('No frame') # sg.PopupNoButtons('No Buttons') # don't mix with non-blocking... disaster ahead... sg.PopupCancel('Cancel') sg.PopupOKCancel('OK Cancel') sg.PopupAutoClose('Autoclose')
if val["tk-support"]: rename_script(pscript) cmd.append('"' + pscript + '"') cmd = " ".join(cmd) print(sep_line) message = ["Now executing Nuitka. Please be patient and let it finish!", cmd] print("\n".join(message)) print() rc = sp.Popen(cmd, shell=True) sg.Popup(message[0], message[1], "This window will auto-close soon.", auto_close=True, auto_close_duration=10, non_blocking=False) return_code = rc.wait() if val["tk-support"]: restore_script(pscript) if return_code != 0: message = ["Nuitka compile failed!", "Check its output!"] print("\n".join(message)) sg.Popup(message[0], message[1]) raise SystemExit() print(sep_line)
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
]] window = sg.Window("Disable Elements Demo", default_element_size=(12, 1), text_justification='r', auto_size_text=False, auto_size_buttons=False, keep_on_top=True, grab_anywhere=False, default_button_element_size=(12, 1)).Layout(layout).Finalize() key_list = 'cbox', 'listbox', 'radio1', 'radio2', 'spin', 'option', 'combo', 'reset', 'notes', 'multi', 'slider' for key in key_list: window.FindElement(key).Update( disabled=True) # don't do this kind of for-loop while True: button, values = window.Read() if button is None or button == 'Exit': break elif button == 'Disable': for key in key_list: window.FindElement(key).Update(disabled=True) elif button == 'Enable': for key in key_list: window.FindElement(key).Update(disabled=False) elif button == 'Values': sg.Popup(values, keep_on_top=True)
filter_input = values[6] feature_input = values[7] train = pd.read_csv("1_filter_train.csv", na_values=['no info', '.'], low_memory=False) train[ 'Rating_adjusted'] = train.Reviewer_Score - train.User_Average_Score train['Positive_Words_Percent'].fillna(0, inplace=True) train['Review_Date'] = pd.to_datetime( train['Review_Date']).astype('int64') list_hotel = train['Hotel_Address'].values # validation if id_input not in train.id.values.tolist(): sg.Popup("Invalid user Id") elif any(country_input in a for a in list_hotel) == False: sg.Popup("Invalid country/ city input") else: if norm_input != 'none': train = norm_test(norm_input, train) if filter_input != 'none': train = filter_test(filter_input, train) train = feature_test(feature_input, train, norm_input) hotelList = hotel_df(train, id_input, travel_input, room_input, travel_input) list1 = pd.Series(index=hotelList) for n in hotelList: pearson_corr = sim(train, id_input, n) print n
#!/usr/bin/env python import sys if sys.version_info[0] < 3: import PySimpleGUI27 as sg else: import PySimpleGUI as sg layout = [[sg.T('Calendar Test')], [sg.In('', size=(20, 1), key='input')], [sg.CalendarButton('Choose Date', target='input', key='date')], [sg.Ok(key=1)]] window = sg.Window('Calendar', grab_anywhere=False).Layout(layout) b, v = window.Read() sg.Popup(v['input'])