def AddResults(): colnames = ["_TeamName_", "_member1_","_member2_","_member3_","_member4_","_member5_",] data = pd.read_csv('teams.csv', names=colnames, header = 0) layout = [ [sg.Text('Please select team 1'),sg.Drop(key = "Team1",values=(data._TeamName_.tolist()), auto_size_text=True),sg.Text('Goals:'),sg.InputText('Name', key='_goals1_')], [sg.Text('Please select team 2'),sg.Drop(key = "Team2",values=(data._TeamName_.tolist()), auto_size_text=True),sg.Text('Goals:'),sg.InputText('Name', key='_goals2_')], [sg.Submit(), sg.Cancel()] ] window = sg.Window('Simple data entry GUI').Layout(layout) event, values = window.Read() window.Close() file_exists = os.path.isfile("scores.csv") with open("scores.csv", "a") as csvfile: colnames = ["_TeamName_", "_Goals_","_Goals_","_TeamName_",] writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) fields = [values['Team1'], values['_goals1_'], values['_goals2_'],values['Team2'],] if not file_exists: writer.writerow(colnames) writer.writerow(fields)
def pxxtest04(): # Green & tan color scheme sg.ChangeLookAndFeel('GreenTan') sg.SetOptions(text_justification='right') layout = [[sg.Text('Machine Learning Command Line Parameters', font=('Helvetica', 16))], [sg.Text('Passes', size=(15, 1)), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1)), sg.Text('Steps', size=(18, 1)), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1))], [sg.Text('ooa', size=(15, 1)), sg.In(default_text='6', size=(10, 1)), sg.Text('nn', size=(15, 1)), sg.In(default_text='10', size=(10, 1))], [sg.Text('q', size=(15, 1)), sg.In(default_text='ff', size=(10, 1)), sg.Text('ngram', size=(15, 1)), sg.In(default_text='5', size=(10, 1))], [sg.Text('l', size=(15, 1)), sg.In(default_text='0.4', size=(10, 1)), sg.Text('Layers', size=(15, 1)), sg.Drop(values=('BatchNorm', 'other'), auto_size_text=True)], [sg.Text('_' * 100, size=(65, 1))], [sg.Text('Flags', font=('Helvetica', 15), justification='left')], [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.Text('_' * 100, size=(65, 1))], [sg.Text('Loss Functions', font=('Helvetica', 15), justification='left')], [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))], [sg.Submit(), sg.Cancel()]] window = sg.Window('Machine Learning Front End', layout, font=("Helvetica", 12)) event, values = window.read()
def identify_line_GUI(self): if self.label == 'None': self.label = 'LLS Small' data = line.read_line_list(self.label) Transition_List = [] wavelist = [] for i in range(0, len(data)): Transition_List.append(data[i]['ion']) wavelist.append(data[i]['wrest']) layout = [[sg.Text('Please select the transition and LineList')], [ sg.Listbox(values=Transition_List, size=(30, 6), key='_Transition_') ], [ sg.Text('LineList', size=(15, 1)), sg.Drop(values=(self.label, 'LLS', 'LLS Small', 'DLA'), size=(15, 1), key='_Menu_') ], [sg.Button('Reset'), sg.Button('Submit')]] window = sg.Window('Line Identification', layout, font=("Helvetica", 12)) while True: # Event Loop event, values = window.Read() if event is None or event == 'Submit': break self.label = values['_Menu_'] data = line.read_line_list(self.label) Transition_List = [] wavelist = [] for i in range(0, len(data)): Transition_List.append(data[i]['ion']) wavelist.append(data[i]['wrest']) window.Element('_Transition_').Update(Transition_List) window.Close() Transition_List = np.array(Transition_List) wavelist = np.array(wavelist) Transition_rest = values['_Transition_'] qq = np.where(Transition_List == Transition_rest) #ipdb.set_trace() lambda_rest = wavelist[qq][0] LineList = values['_Menu_'] return lambda_rest, LineList
def set_redshift_GUI(self): layout = [[sg.Text('Please enter the desired redshift, LineList')], [ sg.Text('Redshift', size=(15, 1)), sg.InputText(np.str(self.zabs)) ], [ sg.Text('LineList', size=(15, 1)), sg.Drop(values=(self.label, 'None', 'LLS', 'LLS Small', 'DLA'), auto_size_text=True) ], [sg.Submit(), sg.Cancel()]] window = sg.Window('Redshift Query', layout, font=("Helvetica", 12)) event, values = window.Read() window.Close() zabs = values[0] LineList = values[1] return zabs, LineList
def __init__(self): layout = [ [sg.Text('Please enter the following parameters')], [sg.Text('Bioreactor Type', size=(25, 1)), sg.Drop(key='BIO', values=( 'multitissue', 'eht'), size=(25, 1))], [sg.Text('Folder:', size=(25, 1)), sg.InputText( key='FOLDER'), sg.FolderBrowse()], [sg.Text('Percentage Threshold', size=(25, 1)), sg.InputText('.8', key='THRESWIDTH')], [sg.Text('Youngs Modulus', size=(25, 1)), sg.InputText('1.33', key='YOUNGS')], [sg.Text('Distance between posts', size=(25, 1)), sg.InputText('10', key='MAXDISP')], [sg.Text('Peak Detection Sensitivity', size=(25, 1)), sg.InputText('.5', key='PEAKSENS')], [sg.Text('Peak Detection Difference', size=(25, 1)), sg.InputText('15', key='PEAKDIST')], [sg.Text('Peak Smoothing Polynomial', size=(25, 1)), sg.InputText('4', key='PEAKPOLY')], [sg.Text('Peak Smoothing Window Size', size=(25, 1)), sg.InputText('13', key='PEAKWIND')], [sg.Text('Time Min', size=(25, 1)), sg.InputText('0', key='TIMEMIN')], [sg.Text('Time Max', size=(25, 1)), sg.InputText('0', key='TIMEMAX')], [sg.Submit(), sg.Cancel()] ] window = sg.Window('Analyze GUI', layout) event, expar = window.Read() floaterizer = ['THRESWIDTH', 'YOUNGS', 'MAXDISP', 'PEAKSENS', 'PEAKDIST', 'TIMEMIN', 'TIMEMAX'] intergerizer = ['PEAKPOLY', 'PEAKWIND'] for item in floaterizer: expar[item] = float(expar[item]) for item in intergerizer: expar[item] = int(expar[item]) analyze = GraphAnalyze(expar)
def run_gui(): settings_path = os.path.join(cd, 'setting.json') def clear_empty_top_widget(ui): ''' clear ui to easyily for coping functionality (ctrl+c) ''' ''' # case1 sg.Frame('', key='gridLayout', layout = [ [sg.RButton('PushButton', key='pushButton'), sg.RButton('PushButton', key='pushButton_2')] ]) ''' first_line = ui.split('\n')[0] regex_matched = make_regex( r"^sg.Frame\('',\s?key='.*',\slayout\s=\s\[").match(first_line) if regex_matched and ui[-2:] == '])': new_ui = '[\n' + '\n'.join(ui.split('\n')[1:]).strip() return new_ui[:-1] return ui def update_clear_btn(my_window, my_values, real_value=''): objname = my_values['objname'] if real_value == '' else real_value all_object_names_in_combo = my_window['objs'].Values if my_values['xmlfile'] and objname and objname in all_object_names_in_combo: my_window['convert_btn'].update(disabled=False) my_window['convert_all_events'].update(disabled=False) my_window['convert_btns_events'].update(disabled=False) else: my_window['convert_btn'].update(disabled=True) my_window['convert_all_events'].update(disabled=True) my_window['convert_btns_events'].update(disabled=True) def update_app_settings(): with open(settings_path, 'w', encoding='utf-8') as f: json.dump(_settings, f, ensure_ascii=False, indent=2) if os.path.exists(settings_path): try: with open(settings_path, 'r', encoding='utf-8') as f: _settings = json.load(f) except Exception as e: _settings = { '-memento-file-cb-': False, 'xmlfile': '' } update_app_settings() else: _settings = { '-memento-file-cb-': False, 'xmlfile': '' } update_app_settings() ############### ### GUI ### ############### ralign = {'size': (16, 1), "justification": 'r'} main_layout = [ [sg.T('xml file', **ralign), sg.I(key='xmlfile', size=(35, 2), change_submits=True), sg.FileBrowse(target='xmlfile')], [sg.T('target object name', **ralign), sg.I(key='objname', size=(35, 2), change_submits=True)], [sg.T('all object names', **ralign), sg.Drop(values=[''], key='objs', size=(34, 1), change_submits=True) ], [ sg.T('', **ralign), sg.B('convert', key='convert_btn', disabled=True), sg.B('convert++\nall events', size=(-1, 2), key='convert_all_events', disabled=True), sg.B('convert++\nbtns events', size=(-1, 2), key='convert_btns_events', disabled=True) ], [ sg.T('options:', **ralign), sg.CB('try convert unknows widgets', True, key='no_bad_widgets') ], ] settings_layout = [ [sg.CB('Remember path to previous file', False, change_submits=True, key='-memento-file-cb-')], [sg.T('Indent size', key='indent_size '), sg.I('1', size=(5, 1), key='indent_size')], [sg.T('Indent char', key='indent_char '), sg.I(' ', size=(5, 1), key='indent_char')], ] layout = [ [ sg.TabGroup([[ sg.Tab('transpiler', main_layout), sg.Tab('settings', settings_layout) ]]), sg.Frame('Output data', layout=[ [sg.B('Clear output', key='clear_btn'), sg.B('Execute output (used after convert++)', size=(35, 1), disabled=True, key='Try')], [sg.ML(key='psg_ui_output', size=(60, 15))] ], key='message_board', metadata='Output data')], ] window = sg.Window('Transpiler', layout, auto_size_buttons=False, default_button_element_size=(10, 1), finalize=True, location=(100, 100)) # setup if _settings['-memento-file-cb-']: window['-memento-file-cb-'].update(True) window['xmlfile'].update(_settings['xmlfile']) timers = [] def send_board_message(text='*** Done ***', window=None): curr_title = window['message_board'].metadata new_title = '{} | {} '.format(curr_title, text) window['message_board'].TKFrame.config(text=new_title) # counter end -> execute this: def clear_frame(): new_board_message = window['message_board'].metadata window['message_board'].TKFrame.config(text=new_board_message) return {'count': 1, 'finished' : clear_frame} # loop prev_values = None first_time_running = True while True: # первый запуск -> подгружка имен из xmlfile, если он есть if first_time_running: event, values = window.read(timeout=0) event = 'xmlfile' first_time_running = False else: event, values = window.read(timeout=500) if event in (None, 'Exit'): break # сдежка за таймерами и их работами for a_timer in timers: if a_timer['count'] > 0: a_timer['count'] -= 1 elif a_timer['count'] == 0: a_timer['finished']() timers.remove(a_timer) ################################ # _ _ # # | | (_) # # | | ___ __ _ _ ___ # # | |/ _ \ / _` | |/ __| # # | | (_) | (_| | | (__ # # |_|\___/ \__, |_|\___| # # __/ | # # |___/ # ################################ indend_size_n_char = int(values['indent_size']), values['indent_char'] prev_values = values if event == '-memento-file-cb-': _settings['-memento-file-cb-'] = values['-memento-file-cb-'] _settings['xmlfile'] = '' if values['-memento-file-cb-'] else values['xmlfile'] update_app_settings() elif event == 'xmlfile': myxml_file = values['xmlfile'].strip() # remember this file if _settings['-memento-file-cb-']: _settings['xmlfile'] = myxml_file update_app_settings() if os.path.exists(myxml_file) and os.path.isfile(myxml_file): # get xml with open(myxml_file, 'r', encoding='utf-8') as ff: xml_code = ff.read() # filter object names widgets_regexpattern = make_regex( r"^[ \s]{1,}<(widget)\s?.*?\s?name=\"(.+)\"\/?>", MULTILINE) layouts_regexpattern = make_regex( r"^[ \s]{1,}<(layout)\s?.*?\s?name=\"(.+)\"\/?>", MULTILINE) widgets = [i.group(2) for i in finditer( widgets_regexpattern, xml_code)] layouts = [i.group(2) for i in finditer( layouts_regexpattern, xml_code)] widgets.sort() layouts.sort() combo_items = ['# pick LAYOUTS widgets #', *layouts, '# pick WIDGETS widgets #', *widgets] # set it window['objs'].update(values=combo_items) update_clear_btn(window, values) el = combo_items[1] if ' ' not in el: window['objname'].update(el) update_clear_btn(window, values, real_value=el) else: window['objs'].update(values=[]) window['objname'].update('') elif event == 'objs': # add only REAL object names -> those, who not contain ' ' if ' ' not in values['objs']: window['objname'].update(values['objs']) update_clear_btn(window, values, real_value=values['objs']) elif event == 'objname': update_clear_btn(window, values) elif event == 'clear_btn': window['psg_ui_output'].update('') elif event == 'convert_btn': ui = just_compile(values, *indend_size_n_char) window['psg_ui_output'].update(ui) if ui.startswith('Error:'): # fail timers.append(send_board_message(text='*** Fail ***', window=window)) else: # success timers.append(send_board_message(text='*** Done ***', window=window)) elif event == 'convert_all_events': ui = just_compile(values, *indend_size_n_char) psg_ui = build_boilerplate(layout=ui, btns_event=False, all_events=True) if ui.startswith('Error:'): # fail window['psg_ui_output'].update(ui) timers.append(send_board_message(text='*** Fail ***', window=window)) else: # success window['psg_ui_output'].update(psg_ui) timers.append(send_board_message(text='*** Done ***', window=window)) elif event == 'convert_btns_events': ui = just_compile(values, *indend_size_n_char) psg_ui = build_boilerplate(layout=ui, btns_event=True, all_events=False) if ui.startswith('Error:'): # fail window['psg_ui_output'].update(ui) timers.append(send_board_message(text='*** Fail ***', window=window)) else: # success window['psg_ui_output'].update(psg_ui) timers.append(send_board_message(text='*** Done ***', window=window)) elif event == 'Try': try: psg_ui = values['psg_ui_output'].strip() psg_ui_lines = psg_ui.split('\n') ''' case 1: import PySimpleGUI as sg ... case 2: sg.Frame('', layout = [ [...], [...], [...], ]) case 3: [ [...], [...], [...], ] ''' if psg_ui.startswith('import PySimpleGUI as sg'): exec(psg_ui) if psg_ui_lines[0].startswith("""sg.Frame('""") and psg_ui_lines[0].endswith("""', layout = ["""): window2 = sg.Window('test', eval(psg_ui)) window2.read() window2.close() if psg_ui_lines[0].startswith("""[""") and psg_ui_lines[-1].endswith("""]"""): possible_ui = eval(psg_ui) possible_ui if type(possible_ui) is list and type(possible_ui[0]) is not list: raise Exception(f"bad ui given. It's not a list of LISTS.") window2 = sg.Window('test', possible_ui) window2.read() window2.close() except Exception as e: sg.popup(str(e)) window.close()
def __init__(self): #Menu menu_def = [ ['&Help', '&Tutorial'], ] menu = sg.Menu(menu_def, ) #File imports def left(name): return sg.Text('{}:'.format(name), size=(10, 2)) def mid(): return sg.Text('Nothing imported.', size=(30, 2)) repo_row = [left('Repo Files'), mid(), sg.FolderBrowse(key="-repo-")] combi_row = [ left('Combinations'), mid(), sg.FilesBrowse(key="-combinations-") ] user_rules_row = [ left('User Rules'), mid(), sg.FilesBrowse(key="-user_rules-") ] inventory_row = [ left('Inventory'), mid(), sg.FilesBrowse(key="-inventory-") ] import_file = [repo_row, combi_row, user_rules_row, inventory_row] #Main rea main_area = [[ sg.Image(r'C:\Users\Xinling\gui\logo\final7.png'), sg.Text('HiPAD', font=('', 40), text_color='#254393') ], [sg.Text('High Throughput Plasmid Assembly Design', font=('', 12))], [ sg.Text('Task Name:'), sg.InputText( '', key="-task_name-", size=(22, 1), ) ], [ sg.Text('Assembly Method:'), sg.Drop(values=('SENAX'), key="-assembly-", size=(12, 1)) ], [ sg.Frame('Import', import_file, title_color='#254393', font=(12)) ], [ sg.Text('', size=(48, 2)), sg.Button('Run'), sg.Button('Cancel') ]] #Overall layout layout = [[menu], [sg.Column(main_area, element_justification='c')]] # Create the Window super().__init__('HiPAD', layout) #Other attributes self.output = None
def display_gui(self): """ The method that displays the GUI to the user. """ # Set basic theme options. sg.theme('Black') sg.SetOptions(font=("Lato", 14)) # Global sizing options full_width = 80 full_size = int(full_width / 2) half_size = int(full_size / 2) adjusted_full = full_width + full_size + half_size # Element-specific definitions cb_size = 6 # Scale style definitions scale_header_font_size = 32 scale_header_size = 40 scale_subheader_size = 16 scale_list_font_size = 18 scale_list_size = 52 mini_bar_font_size = 8 mini_bar_size = 80 mini_bar_color = '#dddddd' scale_bg_color = '#222222' scale_alt_text = 'orange' button_pdf_color = '#00e676' button_muse_color = '#2fa4e7' note_nums = (ANY, '5', '6', '7', '8', '9', '10', '11', '12') # Row 1 - Key selection combo box. col_topleft = [[sg.Text('Key: ', size=(half_size, 1))], [ sg.Drop( self._keys_for_display, default_value=self.selected_key.get_longname(), enable_events=True, size=(half_size, 1), key='R1_KEY') ]] # Row 1 - Note count selection combo box. col_topmid = [[sg.Text('# of Notes: ', size=(half_size, 1))], [ sg.Drop(note_nums, default_value=note_nums[0], enable_events=True, size=(half_size, 1), key='R1_NOTECOUNT') ]] # Row 1 - Search box. col_topright = [[sg.Text('Search: ', size=(full_size, 1))], [ sg.In(size=(full_size, 1), enable_events=True, key='R1_SEARCH') ]] # Row 1 - Combined layout. layout_one = [ sg.Column(col_topleft), sg.Column(col_topmid), sg.VerticalSeparator(), sg.Column(col_topright) ] # Row 2 checkboxes = [[]] # Cycle through all the note choices by key and create a checkbox for them. for i in range(1, MAX_SCALE_LENGTH): checkboxes[0].append( sg.Checkbox(self.note_opts_by_key[i].get_shortname(), size=(cb_size, 1), enable_events=True, disabled=True, key=R2_NOTE + str(i))) layout_two = [ sg.Frame('Notes to include (Feature coming soon!): ', checkboxes, pad=(50, 3), element_justification='center') ] # The list to hold the scale display tiles. scale_layout = [] # Cycle through scales_for_display and generate scale tiles for display to user. for i, scale in enumerate(self.scales_for_display, 1): # Convert each scale to the selected key. converted_scale = self._converter.convert_scale( scale, self.selected_key.get_root(), self.selected_key.get_accidental()) # Get a formatted string of the notes of this scale for the given key. scale_notes = ", ".join( [nt.get_shortname() for nt in converted_scale]) # Create this scale tile. this_scale = [[ sg.Text('' + str(i) + '. ' + scale.get_name(), background_color=scale_bg_color, size=(scale_header_size, 1), font=('Lato', scale_header_font_size), key=SC_TITLE + str(i)) ], [ sg.Text('Alternate Names: ', background_color=scale_bg_color, pad=(0, 0), text_color=scale_alt_text, font=('Lato', scale_subheader_size)), sg.Text(scale.get_formatted_alt_names(), background_color=scale_bg_color, pad=(0, 0), size=(70, 1), font=('Lato', scale_subheader_size), key=SC_ALTS + str(i)) ], [ sg.Text('Number of notes: ', background_color=scale_bg_color, pad=(0, 0), text_color=scale_alt_text, font=('Lato', scale_subheader_size)), sg.Text(str(len(scale)), background_color=scale_bg_color, pad=(0, 0), font=('Lato', scale_subheader_size), key=SC_COUNT + str(i)) ], [ sg.Text('_' * mini_bar_size, pad=(0, 0), background_color=scale_bg_color, font=('Lato', mini_bar_font_size), text_color=mini_bar_color) ], [ sg.Text(scale_notes, background_color=scale_bg_color, font=('Lato', scale_list_font_size), size=(scale_list_size, 1), key=SC_NOTES + str(i)), sg.Button('View as PDF', button_color=('white', button_pdf_color), enable_events=True, key=SC_PDF_BTN + str(i)), sg.Button('Load in MuseScore', button_color=('white', button_muse_color), enable_events=True, key=SC_MUSE_BTN + str(i)) ]] # Append this scale as a column to the scale_layout. scale_layout.append([ sg.Column(this_scale, background_color=scale_bg_color, pad=(0, 10), key=SC_COLUMN + str(i)) ]) # TODO: Auto-Refresh by groups of 10 (Use Generator) # For now, break after 10 scales have loaded. if i > self._max_scale_display: break # Display to use when no scales are found (hidden by default) no_scales_found = [ sg.Text('\nNo scales found. Try revising your search.', font=('Lato', 24), key=SC_EMPTY, size=(58, 3), justification='center', visible=False, background_color=scale_bg_color) ] # The scrollable scale output column (hidden if no scales found) scales_display = [ sg.Column(scale_layout, key=SC_MAIN, scrollable=True, visible=True, vertical_scroll_only=True) ] # Vertical bar display vertical_bar1 = [sg.Text('_' * adjusted_full)] vertical_bar2 = [sg.Text('_' * adjusted_full)] # Build the GUI layout row by row from above defined rows. layout = [ layout_one, vertical_bar1, layout_two, vertical_bar2, no_scales_found, scales_display ] # Attach the GUI Layout to the window and add a title. window = sg.Window('Scale Explorer v1.0', layout, default_element_size=(half_size, 1)) # Event Handler loop. while True: # Read in any event and values from elements that are registered. event, values = window.read() # If the user exits, quit the program. if event in (None, 'Exit'): break # If user selected a new key, update the checkbox displays to reflect the new key. if R1_KEY in event: self.update_note_selections(values[event], window) # TODO: If user pressed the PDF button, prepare scale as export to PDF. if SC_PDF_BTN in event: self.export_scale(event, values, LILYPDF) # If user pressed the MuseScore button, prepare scale for export to MuseScore. if SC_MUSE_BTN in event: self.export_scale(event, values) # Use current event-enabled element states to update the GUI (selected key will be updated already). self.update_gui(window, values) window.close()
def PlayGame(): menu_def = [ ['&File', ['&Open PGN File', 'E&xit']], ['&Help', '&About...'], ] # sg.SetOptions(margins=(0,0)) sg.ChangeLookAndFeel('GreenTan') # create initial board setup psg_board = copy.deepcopy(initial_board) # the main board display layout board_layout = [[sg.T(' ')] + [ sg.T('{}'.format(a), pad=((23, 27), 0), font='Any 13') for a in 'abcdefgh' ]] # loop though board and create buttons with images for i in range(8): row = [sg.T(str(8 - i) + ' ', font='Any 13')] for j in range(8): piece_image = images[psg_board[i][j]] row.append(render_square(piece_image, key=(i, j), location=(i, j))) row.append(sg.T(str(8 - i) + ' ', font='Any 13')) board_layout.append(row) # add the labels across bottom of board board_layout.append([sg.T(' ')] + [ sg.T('{}'.format(a), pad=((23, 27), 0), font='Any 13') for a in 'abcdefgh' ]) # setup the controls on the right side of screen openings = ('Any', 'Defense', 'Attack', 'Trap', 'Gambit', 'Counter', 'Sicillian', 'English', 'French', 'Queen\'s openings', 'King\'s Openings', 'Indian Openings') board_controls = [ [sg.RButton('New Game', key='New Game'), sg.RButton('Draw')], [sg.RButton('Resign Game'), sg.RButton('Set FEN')], [sg.RButton('Player Odds'), sg.RButton('Training')], [sg.Drop(openings), sg.Text('Opening/Style')], [sg.CBox('Play As White', key='_white_')], [ sg.Drop([2, 3, 4, 5, 6, 7, 8, 9, 10], size=(3, 1), key='_level_'), sg.Text('Difficulty Level') ], [sg.Text('Move List')], [ sg.Multiline([], do_not_clear=True, autoscroll=True, size=(15, 10), key='_movelist_') ], ] # layouts for the tabs controls_layout = [[ sg.Text('Performance Parameters', font='_ 20') ], [sg.T('Put stuff like AI engine tuning parms on this tab')]] statistics_layout = [[sg.Text('Statistics', font=('_ 20'))], [sg.T('Game statistics go here?')]] board_tab = [[sg.Column(board_layout)]] # the main window layout layout = [[sg.Menu(menu_def, tearoff=False)], [ sg.TabGroup([[ sg.Tab('Board', board_tab), sg.Tab('Controls', controls_layout), sg.Tab('Statistics', statistics_layout) ]], title_color='red'), sg.Column(board_controls) ], [sg.Text('Click anywhere on board for next move', font='_ 14')]] window = sg.Window('Chess', default_button_element_size=(12, 1), auto_size_buttons=False, icon='kingb.ico').Layout(layout) filename = sg.PopupGetFile('\n'.join(( 'To begin, set location of AI EXE file', 'If you have not done so already, download the engine', 'Download the StockFish Chess engine at: https://stockfishchess.org/download/' )), file_types=(('Chess AI Engine EXE File', '*.exe'), )) if filename is None: sys.exit() engine = chess.uci.popen_engine(filename) engine.uci() info_handler = chess.uci.InfoHandler() engine.info_handlers.append(info_handler) board = chess.Board() move_count = 1 move_state = move_from = move_to = 0 # ---===--- Loop taking in user input --- # while not board.is_game_over(): if board.turn == chess.WHITE: engine.position(board) # human_player(board) move_state = 0 while True: button, value = window.Read() if button in (None, 'Exit'): exit() if button == 'New Game': sg.Popup( 'You have to restart the program to start a new game... sorry....' ) break level = value['_level_'] if type(button) is tuple: if move_state == 0: move_from = button row, col = move_from piece = psg_board[row][col] # get the move-from piece button_square = window.FindElement(key=(row, col)) button_square.Update(button_color=('white', 'red')) move_state = 1 elif move_state == 1: move_to = button row, col = move_to if move_to == move_from: # cancelled move color = '#B58863' if (row + col) % 2 else '#F0D9B5' button_square.Update(button_color=('white', color)) move_state = 0 continue picked_move = '{}{}{}{}'.format( 'abcdefgh'[move_from[1]], 8 - move_from[0], 'abcdefgh'[move_to[1]], 8 - move_to[0]) if picked_move in [ str(move) for move in board.legal_moves ]: board.push(chess.Move.from_uci(picked_move)) else: print('Illegal move') move_state = 0 color = '#B58863' if ( move_from[0] + move_from[1]) % 2 else '#F0D9B5' button_square.Update(button_color=('white', color)) continue psg_board[move_from[0]][move_from[ 1]] = BLANK # place blank where piece was psg_board[row][ col] = piece # place piece in the move-to square redraw_board(window, psg_board) move_count += 1 window.FindElement('_movelist_').Update(picked_move + '\n', append=True) break else: engine.position(board) best_move = engine.go(searchmoves=board.legal_moves, depth=level, movetime=(level * 100)).bestmove move_str = str(best_move) from_col = ord(move_str[0]) - ord('a') from_row = 8 - int(move_str[1]) to_col = ord(move_str[2]) - ord('a') to_row = 8 - int(move_str[3]) window.FindElement('_movelist_').Update(move_str + '\n', append=True) piece = psg_board[from_row][from_col] psg_board[from_row][from_col] = BLANK psg_board[to_row][to_col] = piece redraw_board(window, psg_board) board.push(best_move) move_count += 1 sg.Popup('Game over!', 'Thank you for playing')
def __init__(self): # GUI Interface Start print('Startup up...') layout = [[sg.Text('Please enter the following parameters')], [ sg.Text('Video Path', size=(25, 1)), sg.InputText(key='VIDEOPATH'), sg.FileBrowse() ], [ sg.Text('Save to:', size=(25, 1)), sg.InputText(key='SAVE'), sg.FolderBrowse() ], [sg.Text('Day', size=(25, 1)), sg.InputText(key='DAY')], [ sg.Text('First Tissue', size=(25, 1)), sg.InputText(key='FIRSTTISSUE') ], [ sg.Text('Last Tissue', size=(25, 1)), sg.InputText(key='LASTTISSUE') ], [ sg.Text('Pacing Frequency', size=(25, 1)), sg.InputText(key='PACINGFREQ') ], [ sg.Text('Electrode Spacing', size=(25, 1)), sg.InputText('0', key='ELECTRODESPACING') ], [ sg.Text('Pacing Voltage', size=(25, 1)), sg.InputText('12', key='PACINGVOLT') ], [ sg.Text('Excitation Threshold', size=(25, 1)), sg.InputText('12', key='EXCITTHRESH') ], [ sg.Text('Calibration Distance (mm)', size=(25, 1)), sg.InputText('18', key='CALIBDIST') ], [ sg.Text('Frame Width', size=(25, 1)), sg.InputText('2000', key='FRAMEWIDTH') ], [ sg.Text('Group Name', size=(25, 1)), sg.InputText('need to work on this', key='GROUPNAME') ], [ sg.Text('Group Number', size=(25, 1)), sg.InputText('this too', key='GROUPNUMBER') ], [ sg.Text('Tracker', size=(25, 1)), sg.Drop(key='TRACKER', values=('csrt', 'kcf', 'mil', 'boosting', 'tld', 'medianflow', 'mosse'), size=(25, 1)) ], [sg.Submit(), sg.Cancel()]] # Show to GUI window window = sg.Window('Tracking GUI', layout) # Read the window, values is a dictionary with the values event, values = window.Read() window.Close() # Turn the numebrs into numbers instead of text intergerize = ['FIRSTTISSUE', 'LASTTISSUE', 'FRAMEWIDTH', 'DAY'] floaterize = [ 'PACINGFREQ', 'ELECTRODESPACING', 'PACINGVOLT', 'EXCITTHRESH', 'CALIBDIST' ] for item in intergerize: values[item] = int(values[item]) for item in floaterize: values[item] = float(values[item]) # Call the tracker. From trackingmod MultiTissueTracker(values)
def calculator_window(): kt = False kp = False sg.theme('Dark Amber 5') refrigerant_list = [['R-134A'], ['water'], ['steam'], ['dheeresh'], ['saransh']] pressure_units = [['Pa'], ['Bar'], ['mmHg'], ['kg/m^2'], ['atm'], ['torr'], ['lbf/inch^2']] temperature_units = [['celcius'], ['Kelvin'], ['Fahrenheit']] layout_2 = [[sg.Menu(menu_def, tearoff=False, pad=(200, 1))], [ sg.Text('WELCOME', size=(40, 1), justification='center', font=("Algerian", 25)) ], [ sg.Drop( refrigerant_list, size=(20, 2), auto_size_text=True, enable_events=True, default_value="select the refrigerant", font=("Calibri", 20), ) ], [ sg.Checkbox('Pressure', size=(20, 2), auto_size_text=True, enable_events=True, default=False, key='Pressure'), sg.Checkbox('Temperature', size=(20, 2), auto_size_text=True, enable_events=True, default=False, key='Temperature') ], [ sg.Input(default_text="enter the values", size=(25, 1), font=("Algerian", 25), key="__IN__"), sg.Drop(temperature_units, size=(10, 1), auto_size_text=True, enable_events=True, font=("Calibri", 20), visible=False, key="units") ], [sg.Button("EXIT"), sg.Button("PREVIOUS")]] window_2 = sg.Window(title="CALCULATOR", layout=layout_2, resizable=True, right_click_menu=right_click_menu, default_button_element_size=(40, 2), default_element_size=(40, 5), auto_size_buttons=True, auto_size_text=True, element_justification='left') while True: event, values = window_2.read() if event == "PREVIOUS": window_2.close() callback() break elif event == "Temperature": layout_2 = [[sg.Menu(menu_def, tearoff=False, pad=(200, 1))], [ sg.Text('WELCOME', size=(40, 1), justification='center', font=("Algerian", 25)) ], [ sg.Drop( refrigerant_list, size=(20, 2), auto_size_text=True, enable_events=True, default_value="select the refrigerant", font=("Calibri", 20), ) ], [ sg.Checkbox('Pressure', size=(20, 2), auto_size_text=True, enable_events=True, default=False, key='Pressure'), sg.Checkbox('Temperature', size=(20, 2), auto_size_text=True, enable_events=True, default=True, key='Temperature') ], [ sg.Input(default_text="enter the values", size=(25, 1), font=("Algerian", 25), key="__IN__"), sg.Drop(temperature_units, size=(10, 1), auto_size_text=True, enable_events=True, font=("Calibri", 20), visible=True, key="units") ], [sg.Button("EXIT"), sg.Button("PREVIOUS")]] window_2 = sg.Window(title="CALCULATOR", layout=layout_2, resizable=True, right_click_menu=right_click_menu, default_button_element_size=(40, 2), default_element_size=(40, 5), auto_size_buttons=True, auto_size_text=True, element_justification='left') elif event == "Pressure": window_2['Temperature'].Update(False) layout_2 = [[sg.Menu(menu_def, tearoff=False, pad=(200, 1))], [ sg.Text('WELCOME', size=(40, 1), justification='center', font=("Algerian", 25)) ], [ sg.Drop( refrigerant_list, size=(20, 2), auto_size_text=True, enable_events=True, default_value="select the refrigerant", font=("Calibri", 20), ) ], [ sg.Checkbox('Pressure', size=(20, 2), auto_size_text=True, enable_events=True, default=True, key='Pressure'), sg.Checkbox('Temperature', size=(20, 2), auto_size_text=True, enable_events=True, default=False, key='Temperature') ], [ sg.Input(default_text="enter the values", size=(25, 1), font=("Algerian", 25), key="__IN__"), sg.Drop(pressure_units, size=(10, 1), auto_size_text=True, enable_events=True, font=("Calibri", 20), visible=True, key="units") ], [sg.Button("EXIT"), sg.Button("PREVIOUS")]] window_2 = sg.Window(title="CALCULATOR", layout=layout_2, resizable=True, right_click_menu=right_click_menu, default_button_element_size=(40, 2), default_element_size=(40, 5), auto_size_buttons=True, auto_size_text=True, element_justification='left') elif event == "EXIT" or event == sg.WIN_CLOSED: break
pbars, epi_count = init_progressbars() progress_panel = sg.Frame(title='progress', key='progress_panel', layout= [ [sg.Text('Steps per Rollout'), sg.Text('0000000', key='num_steps_per_rollout')], [sg.ProgressBar(config.gatherer.num_steps_per_rollout, orientation='h', size=(20, 20), key='trainer'), sg.Text('000000', key='wallclock')], pbars, epi_count ] ) """ RUN PANEL """ env_droplist_value = ['all', 'latest'] + [c for c in config_list] env_droplist = sg.Drop(values=env_droplist_value, auto_size_text=True, key='FilterRun', enable_events=True, default_value='latest') class PolicyTable: def __init__(self, policy_db): self.best = [] self.policy_db = policy_db latest_run = self.policy_db.latest_run() if latest_run is not None: runs = [latest_run.run] for run in runs: result = self.policy_db.best(run) if len(result) > 0: row = result.get() self.best.append([run.ljust(25), row.stats['ave_reward_episode']]) else:
[sg.T('', **bw), sg.T('Global', **bw)], [sg.T('Yrs to Normal Spreads', **bw), sg.Combo(values=[0,1,2,3,4,5,6,7,8,9,10], default_value=5, **bw, key='spread_norm_yrs')], [sg.T('_'*190)]] # %% # Equity Tab equity_len = len(list(equity_us_base.keys())) equity_nonus_len = len(list(equity_nonus_base.keys())) equity_layout = [[sg.T('Asset Class', size=(35,1)), sg.T('Bloomberg Code', size=(17,1)), sg.T('Beta Relative To', size=(35,1))]] +\ [[sg.In(list(equity_us_base.keys())[i], disabled=True, size=(40,1), key='equity_us_name' + str(i)), sg.In(list(equity_us_base.values())[i][0], size=(20,1), key='equity_us_code' + str(i)), sg.Drop(values=beta_equity, default_value=list(equity_us_base.values())[i][1], size=(37,1), key='equity_us_beta' + str(i))] for i in range(1, equity_len)] +\ [[sg.In(size=(40,1), key='equity_us_name' + str(equity_len)), sg.In(size=(20,1), key='equity_us_code' + str(equity_len)), sg.Drop(values=beta_equity, default_value='', size=(37,1), key='equity_us_beta' + str(equity_len))]] +\ [[sg.In(size=(40,1), key='equity_us_name' + str(equity_len+1)), sg.In(size=(20,1), key='equity_us_code' + str(equity_len+1)), sg.Drop(values=beta_equity, default_value='', size=(37,1), key='equity_us_beta' + str(equity_len+1))]] equity_nonus_layout = [[sg.T('Asset Class', size=(35,1)), sg.T('Bloomberg Code', size=(17,1)), sg.T('Beta Relative To', size=(35,1))]] +\ [[sg.In(list(equity_nonus_base.keys())[i], disabled=True, size=(40,1), key='equity_nonus_name' + str(i)), sg.In(list(equity_nonus_base.values())[i][0], size=(20,1), key='equity_nonus_code' + str(i)), sg.Drop(values=beta_equity, default_value=list(equity_nonus_base.values())[i][1], size=(37,1), key='equity_nonus_beta' + str(i))] for i in range(1, equity_nonus_len)] +\ [[sg.In(size=(40,1), key='equity_nonus_name' + str(equity_nonus_len)), sg.In(size=(20,1), key='equity_nonus_code' + str(equity_nonus_len)), sg.Drop(values=beta_equity, default_value='', size=(37,1), key='equity_nonus_beta' + str(equity_nonus_len))]] +\ [[sg.In(size=(40,1), key='equity_nonus_name' + str(equity_nonus_len+1)), sg.In(size=(20,1), key='equity_nonus_code' + str(equity_nonus_len+1)),
def user_interface(): #------------- Layout settings ------------ layout = [ [ #sg.Text('Screens: ', size=(12,1)),*screen_checkboxes(), sg.Checkbox("Colors", key="Colors", default=True, visible=False) ], [ sg.Button('Initializing', key='TOGGLE AUTO CAPTURE', tooltip="Toggle the AutoPhoto"), sg.Text('', size=(2, 1), key='timer', text_color=theme_items['BUTTON'][0], background_color=theme_items['BUTTON'][1]), sg.Text(key="Last Image", size=(12, 2)) ], [ sg.Text('Frequency', size=(10, 1)), sg.Drop( values=r_capture_freq_map_keys, default_value=capture_freq_map_keys[5], #Every 2 min readonly=True, key="Rate", size=(12, 1)) ], [ sg.Button(image_filename="ressources/icon-camera.png", image_size=BUTTON_ICON_SIZE, key='Capture', tooltip="Take a screenshot now"), sg.Checkbox("& Open", key='Viewer', default=True, visible=False), #sg.Button('Capture Region', key='Capture Region'), sg.Button(image_filename="ressources/icon-film.png", image_size=BUTTON_ICON_SIZE, key="MakeVideo", tooltip="Make a video of today's screenshots"), sg.Button(image_filename="ressources/icon-folder-mini.png", image_size=BUTTON_ICON_SIZE, key="explorer_folder", tooltip="Open the screenshots folder") ], [ sg.Button(image_filename="ressources/icon-report-mini.png", image_size=BUTTON_ICON_SIZE, key='summary', tooltip="Print a summary of your activity"), sg.Button(image_filename="ressources/icon-csv.png", image_size=BUTTON_ICON_SIZE, key='csv_report', tooltip="Export the summary to a .csv file"), sg.Button(image_filename="ressources/icon-bird-button.png", image_size=BUTTON_ICON_SIZE, key='Bird', tooltip="Start an auto-typing robot", visible=True) ], [ sg.Text('_' * 25, text_color=theme_items['BUTTON'][0]), sg.Button(image_filename="ressources/icon-exit-mini.png", image_size=BUTTON_ICON_SIZE, tooltip="Close", key='Exit') ], ] advanced_menu_def = [ 'BLANK', [ '&Record', '&Screenshot', ['Full &Screen', '&Region'], '---', 'Settings', [ 'Colors', ['On::Colors', 'Off::Colors'], 'Screens', ['[1]', '[2]', '[1][2]'], 'Open Paint w/ capture', ['On::Paint', 'Off::Paint'] ], '&Bird', '&Properties', 'E&xit', ] ] menu_def = ['BLANK', ['E&xit']] tray = sg.SystemTray(menu=menu_def, filename=LOGO_ON) window = sg.Window( "Activity Report", layout, keep_on_top=True, grab_anywhere=True, #no_titlebar=True, return_keyboard_events=True, finalize=True, icon="ressources/icon-camera.png", titlebar_background_color=theme_items['BACKGROUND']) # Initial state last_capture = "" count_auto_capture = 0 control = Control() control.start() global Bird Bird = False startMousePosition = [] endMousePosition = [] capturing_region = False state_left = 0 ############ Main loop ############ while True: timestamp = datetime.now() formatted_timestamp = timestamp.strftime("%y-%m-%d_%a_%H-%M-%S") YYMMDD, WeekDay, HHMMSS = formatted_timestamp.split('_') if not capturing_region: event, inputs = window.Read(timeout=100) #Most of the time tray_menu_item = tray.Read(timeout=100) elif capturing_region: event, inputs = window.Read( 1 ) #We lower the timeout to avoid lag when getting Mouse coordinates while Capturing Region #tray_menu_item = tray.Read(1) if DEBUG and event != "__TIMEOUT__": print(event) if event in (sg.WIN_CLOSED, 'Exit') or tray_menu_item == "Exit": break #---------------- Display Timer -----------------------------# window.Elem('timer').Update(timestamp.second, text_color=theme_items['BUTTON'][0], background_color=theme_items['BUTTON'][1]) #-------------- Auto - Capture -------------------- if control.capturing: window['TOGGLE AUTO CAPTURE'].Update('AutoPhoto : ON', button_color=("white", "green")) autocapture_frequency = capture_frequency_map[inputs['Rate']] if (event == 'TOGGLE AUTO CAPTURE' or tray_menu_item == "__ACTIVATED__") and not control.capturing: tray.close() tray = sg.SystemTray(menu=menu_def, filename=LOGO_ON) control.start() window['TOGGLE AUTO CAPTURE'].Update('AutoPhoto : ON', button_color=("white", "green")) elif (event == 'TOGGLE AUTO CAPTURE' or tray_menu_item == "__ACTIVATED__") and control.capturing: tray.close() tray = sg.SystemTray(menu=menu_def, filename=LOGO_OFF) control.stop() window['TOGGLE AUTO CAPTURE'].Update("AutoPhoto : OFF", button_color=("white", "red")) if control.capturing: elapsed_time_from_start = control.start_time - timestamp elapsed_time_from_start_rounded = int( elapsed_time_from_start.total_seconds()) if elapsed_time_from_start_rounded % autocapture_frequency == 0: screens = get_n_screens(inputs) previous_capture = last_capture last_capture = capture(f"{AUTOCAPTURE_DIR}/{YYMMDD}/{HHMMSS}", colors=inputs["Colors"], screens=screens) """if last_capture: if equal_size(previous_capture, last_capture): if FILTER_OUT_SAME_SIZE_CAPTURE : os.remove(last_capture) """ count_auto_capture += 1 try: last_capture_info = os.path.basename( last_capture) + '\n' + print_file_size(last_capture) window['Last Image'].Update(last_capture_info) if sys.platform == "win32": window.Elem('timer').Update( '⚫', text_color='red', background_color=theme_items['BACKGROUND']) else: window.Elem('timer').Update( 'O', text_color='red', background_color=theme_items['BACKGROUND']) except AttributeError: pass # Stop if session is closed (method can be improved) if control.capturing and timestamp.second == 1 and is_login_screen_image( os.path.join(AUTOCAPTURE_DIR, YYMMDD), LOGIN_SCREEN_SIZE): control.stop() #-------------- Manual - Capture -------------------- if event == 'Capture': last_capture = capture(os.path.join(AUTOCAPTURE_DIR, HHMMSS)) last_capture_info = os.path.basename( last_capture) + " - " + print_file_size(last_capture) window['Last Image'].Update(last_capture_info) if inputs['Viewer'] == True: window.Minimize() start_paint(last_capture) else: if sys.platform == "win32": window.Elem('timer').Update( '⚫', text_color='red', background_color=theme_items['BACKGROUND']) else: window.Elem('timer').Update( 'O', text_color='red', background_color=theme_items['BACKGROUND']) #-------------- Capture Region -------------------- """ if event == "Capture Region": capturing_region= True window["Capture Region"].Update("Select region", button_color=("white", "orange")) if capturing_region: if not startMousePosition: step, value = get_region_to_capture() if step == 'init': startMousePosition = value endMousePosition = [] else: step, value = get_region_to_capture() if step == 'end': endMousePosition = value capturing_region= False window["Capture Region"].Update("Capture Region", button_color=sg.LOOK_AND_FEEL_TABLE[THEME]['BUTTON']) if startMousePosition != [] and endMousePosition != []: screens = get_n_screens(inputs) bbox = startMousePosition + endMousePosition #(0, 0, 3840, 1080) startMousePosition = [] endMousePosition = [] time.sleep(1) path_to_screenshot = capture(f"{CAPTURE_DIR}/{HHMMSS}", region=bbox, screens=screens) if inputs['Viewer'] == True: start_paint(path_to_screenshot) """ #--------------- Bird ----------------------- if control.bird_ticking and event != "__TIMEOUT__": control.bird_ticking = False window.Elem("Bird").Update(button_color=theme_items['BUTTON']) elif event == "Bird" and control.bird_ticking == False: control.bird_ticking = True if control.bird_ticking and timestamp.second in range( 0, 60, 2) and "Bird Thread" not in [ t.name for t in threading.enumerate() ]: bird_thread = start_bird(control) control.bird_ticking = True window.Elem("Bird").Update(button_color=('white', 'red')) #-------------- Build Video --------------------------# if event == "MakeVideo": t1 = threading.Thread(target=make_video, args=(f"{AUTOCAPTURE_DIR}/{YYMMDD}", )) t1.start() #-------------- Build CSV Report --------------------------# if event == "csv_report": csv_t = threading.Thread(target=count_work_hours.main, kwargs=({ "export": 'csv' })) csv_t.start() #-------------- Print Summary --------------------------# if event == "summary": print_summary = threading.Thread(target=count_work_hours.main) print_summary.start() ##-------------- Convenience events ------------------------------# if event == "explorer_folder": if sys.platform == "win32": cmd(['explorer', f'{AUTOCAPTURE_DIR}\\{YYMMDD}']) elif sys.platform == "darwin": cmd(["open", f'{AUTOCAPTURE_DIR}/{YYMMDD}']) else: print('Unsupported feature. Open ', CAPTURE_DIR) """ if event == "explorer_folder" or count_auto_capture == 500: dir_size = print_dir_size(AUTOCAPTURE_DIR) window.Elem("Disk size").Update(f"{dir_size}")""" return window, tray
def gui_window(last_event): user_dict = None today = datetime.today() today_list = [today.year, today.month, today.day, today.hour, today.minute] possible_events = ('Noon Sea', 'Noon River', 'Noon Port', 'Arrival', 'Departure', 'BOSP', 'EOSP', 'Drop Anchor', 'Anchor Aweigh', 'Bunkering') if last_event is None: voyage_no = location = time_zone = next_port = dest_tz = master = cargo_rob = ballast_rob = bilges = '' latitude = longitude = {'degrees': '', 'minutes': '', 'hemisphere': ''} last_event = [''] * 19 else: voyage_no = last_event[0] time_zone = round(float(last_event[2]), 1) next_port = last_event[8] dest_tz = round(float(last_event[10]), 1) master = last_event[11] cargo_rob = last_event[12] ballast_rob = last_event[17] location = last_event[18] bilges = last_event[19] latitude = geoposition_split(last_event[20]) longitude = geoposition_split(last_event[21]) last_eta_lt = check_datetime_data_present(last_event[9], dest_tz) c_ops_comm_lt = check_datetime_data_present(last_event[13], time_zone) c_ops_compl_lt = check_datetime_data_present(last_event[14], time_zone) etc = check_datetime_data_present(last_event[15], 0) etd = check_datetime_data_present(last_event[16], 0) general_info = [ [ sg.Text('Voyage:', size=(35, 1)), sg.InputText(voyage_no, size=(20, 1), key='voy') ], # 0 [ sg.Text('Event:', size=(35, 1)), sg.Drop(values=possible_events, size=(20, 1), key='event') ], [ sg.Text('Location:', size=(35, 1)), sg.InputText(location, size=(20, 1), key='location') ], [sg.Text('Local Date/Time:', size=(35, 1))], time_read('local_time', today_list), [ sg.Text('Time Zone: (HH,H - if W):', size=(35, 1)), sg.InputText(time_zone, size=(20, 1), key='tz') ], [ sg.Text('Latitude:', size=(35, 1)), sg.InputText(latitude['degrees'], size=(5, 1), key='lat_deg'), sg.InputText(latitude['minutes'], size=(5, 1), key='lat_min'), sg.Drop(default_value=latitude['hemisphere'], values=('', 'N', 'S'), size=(2, 1), key='lat_hemisphere') ], [ sg.Text('Longitude:', size=(35, 1)), sg.InputText(longitude['degrees'], size=(5, 1), key='long_deg'), sg.InputText(longitude['minutes'], size=(5, 1), key='long_min'), sg.Drop(default_value=longitude['hemisphere'], values=('', 'E', 'W'), size=(2, 1), key='long_hemisphere') ] ] voy_info = [ [ sg.Text('Pressure:', size=(35, 1)), sg.InputText(size=(20, 1), key='pressure') ], [ sg.Text('Temp:', size=(35, 1)), sg.InputText(size=(20, 1), key='airtemp') ], [ sg.Text('Wind direction:', size=(35, 1)), sg.InputText(size=(20, 1), key='wind_dir') ], [ sg.Text('Wind force in kts:', size=(35, 1)), sg.InputText(size=(20, 1), key='wind_force') ], [ sg.Text('Sea height:', size=(35, 1)), sg.InputText(size=(20, 1), key='sea_height') ], [ sg.Text('Sea direction:', size=(35, 1)), sg.InputText(size=(20, 1), key='sea_dir') ], [ sg.Text('Swell height:', size=(35, 1)), sg.InputText(size=(20, 1), key='swell') ], [ sg.Text('Course made good:', size=(35, 1)), sg.InputText(size=(20, 1), key='cog') ], [ sg.Text('Log distance from last event:', size=(35, 1)), sg.InputText(size=(20, 1), key='log') ], [ sg.Text('GPS distance from last event:', size=(35, 1)), sg.InputText(size=(20, 1), key='gps_dist') ], [ sg.Text('Next port:', size=(35, 1)), sg.InputText(next_port, size=(20, 1), key='next_port') ], [sg.Text('ETA:', size=(35, 1))], time_read('eta_lt', last_eta_lt), [ sg.Text("Destinantion's Time Zone: (HH,H - if W):", size=(35, 1)), sg.InputText(dest_tz, size=(20, 1), key='dest_tz') ], [ sg.Text('Bilges:', size=(35, 1)), sg.InputText(bilges, size=(20, 1), key='bilges') ], [ sg.Text('Master:', size=(35, 1)), sg.InputText(master, size=(20, 1), key='master') ], [sg.Text('Remarks:', size=(35, 1))], [sg.Multiline(size=(57, 5), key='remarks')], [sg.Text('Calculated values for navigation & weather:', size=(35, 1))], # Voyage calculations to be made: [ sg.Text('Time from last event:', size=(35, 1)), sg.InputText(key='time_from_last', size=(20, 1)) ], [ sg.Text('Average GPS speed from last event:', size=(35, 1)), sg.InputText(key='avg_gps_spd', size=(20, 1)) ], [ sg.Text('Average log speed from last event:', size=(35, 1)), sg.InputText(key='avg_log_spd', size=(20, 1)) ], [ sg.Text('Current:', size=(35, 1)), sg.InputText(key='current', size=(20, 1)) ], [ sg.Text('Wind force in Beaufort scale:', size=(35, 1)), sg.InputText(key='wind_b', size=(20, 1)) ], [ sg.Text('Total steaming time:', size=(35, 1)), sg.InputText(key='voy_time', size=(20, 1)) ], [ sg.Text('Total GPS distance:', size=(35, 1)), sg.InputText(key='voy_dist', size=(20, 1)) ], [ sg.Text('Voyage average speed:', size=(35, 1)), sg.InputText(key='voy_avg_spd', size=(20, 1)) ], [ sg.Text('Total log distance:', size=(35, 1)), sg.InputText(key='voy_log_dist', size=(20, 1)) ], [ sg.Text('Remaining distance:', size=(35, 1)), sg.InputText(key='rem_dist', size=(20, 1)) ], [ sg.Text('ETA (destination ZT) with present speed:', size=(35, 1)), sg.Text('', key='real_eta', size=(20, 1)) ], [ sg.Text('Speed required for given ETA:', size=(35, 1)), sg.Text('', key='speed_req', size=(20, 1)) ] ] er_info = [ [ sg.Text('HFO ROB:', size=(35, 1)), sg.InputText(er_excel['~HFOROB~'], size=(20, 1), key='HFOROB') ], [ sg.Text('MDO ROB:', size=(35, 1)), sg.InputText(er_excel['~MDOROB~'], size=(20, 1), key='MDOROB') ], [ sg.Text('Lube oil (cylinders) ROB:', size=(35, 1)), sg.InputText(er_excel['~LOCYLROB~'], size=(20, 1), key='LOCYLROB') ], [ sg.Text('Lube oil (Main Engine) ROB:', size=(35, 1)), sg.InputText(er_excel['~LOMEROB~'], size=(20, 1), key='LOMEROB') ], [ sg.Text('Lube oil (Aux engines) ROB:', size=(35, 1)), sg.InputText(er_excel['~LOAUXROB~'], size=(20, 1), key='LOAUXROB') ], [ sg.Text('Lube oil (Total) ROB:', size=(35, 1)), sg.InputText(er_excel['~LOTOTALROB~'], size=(20, 1), key='LOTOTALROB') ], [ sg.Text('ME HFO consumption:', size=(35, 1)), sg.InputText(er_excel['~MEHFOCONS~'], size=(20, 1), key='MEHFOCONS') ], [ sg.Text('ME MDO consumption:', size=(35, 1)), sg.InputText(er_excel['~MEMDOCONS~'], size=(20, 1), key='MEMDOCONS') ], [ sg.Text('Aux engines HFO consumption:', size=(35, 1)), sg.InputText(er_excel['~AUXHFOCONS~'], size=(20, 1), key='AUXHFOCONS') ], [ sg.Text('Aux engines MDO consumption:', size=(35, 1)), sg.InputText(er_excel['~AUXMDOCONS~'], size=(20, 1), key='AUXMDOCONS') ], [ sg.Text('Boiler HFO consumption:', size=(35, 1)), sg.InputText(er_excel['~BOILERHFOCONS~'], size=(20, 1), key='BOILERHFOCONS') ], [ sg.Text('Boiler MDO consumption:', size=(35, 1)), sg.InputText(er_excel['~BOILERMDOCONS~'], size=(20, 1), key='BOILERMDOCONS') ], [ sg.Text('Total HFO consumption:', size=(35, 1)), sg.InputText(er_excel['~TOTALHFOCONS~'], size=(20, 1), key='TOTALHFOCONS') ], [ sg.Text('Total MDO consumption:', size=(35, 1)), sg.InputText(er_excel['~TOTALMDOCONS~'], size=(20, 1), key='TOTALMDOCONS') ], [ sg.Text('Lube oil consumption (cylinders):', size=(35, 1)), sg.InputText(er_excel['~LOCYLCONS~'], size=(20, 1), key='LOCYLCONS') ], [ sg.Text('Lube oil consumption (ME):', size=(35, 1)), sg.InputText(er_excel['~LOMECONS~'], size=(20, 1), key='LOMECONS') ], [ sg.Text('Lube oil consumption (aux engines):', size=(35, 1)), sg.InputText(er_excel['~LOAUXCONS~'], size=(20, 1), key='LOAUXCONS') ], [ sg.Text('Lube oil total consumption:', size=(35, 1)), sg.InputText(er_excel['~TOTALLOCONS~'], size=(20, 1), key='TOTALLOCONS') ], [ sg.Text('Average RPM:', size=(35, 1)), sg.InputText(er_excel['~RPM~'], size=(20, 1), key='RPM') ], [ sg.Text('ME distance:', size=(35, 1)), sg.InputText(er_excel['~MEDIST~'], size=(20, 1), key='MEDIST') ], [ sg.Text('ME speed:', size=(35, 1)), sg.InputText(er_excel['~MESPD~'], size=(20, 1), key='MESPD') ], [ sg.Text('Slip:', size=(35, 1)), sg.InputText(er_excel['~SLIP~'], size=(20, 1), key='SLIP') ], [ sg.Text('ME average kW:', size=(35, 1)), sg.InputText(er_excel['~MEKW~'], size=(20, 1), key='MEKW') ], [ sg.Text('ME total kWh:', size=(35, 1)), sg.InputText(er_excel['~MEKWH~'], size=(20, 1), key='MEKWH') ], [ sg.Text('ME load:', size=(35, 1)), sg.InputText(er_excel['~MELOAD~'], size=(20, 1), key='MELOAD') ], [ sg.Text('ME governor setting:', size=(35, 1)), sg.InputText(er_excel['~MEGOV~'], size=(20, 1), key='MEGOV') ], [ sg.Text('Aux engines total time:', size=(35, 1)), sg.InputText(check_float_value_present(er_excel['~AUXTIME~']), size=(20, 1), key='AUXTIME') ], [ sg.Text('Aux engines average kW:', size=(35, 1)), sg.InputText(er_excel['~AUXKW~'], size=(20, 1), key='AUXKW') ], [ sg.Text('Aux engines total kWh:', size=(35, 1)), sg.InputText(check_float_value_present(er_excel['~AUXKWH~']), size=(20, 1), key='AUXKWH') ], [ sg.Text('Fresh water ROB:', size=(35, 1)), sg.InputText(er_excel['~FWROB~'], size=(20, 1), key='FWROB') ], [ sg.Text('Fresh water produced:', size=(35, 1)), sg.InputText(er_excel['~FWPROD~'], size=(20, 1), key='FWPROD') ], [ sg.Text('Fresh water consumed:', size=(35, 1)), sg.InputText(er_excel['~FWCONS~'], size=(20, 1), key='FWCONS') ], [ sg.Text('Sludge tank content:', size=(35, 1)), sg.InputText(er_excel['~SLUDGETK~'], size=(20, 1), key='SLUDGETK') ], [ sg.Text('Oily bilge tank content:', size=(35, 1)), sg.InputText(er_excel['~OILYBILGETK~'], size=(20, 1), key='OILYBILGETK') ], [ sg.Text('Incinerator settling tank content:', size=(35, 1)), sg.InputText(er_excel['~INCINERATORSETTLINGTK~'], size=(20, 1), key='INCINERATORSETTLINGTK') ], [ sg.Text('Incinerator service tank content:', size=(35, 1)), sg.InputText(er_excel['~INCINERATORSERVICETK~'], size=(20, 1), key='INCINERATORSERVICETK') ], [ sg.Text('Bilge water tank content:', size=(35, 1)), sg.InputText(er_excel['~BILGEWATERTK~'], size=(20, 1), key='BILGEWATERTK') ], [ sg.Text('Sludge total:', size=(35, 1)), sg.InputText(er_excel['~SLUDGETOTAL~'], size=(20, 1), key='SLUDGETOTAL') ] ] cargo_info = [[ sg.Text('Cargo ops in progress:', size=(35, 1)), sg.Drop(key='if_cargo', values=('No', 'Yes'), size=(20, 1)) ], [sg.Text('Cargo ops commenced (LT):', size=(35, 1))], time_read('c_ops_comm', c_ops_comm_lt), [sg.Text('Cargo ops completed (LT):', size=(35, 1))], time_read('c_ops_compl', c_ops_compl_lt), [ sg.Text('Cargo ROB:', size=(35, 1)), sg.InputText(cargo_rob, key='cargo_rob', size=(20, 1)) ], [ sg.Text('Cargo loaded/discharged from last event:', size=(35, 1)), sg.InputText(key='cargo_daily', size=(20, 1)) ], [ sg.Text('Cargo to go:', size=(35, 1)), sg.InputText(key='cargo_to_go', size=(20, 1)) ], [ sg.Text('Ballast water ROB:', size=(35, 1)), sg.InputText(ballast_rob, key='ballast_rob', size=(20, 1)) ], [ sg.Text('Ballast water change from last event:', size=(35, 1)), sg.InputText(key='ballast_daily', size=(20, 1)) ], [ sg.Text('Number of shore cranes:', size=(35, 1)), sg.InputText(key='shore_cranes_no', size=(20, 1)) ], [ sg.Text('Number of ship cranes:', size=(35, 1)), sg.InputText(key='ship_cranes_no', size=(20, 1)) ], [sg.Text('Estimated time completion (LT):', size=(35, 1))], time_read('etc', etc), [sg.Text('Estimated time departure (LT):', size=(35, 1))], time_read('etd', etd)] noon_rep = [[ sg.Text('Here will go customisation of the reports data', size=(57, 5)) ], [sg.Button('Create reports')]] column = [ sg.TabGroup([[ sg.Tab('Nav info', voy_info), sg.Tab('Engine info', er_info), sg.Tab('Cargo Info', cargo_info), sg.Tab('Customise report', noon_rep) ]]) ], sg.ChangeLookAndFeel('SystemDefault') # Create the Window layout = [[sg.Frame('Mandatory Data', general_info)], [ sg.Button('Calculate'), sg.Button('Data Ready!'), sg.Button('Submit Event'), sg.Button('Quit') ], [sg.Column(column, scrollable=True, vertical_scroll_only=True)]] window = sg.Window('report_creator', resizable=True).Layout(layout) # Event Loop to process "events" and get the "values" of the inputs while True: event, values = window.read() if event in (None, 'Quit'): break if event == 'Calculate': time_local = datetime(int(values['local_time_year']), int(values['local_time_month']), int(values['local_time_day']), int(values['local_time_hour']), int(values['local_time_minute'])) time_utc = time_local - timedelta(hours=float(values['tz'])) eta_lt = datetime(int(values['eta_lt_year']), int(values['eta_lt_month']), int(values['eta_lt_day']), int(values['eta_lt_hour']), int(values['eta_lt_minute'])) eta_utc = eta_lt - timedelta(hours=float(values['dest_tz'])) if last_event == [''] * 19: time_from_last_seconds = hour_notation_to_seconds( values['time_from_last']) voy_time_seconds = time_from_last_seconds voy_dist = float( values['gps_dist']) if values['gps_dist'] != '' else 0 voy_log_dist = float( values['log']) if values['log'] != '' else 0 rem_dist = float( values['rem_dist']) if values['rem_dist'] != '' else 0 avg_gps_spd = voy_dist / (time_from_last_seconds / 3600) avg_log_spd = voy_log_dist / (time_from_last_seconds / 3600) else: time_from_last_seconds = ( time_utc - parser.parse(last_event[3])).total_seconds() last_voy_time = hour_notation_to_seconds(last_event[5]) voy_time_seconds = time_from_last_seconds + last_voy_time voy_dist = round( check_float_value_present(values['gps_dist']) + float(last_event[6]), 1) if values['gps_dist'] != '' else round( float(last_event[6]), 1) voy_log_dist = check_float_value_present( values['log']) + float( last_event[7]) if values['log'] != '' else float( last_event[7]) rem_dist = round( float(last_event[4]) - check_float_value_present(values['gps_dist'])) avg_gps_spd = round( check_float_value_present(values['gps_dist']) / (time_from_last_seconds / 3600), 1) avg_log_spd = round( check_float_value_present(values['log']) / (time_from_last_seconds / 3600), 1) voy_avg_spd = round(voy_dist / (voy_time_seconds / 3600), 1) time_from_last_display = seconds_to_hour_notation( time_from_last_seconds) voy_time_display = seconds_to_hour_notation(voy_time_seconds) current = round((avg_gps_spd - avg_log_spd), 2) wind_kts = check_int_value_present(values['wind_force']) if wind_kts < 1: wind_b = 0 elif 1 <= wind_kts <= 3: wind_b = 1 elif 4 <= wind_kts <= 6: wind_b = 2 elif 7 <= wind_kts <= 10: wind_b = 3 elif 11 <= wind_kts <= 16: wind_b = 4 elif 17 <= wind_kts <= 21: wind_b = 5 elif 22 <= wind_kts <= 27: wind_b = 6 elif 28 <= wind_kts <= 33: wind_b = 7 elif 34 <= wind_kts <= 40: wind_b = 8 elif 41 <= wind_kts <= 47: wind_b = 9 elif 48 <= wind_kts <= 55: wind_b = 10 elif 56 <= wind_kts <= 63: wind_b = 11 elif wind_kts <= 64: wind_b = 12 else: wind_b = 0 time_rem_hrs = rem_dist / avg_gps_spd if avg_gps_spd != 0 else 0 real_eta = time_utc + timedelta(hours=(time_rem_hrs + float(values['dest_tz']))) time_to_eta = eta_utc - time_utc speed_req = rem_dist / (time_to_eta.total_seconds() / 3600) hfo_rob = check_float_value_present(values['HFOROB']) mdo_rob = check_float_value_present(values['MDOROB']) me_hfo_cons = check_float_value_present(values['MEHFOCONS']) me_mdo_cons = check_float_value_present(values['MEMDOCONS']) aux_hfo_cons = check_float_value_present(values['AUXHFOCONS']) aux_mdo_cons = check_float_value_present(values['AUXMDOCONS']) boiler_hfo_cons = check_float_value_present( values['BOILERHFOCONS']) boiler_mdo_cons = check_float_value_present( values['BOILERMDOCONS']) total_hfo_cons = check_float_value_present(values['TOTALHFOCONS']) total_mdo_cons = check_float_value_present(values['TOTALMDOCONS']) lo_cyl_cons = check_int_value_present(values['LOCYLCONS']) lo_me_cons = check_int_value_present(values['LOMECONS']) lo_aux_cons = check_int_value_present(values['LOAUXCONS']) lo_total_cons = check_int_value_present(values['TOTALLOCONS']) rpm = check_float_value_present(values['RPM']) me_dist = check_float_value_present(values['MEDIST']) me_spd = check_float_value_present(values['MESPD']) me_kw = check_float_value_present(values['MEKW']) me_kwh = check_float_value_present(values['MEKWH']) aux_kw = check_float_value_present(values['AUXKW']) aux_kwh = check_float_value_present(values['AUXKWH']) slip = percentage(values['SLIP']) me_load = percentage(values['MELOAD']) me_gov = percentage(values['MEGOV']) if values['c_ops_comm_year'] != '': c_ops_comm_lt = datetime( check_int_value_present(values['c_ops_comm_year']), check_int_value_present(values['c_ops_comm_month']), check_int_value_present(values['c_ops_comm_day']), check_int_value_present(values['c_ops_comm_hour']), check_int_value_present(values['c_ops_comm_minute'])) c_ops_comm_utc = c_ops_comm_lt + timedelta( hours=float(values['dest_tz'])) if values['c_ops_compl_year'] != '': c_ops_compl_lt = datetime( check_int_value_present(values["c_ops_compl_year"]), check_int_value_present(values['c_ops_compl_month']), check_int_value_present(values['c_ops_compl_day']), check_int_value_present(values['c_ops_compl_hour']), check_int_value_present(values['c_ops_compl_minute'])) c_ops_compl_utc = c_ops_compl_lt + timedelta( hours=float(values['dest_tz'])) window.Element('time_from_last').Update(time_from_last_display) window.Element('avg_gps_spd').Update(avg_gps_spd) window.Element('avg_log_spd').Update(avg_log_spd) window.Element('current').Update(current) window.Element('voy_time').Update(voy_time_display) window.Element('voy_dist').Update(voy_dist) window.Element('voy_avg_spd').Update(voy_avg_spd) window.Element('voy_log_dist').Update(voy_log_dist) window.Element('rem_dist').Update(rem_dist) window.Element('real_eta').Update( real_eta.strftime('%Y-%m-%d %H:%M')) window.Element('wind_b').Update(wind_b) window.Element('speed_req').Update(round(speed_req, 2)) if event == 'Data Ready!': user_dict = { '~VOY~': values['voy'], '~EVENT~': values['event'], '~LOCATION~': values['location'], '~TIMELOCAL~': time_local.strftime('%Y-%m-%d %H:%M'), '~TZ~': values['tz'], '~TIMEUTC~': time_utc.strftime('%Y-%m-%d %H:%M'), '~LAT~': f'{values["lat_deg"]}-{values["lat_min"]}{values["lat_hemisphere"]}', '~LON~': f'{values["long_deg"]}-{values["long_min"]}{values["long_hemisphere"]}', '~COURSE~': values['cog'], '~GPSDIST~': values['gps_dist'], '~TIMEFROMLAST~': time_from_last_display, '~GPSAVGSPD~': avg_gps_spd, '~REMAININGDIST~': rem_dist, '~LOGFROMLAST~': values['log'], '~LOGSPDLAST~': avg_log_spd, '~CURRENTSPD~': current, '~ANCHORDROPPED~': 'anchor dropped', '~ANCHORAWEIGH~': 'anchor aweigh', '~NEXTPORT~': values['next_port'], '~ETATIMELOCAL~': eta_lt.strftime('%Y-%m-%d %H:%M'), '~ETATZ~': values['dest_tz'], '~ETATIMEUTC~': eta_utc.strftime('%Y-%m-%d %H:%M'), '~WINDDIR~': values['wind_dir'], '~WINDFORCEKTS~': wind_kts, '~WINDFORCEB~': wind_b, '~SEAHEIGHT~': values['sea_height'], '~SEADIR~': values['sea_dir'], '~SWELL~': values['swell'], '~AIRTEMP~': values['airtemp'], '~PRESSURE~': values['pressure'], '~BILGES~': values['bilges'], '~REMARKS~': values['remarks'], '~MASTER~': values['master'], '~VOYDIST~': voy_dist, '~VOYTIME~': voy_time_display, '~VOYGPSAVGSPD~': voy_avg_spd, '~VOYLOGDIST~': voy_log_dist, '~HFOROB~': hfo_rob, '~MDOROB~': mdo_rob, '~LOCYLROB~': int(float(values['LOCYLROB'])), '~LOMEROB~': int(float(values['LOMEROB'])), '~LOAUXROB~': int(float(values['LOAUXROB'])), '~LOTOTALROB~': int(float(values['LOTOTALROB'])), '~FWROB~': values['FWROB'], '~FWPROD~': values['FWPROD'], '~FWCONS~': values['FWCONS'], '~MEHFOCONS~': me_hfo_cons, '~MEMDOCONS~': me_mdo_cons, '~AUXHFOCONS~': aux_hfo_cons, '~AUXMDOCONS~': aux_mdo_cons, '~BOILERHFOCONS~': boiler_hfo_cons, '~BOILERMDOCONS~': boiler_mdo_cons, '~TOTALHFOCONS~': total_hfo_cons, '~TOTALMDOCONS~': total_mdo_cons, '~LOCYLCONS~': lo_cyl_cons, '~LOMECONS~': lo_me_cons, '~LOAUXCONS~': lo_aux_cons, '~TOTALLOCONS~': lo_total_cons, '~RPM~': rpm, '~MEDIST~': me_dist, '~MESPD~': me_spd, '~SLIP~': slip, '~MEKW~': me_kw, '~MEKWH~': me_kwh, '~MELOAD~': me_load, '~MEGOV~': me_gov, '~AUXTIME~': values['AUXTIME'], '~AUXKW~': aux_kw, '~AUXKWH~': aux_kwh, '~SLUDGETK~': values['SLUDGETK'], '~OILYBILGETK~': values['OILYBILGETK'], '~INCINERATORSETTLINGTK~': values['INCINERATORSETTLINGTK'], '~INCINERATORSERVICETK~': values['INCINERATORSERVICETK'], '~BILGEWATERTK~': values['BILGEWATERTK'], '~SLUDGETOTAL~': values['SLUDGETOTAL'], '~IFCARGO~': values['if_cargo'], '~COMMENCECARGOUTC~': c_ops_comm_utc.strftime('%Y-%m-%d %H:%M') if values['c_ops_comm_year'] != '' else '', '~COMPLETEDCARGOUTC~': c_ops_compl_utc.strftime('%Y-%m-%d %H:%M') if values['c_ops_compl_year'] != '' else '', '~CARGOROB~': values['cargo_rob'], '~CARGODAILY~': values['cargo_daily'], '~CARGOTOGO~': values['cargo_to_go'], '~BALLASTROB~': values['ballast_rob'], '~BALLASTDAILY~': values['ballast_daily'], '~SHORECRANESNO~': values['shore_cranes_no'], '~SHIPCRANESNO~': values['ship_cranes_no'], '~ETCLOCAL~': f'{values["etc_year"]}-{values["etc_month"]}-{values["etc_day"]} {values["etc_hour"]}:{values["etc_minute"]}' if values['etc_year'] != '' else '', '~ETDLOCAL~': f'{values["etd_year"]}-{values["etd_month"]}-{values["etd_day"]} {values["etd_hour"]}:{values["etd_minute"]}' if values['etd_year'] != '' else '', } if event == 'Submit Event': if user_dict is not None: update = sg.PopupYesNo( 'Data ready for reports/database update. Do you want to update database?', title='Update database?') check_and_update_database(user_dict) sg.PopupOK(to_next_excel_entry(update)) else: sg.PopupError( 'No calculations made! Press "Calculate" button under Nav Info tab first!', title='Data incomplete!') if event == 'Create reports': if user_dict is None: sg.PopupError( 'No calculations made! Press "Calculate" button under Nav Info tab first!', title='Data incomplete!') else: report_creation(user_dict) window.close()
import PySimpleGUI as sg layout = [[sg.Text('My one-shot window.')], [sg.InputText(), sg.Drop(values=('BatchNorm', 'other'), )], [sg.Submit(), sg.Cancel()]] sg.theme('SystemDefault') window = sg.Window('CKB sUDT issuance GUI', layout) event, values = window.read() window.close() text_input = values[0] sg.popup('You entered', text_input)
def PlayGame(): menu_def = [ ['&File', ['&Do nothing', 'E&xit']], ['&Help', '&About...'], ] # sg.SetOptions(margins=(0,0)) sg.ChangeLookAndFeel('GreenTan') # create initial board setup psg_board = copy.deepcopy(initial_board) # the main board display layout board_layout = [[sg.T(' ')] + [ sg.T('{}'.format(a), pad=((23, 27), 0), font='Any 13') for a in 'efgh' ]] # loop though board and create buttons with images for i in range(8): row = [sg.T(str(8 - i) + ' ', font='Any 13')] for j in range(4): piece_image = images[psg_board[i][j]] row.append(render_square(piece_image, key=(i, j), location=(i, j))) row.append(sg.T(str(8 - i) + ' ', font='Any 13')) board_layout.append(row) # add the labels across bottom of board board_layout.append([sg.T(' ')] + [ sg.T('{}'.format(a), pad=((23, 27), 0), font='Any 13') for a in 'efgh' ]) # setup the controls on the right side of screen openings = ('Any', 'Defense', 'Attack', 'Trap', 'Gambit', 'Counter', 'Sicillian', 'English', 'French', 'Queen\'s openings', 'King\'s Openings', 'Indian Openings') board_controls = [ [sg.RButton('New Game', key='New Game'), sg.RButton('Draw')], [sg.RButton('Resign Game'), sg.RButton('Set FEN')], [sg.RButton('Player Odds'), sg.RButton('Training')], [sg.Drop(openings), sg.Text('Opening/Style')], [sg.CBox('Play As White', key='_white_')], [sg.Text('Move List')], [ sg.Multiline([], do_not_clear=True, autoscroll=True, size=(15, 10), key='_movelist_') ], ] # layouts for the tabs controls_layout = [[ sg.Text('Performance Parameters', font='_ 20') ], [sg.T('Put stuff like AI engine tuning parms on this tab')]] statistics_layout = [[sg.Text('Statistics', font=('_ 20'))], [sg.T('Game statistics go here?')]] board_tab = [[sg.Column(board_layout)]] # the main window layout layout = [[sg.Menu(menu_def, tearoff=False)], [ sg.TabGroup([[ sg.Tab('Board', board_tab), sg.Tab('Controls', controls_layout), sg.Tab('Statistics', statistics_layout) ]], title_color='red'), sg.Column(board_controls) ], [sg.Text('Click anywhere on board for next move', font='_ 14')]] window = sg.Window('Chess', default_button_element_size=(12, 1), auto_size_buttons=False, icon='kingb.ico').Layout(layout) g = HalfchessGame.HalfchessGame() nn = NNet(g) nn.load_checkpoint(nn_filepath, nn_filename) args = dotdict({'numMCTSSims': numMCTSSims, 'cpuct': cpuct}) mcts = MCTS(g, nn, args) nnp = lambda x: np.argmax(mcts.getActionProb(x, temp=temp)) board = g.getInitBoard() move_count = curPlayer = 1 move_state = move_from = move_to = 0 # ---===--- Loop taking in user input --- # while g.getGameEnded(board, curPlayer) == 0: canonicalBoard = g.getCanonicalForm(board, curPlayer) if curPlayer == human: # human_player(board) move_state = 0 while True: button, value = window.Read() if button in (None, 'Exit'): exit() if button == 'New Game': sg.Popup( 'You have to restart the program to start a new game... sorry....' ) break psg_board = copy.deepcopy(initial_board) redraw_board(window, psg_board) move_state = 0 break if type(button) is tuple: if move_state == 0: move_from = button row, col = move_from piece = psg_board[row][col] # get the move-from piece button_square = window.FindElement(key=(row, col)) button_square.Update(button_color=('white', 'red')) move_state = 1 elif move_state == 1: move_to = button row, col = move_to if move_to == move_from: # cancelled move color = '#B58863' if (row + col) % 2 else '#F0D9B5' button_square.Update(button_color=('white', color)) move_state = 0 continue picked_move = '{}{}{}{}'.format( 'efgh'[move_from[1]], 8 - move_from[0], 'efgh'[move_to[1]], 8 - move_to[0]) action = moveset[picked_move] valids = g.getValidMoves(canonicalBoard, 1) if valids[action] != 0: board, curPlayer = g.getNextState( board, curPlayer, action) else: print('Illegal move') move_state = 0 color = '#B58863' if ( move_from[0] + move_from[1]) % 2 else '#F0D9B5' button_square.Update(button_color=('white', color)) continue psg_board[move_from[0]][move_from[ 1]] = BLANK # place blank where piece was psg_board[row][ col] = piece # place piece in the move-to square redraw_board(window, psg_board) move_count += 1 window.FindElement('_movelist_').Update(picked_move + '\n', append=True) break else: best_move = nnp(canonicalBoard) move_str = moveset[best_move] if curPlayer == -1: move_str = HalfchessGame.mirrored_move(move_str) from_col = ord(move_str[0]) - ord('e') from_row = 8 - int(move_str[1]) to_col = ord(move_str[2]) - ord('e') to_row = 8 - int(move_str[3]) window.FindElement('_movelist_').Update(move_str + '\n', append=True) piece = psg_board[from_row][from_col] psg_board[from_row][from_col] = BLANK psg_board[to_row][to_col] = piece redraw_board(window, psg_board) board, curPlayer = g.getNextState(board, curPlayer, best_move) move_count += 1 sg.Popup('Game over!', 'Thank you for playing')
'S7WLBit', 'S7WLByte', 'S7WLWord', 'S7WLDWord', 'S7WLReal', 'S7WLCounter', 'S7WLTimer' ]) intervals = tuple(['min', '1s', '2s', '5s', '10s', '60s', '300s']) #prepare layout data_row = [ sg.Input('0.0.0.0', size=(15, 1), key='PLC_NEW', tooltip='enter PLC IP address'), sg.Input('1', size=(2, 1), key="SLOT_NEW", tooltip='enter plc slot number'), sg.Drop(values=areas, key='AREA_NEW', size=(10, 1), tooltip='select data area', readonly=True, default_value=areas[0]), sg.Drop(values=types, key='TYPE_NEW', size=(14, 1), tooltip='select data type', readonly=True, default_value=types[0]), sg.Input('0', size=(10, 1), key='ADR_NEW', tooltip='enter data address'), sg.Input('data_alias', size=(20, 1), key='ALIAS_NEW', tooltip='enter data alias'), sg.Drop(values=intervals, key='INTERVAL_NEW',
], [ sg.Multiline('', key='-IN-', size=(100, 10), enable_events=True) ], [ sg.MLine(size=(100, 10), key='-OUTPUT-', disabled=True) ], [ sg.Text('Order: '), sg.Drop(values=('2', '3', '4', '5', '6'), auto_size_text=True, key='-D1-') ], [ sg.Text('Max iterations: '), sg.Input(key='-IN2-', size=(10, 10)) ], [ sg.Checkbox('Dynamic generation', default=False, key='-DG-', enable_events=True) ], [ sg.Button('Go', key='-B1-'), sg.Button('Clear'),
def manage_identified_absorbers(self): sg.ChangeLookAndFeel('Dark') col1 = [[ sg.Text('1. zabs', size=(5, 1)), sg.In(default_text=np.str(self.zabs_list['zabs'][0]), size=(15, 1)) ], [ sg.Text('2. zabs', size=(5, 1)), sg.In(default_text=np.str(self.zabs_list['zabs'][1]), size=(15, 1)) ], [ sg.Text('3. zabs', size=(5, 1)), sg.In(default_text=np.str(self.zabs_list['zabs'][2]), size=(15, 1)) ], [ sg.Text('4. zabs', size=(5, 1)), sg.In(default_text=np.str(self.zabs_list['zabs'][3]), size=(15, 1)) ], [ sg.Text('5. zabs', size=(5, 1)), sg.In(default_text=np.str(self.zabs_list['zabs'][4]), size=(15, 1)) ], [ sg.Text('6. zabs', size=(5, 1)), sg.In(default_text=np.str(self.zabs_list['zabs'][5]), size=(15, 1)) ], [ sg.Text('7. zabs', size=(5, 1)), sg.In(default_text=np.str(self.zabs_list['zabs'][6]), size=(15, 1)) ], [ sg.Text('8. zabs', size=(5, 1)), sg.In(default_text=np.str(self.zabs_list['zabs'][7]), size=(15, 1)) ], [ sg.Text('9. zabs', size=(5, 1)), sg.In(default_text=np.str(self.zabs_list['zabs'][8]), size=(15, 1)) ], [ sg.Text('10. zabs', size=(5, 1)), sg.In(default_text=np.str(self.zabs_list['zabs'][9]), size=(15, 1)) ]] col2 = [[ sg.Text('LineList', size=(5, 1)), sg.Drop(values=('LLS', 'LLS Small', 'DLA'), auto_size_text=True) ], [ sg.Text('LineList', size=(5, 1)), sg.Drop(values=('LLS', 'LLS Small', 'DLA'), auto_size_text=True) ], [ sg.Text('LineList', size=(5, 1)), sg.Drop(values=('LLS', 'LLS Small', 'DLA'), auto_size_text=True) ], [ sg.Text('LineList', size=(5, 1)), sg.Drop(values=('LLS', 'LLS Small', 'DLA'), auto_size_text=True) ], [ sg.Text('LineList', size=(5, 1)), sg.Drop(values=('LLS', 'LLS Small', 'DLA'), auto_size_text=True) ], [ sg.Text('LineList', size=(5, 1)), sg.Drop(values=('LLS', 'LLS Small', 'DLA'), auto_size_text=True) ], [ sg.Text('LineList', size=(5, 1)), sg.Drop(values=('LLS', 'LLS Small', 'DLA'), auto_size_text=True) ], [ sg.Text('LineList', size=(5, 1)), sg.Drop(values=('LLS', 'LLS Small', 'DLA'), auto_size_text=True) ], [ sg.Text('LineList', size=(5, 1)), sg.Drop(values=('LLS', 'LLS Small', 'DLA'), auto_size_text=True) ], [ sg.Text('LineList', size=(5, 1)), sg.Drop(values=('LLS', 'LLS Small', 'DLA'), auto_size_text=True) ]] col3 = [[ sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1)) ], [ sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1)) ], [ sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1)) ], [ sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1)) ], [ sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1)) ], [ sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1)) ], [ sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1)) ], [ sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1)) ], [ sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1)) ], [ sg.Text('color', size=(5, 1)), sg.In(default_text='None', size=(5, 1)) ]] layout = [[sg.Column(col1), sg.Column(col2), sg.Column(col3)], [sg.Submit(), sg.Exit(), sg.Button('Reset')]] window = sg.Window('Update Selected Absorbers', layout, font=("Helvetica", 12)) while True: event, values = window.read() #update database for i in range(0, 10): self.zabs_list.at[i, 'zabs'] = values[i] self.zabs_list.at[i, 'List'] = values[i + 10] self.zabs_list.at[i, 'color'] = values[i + 20] print(self.zabs_list) self.specplot() self.draw_any_linelist() if event == sg.WIN_CLOSED or event == 'Exit': break elif event == 'Reset': self.specplot() window.close()
import pandas as pd import PySimpleGUI as sg while True: layout = [ [sg.Text('Stata file to convert')], [sg.In(), sg.FileBrowse()], [sg.Text('Flags (optional)', size=(15, 1)), sg.Drop(values=('','convert_categoricals=False'), size=(25, 1))], [sg.Open('Convert'), sg.Cancel('Exit')]] window = sg.Window('Stata converter', layout) event, values = window.Read() fname = values[0] success = True if fname: if values[1] == '': try: df = pd.read_stata(fname) except Exception as e: sg.Popup(e) success = False elif values[1] == 'convert_categoricals=False': df = pd.read_stata(fname, convert_categoricals=False) if success: try: df.to_stata(fname[0:-4]+"converted.dta") except Exception as e: sg.Popup(e) if event == 'Exit' or event == None: break elif not fname:
def menu_window(): # set up layout for Option Calculator option_layout = [[ sg.Text('Step 1: Select an Option Type', background_color='darkseagreen') ], [ sg.Text('Option Type:', background_color='darkseagreen'), sg.Drop(values=OPTIONS_CHOICE, default_value=default1, auto_size_text=True, enable_events=True, key='-option_type-') ], [ sg.Text('Step 2: Select a Methodology', background_color='darkseagreen') ], [ sg.Text('Methodology:', background_color='darkseagreen'), sg.Drop(values=option_choice, default_value=default2, auto_size_text=True, enable_events=True, key='-option_method-') ], [ sg.Text('Step 3: Call or Put?', background_color='darkseagreen') ], [ sg.Text('Option Kind:', background_color='darkseagreen'), sg.Drop(values=['Call', 'Put'], default_value='Call', auto_size_text=True, enable_events=True, key='-option_kind-') ], [sg.Button('Next', enable_events=True, key='-next-')]] # set up layout for Implied Volatility Calculator iv_layout = [ [sg.Text("Implied Volatility via Newton's Method")], [sg.Text('Step 1: Call or Put?', background_color='darkseagreen')], [ sg.Text('Option Kind:', background_color='darkseagreen'), sg.Drop(values=['Call', 'Put'], default_value='Call', auto_size_text=True, enable_events=True, key='-option_kind_iv-') ], [sg.Text('Step 2: Input Parameters', background_color='darkseagreen')] ] for iv_param in ['V', 'S', 'K', 'T', 'r', 'q', 'tol', 'epoch']: iv_layout.append([ sg.Text(f'{iv_param}:', background_color='darkseagreen', key=f'-{iv_param}_label-'), sg.Input(key=f'-{iv_param}-', visible=True) ]) iv_layout.append( [sg.Button('Compute', enable_events=True, key='-compute_iv-')]) # set up the layers in tabs layout = [[ sg.TabGroup([[ sg.Tab('Option Value', option_layout, background_color='darkseagreen', key='-mykey-'), sg.Tab('Implied Volatility', iv_layout) ]], key='-group1-', tab_location='top', selected_title_color='purple') ], [sg.Button('Exit', enable_events=True, key='-exit-')]] # create window obj window = sg.Window('Option Calculator', layout, default_element_size=(12, 1)) return window
def the_GUI(): program_theme = 'DarkGrey5' is_authenticated = False gui_queue = queue.Queue() auth_window_active, about_window_active, console_window_active = False, False, False sg.theme(program_theme) menu_def = [ ['File', ['About', 'API Authentication']], ] main_layout = [ [sg.Menu(menu_def)], [sg.Text('FLICKR GeoSearch')], # Search [sg.Radio('BBOX', "Search_Type", default=True, key='-bbox_boolean-')], [ sg.Text(size=(5, 1)), sg.Text('Min Lat:', size=(7, 1), tooltip='-90 - 90'), sg.InputText(size=(5, 1), key='-min_lat-'), sg.Text(size=(1, 1)), sg.Text('Max Lat:', size=(7, 1), tooltip='-90 - 90'), sg.InputText(size=(5, 1), key='-max_lat-') ], [ sg.Text(size=(5, 1)), sg.Text('Min Long:', size=(7, 1), tooltip='-180 - 180'), sg.InputText(size=(5, 1), key='-min_long-'), sg.Text(size=(1, 1)), sg.Text('Max Long:', size=(7, 1), tooltip='-180 - 180'), sg.InputText(size=(5, 1), key='-max_long-') ], [ sg.Radio('Radial', "Search_Type", default=False, key='-radial_boolean-') ], [ sg.Text(size=(5, 1)), sg.Text('Lat: ', size=(7, 1), tooltip='-90 - 90'), sg.InputText(size=(5, 1), key='-radial_lat-'), sg.Text(size=(1, 1)), sg.Text('Long:', size=(7, 1), tooltip='-180 - 180'), sg.InputText(size=(5, 1), key='-radial_long-') ], [ sg.Text(size=(5, 1)), sg.Text('Radius:', size=(7, 1), tooltip='max 20mi / 32km'), sg.InputText(size=(5, 1), key='-radial_radius-'), sg.Text(size=(1, 1)), sg.Text('Units', size=(7, 1)), sg.Drop(values=('mi', 'km'), size=(4, 1), auto_size_text=True, key='-radial_units-') ], # Accuracy [ sg.Checkbox('Accuracy: ', default=False, size=(7, 1), key='-accuracy_boolean-'), sg.InputText(size=(4, 1), key='-accuracy-'), sg.Text(size=(13, 1), key='-accuracy_description-') ], [ sg.Text(size=(3, 1)), sg.Slider((1, 16), key='-slider_accuracy-', orientation='h', enable_events=True, disable_number_display=True) ], # Min Date Taken Upload [ sg.Checkbox('Minimum Date Taken: ', default=False, size=(17, 1), key='-min_date_boolean-') ], [ sg.Text(size=(3, 1)), sg.Drop(values=('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), size=(3, 1), auto_size_text=True, key='-min_month-', tooltip='month, 3 letter abbreviation'), sg.Text('-', size=(1, 1)), sg.Drop(values=('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'), size=(2, 1), tooltip='day, max 2 digit', key='-min_date-'), sg.Text('-', size=(1, 1)), sg.InputText(size=(4, 1), tooltip='Year, 4 number', key='-min_year-') ], # Max Date Taken Upload [ sg.Checkbox('Maximum Date Taken: ', default=False, size=(17, 1), key='-max_date_boolean-') ], [ sg.Text(size=(3, 1)), sg.Drop(values=('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), size=(3, 1), auto_size_text=True, key='-max_month-', tooltip='month, 3 letter abbreviation'), sg.Text('-', size=(1, 1)), sg.Drop(values=('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'), size=(2, 1), tooltip='day, max 2 digit', key='-max_date-'), sg.Text('-', size=(1, 1)), sg.InputText(size=(4, 1), tooltip='Year, 4 number', key='-max_year-') ], # Search Tags [ sg.Checkbox('Search tags: ', default=False, size=(9, 1), key='-search_tags_boolean-', tooltip='comma delimited'), sg.InputText(size=(23, 0), key='-search_tags-') ], # User wants results uploaded to gallery [ sg.Checkbox('Upload to Gallery', default=False, size=(17, 1), key='-upload_to_gallery_boolean-', tooltip='time intensive, 3 minutes per 500 results') ], # User wants results on Owner Info [ sg.Checkbox('Get Owner Info', default=False, size=(17, 1), key='-user_info_boolean-', tooltip='Slow, Name and Hometown') ], [sg.Text('' * 30)], # Download Gallery [ sg.Radio('Download From Gallery', "Search_Type", default=False, key='-gallery_download_boolean-', tooltip='TODO, see V1.0 for function') ], [ sg.Text(size=(1, 1)), sg.Frame(layout=[ [ sg.Text('Gallery ID: ', size=(9, 1)), sg.InputText(size=(20, 1), key='-gallery_id-') ], ], title='', title_color='red', relief=sg.RELIEF_SUNKEN) ], # File name and location [sg.InputText('Output File'), sg.FileSaveAs(key='-file_save_as-')], # Search [sg.Button('Search')] ] window = sg.Window("FLICKR GeoSearch", main_layout) thread = None # ---------EVENT LOOP-----------# while True: event, values = window.read() if event is None or event == 'Exit': break # Authorization Window if event == 'API Authentication' and not auth_window_active: sg.theme(program_theme) auth_layout = [ [sg.Text('API Key')], [sg.InputText(key='-api_key-')], [sg.Text('Secret Key')], [sg.InputText(key='-secret_key-', password_char='*')], [ sg.Button('Validate'), sg.Text(size=(15, 1), key='-Valid_Status-') ], [sg.Text('Token')], [ sg.InputText(key='-token-'), sg.Text(size=(15, 1), key='-Authentication_Status-') ], [sg.Button('Authenticate')], [sg.Ok(), sg.Cancel()], ] auth_window = sg.Window('Authentication', auth_layout, no_titlebar=True, grab_anywhere=True) auth_window_active = True # Authorization Interactions while auth_window_active: event2, values2 = auth_window.read() if event2 == 'Cancel' or event2 == 'Ok': auth_window.close() auth_window_active = False if event2 == 'Validate' and not is_authenticated: flickr = flickrapi.FlickrAPI(values2['-api_key-'], values2['-secret_key-']) auth_window['-Valid_Status-'].update('Validating..') if flickr.token_valid(perms='write'): is_authenticated = True auth_window['-Valid_Status-'].update('Validated') auth_window['-Authentication_Status-'].update( 'Authenticated') if not flickr.token_valid(perms='write'): flickr.get_request_token(oauth_callback='oob') # authorization_url = flickr.auth_url(perms='write') webbrowser.open_new(flickr.auth_url(perms='write')) if event2 == 'Authenticate' and not is_authenticated: auth_window['-Authentication_Status-'].update( 'Authenticating...') verifier = values2['-token-'] flickr.get_access_token(verifier) if flickr.token_valid(perms='write'): is_authenticated = True auth_window['-Authentication_Status-'].update( 'Authenticated') # About Window if event == 'About' and not about_window_active: sg.theme(program_theme) about_layout = [ [ sg.Multiline( default_text= "FLICKR GeoSearch V3.0\nCreated by: Matthew Tralka, 2020\nSource available on " "Github: " "mtralka\nLicensed under: GNU General Public License v3.0\n\n\n\nUses the Flickr API " "to " "execute geospatial photo searches. Results are auto formatted into an excel file and " "can be " "uploaded to Flickr photo galleries for review. Also supports the download of photos " "from " "Flickr photo galleries. " "", enter_submits=False, disabled=True, autoscroll=False, enable_events=False, do_not_clear=True, size=(50, 30)) ], [sg.Ok()], ] about_window = sg.Window('About', about_layout, no_titlebar=True, grab_anywhere=True) about_window_active = True # About Interactions while about_window_active: event3, values3 = about_window.read() if event3 == 'Ok': about_window.close() about_window_active = False # Accuracy Slider window['-accuracy-'].update(values['-slider_accuracy-']) if values['-accuracy_boolean-']: if int(values['-slider_accuracy-']) == 1: window['-accuracy_description-'].update('World') if int(values['-slider_accuracy-']) == 2: window['-accuracy_description-'].update('World+') if int(values['-slider_accuracy-']) == 3: window['-accuracy_description-'].update('Country') if int(values['-slider_accuracy-']) == 4: window['-accuracy_description-'].update('Country+') if int(values['-slider_accuracy-']) == 5: window['-accuracy_description-'].update('Country++') if int(values['-slider_accuracy-']) == 6: window['-accuracy_description-'].update('Region') if int(values['-slider_accuracy-']) == 7: window['-accuracy_description-'].update('Region+') if int(values['-slider_accuracy-']) == 8: window['-accuracy_description-'].update('Region++') if int(values['-slider_accuracy-']) == 9: window['-accuracy_description-'].update('Region+++') if int(values['-slider_accuracy-']) == 10: window['-accuracy_description-'].update('Region++++') if int(values['-slider_accuracy-']) == 11: window['-accuracy_description-'].update('City') if int(values['-slider_accuracy-']) == 12: window['-accuracy_description-'].update('City+') if int(values['-slider_accuracy-']) == 13: window['-accuracy_description-'].update('City++') if int(values['-slider_accuracy-']) == 14: window['-accuracy_description-'].update('City+++') if int(values['-slider_accuracy-']) == 15: window['-accuracy_description-'].update('City++++') if int(values['-slider_accuracy-']) == 16: window['-accuracy_description-'].update('Street') # Search Command if event == 'Search' and not is_authenticated: sg.popup("Authentication Needed", title="Error", background_color='red', no_titlebar=True) if event == 'Search' and is_authenticated and not thread: search = flickrSearchParameters(values) thread = threading.Thread(target=long_operation_thread, daemon=True, kwargs={ 'flickr': flickr, 'search': search }) thread.start() # Threading if thread: sg.popup_animated(sg.DEFAULT_BASE64_LOADING_GIF, background_color='white', transparent_color='white', time_between_frames=1) thread.join(timeout=0) if not thread.is_alive(): sg.popup_animated(None) thread = None
def PlayGame(): menu_def = [ ['&File', ['&Open PGN File', 'E&xit']], ['&Help', '&About...'], ] # sg.SetOptions(margins=(0,0)) sg.ChangeLookAndFeel('GreenTan') # create initial board setup board = copy.deepcopy(initial_board) # the main board display layout board_layout = [[sg.T(' ')] + [ sg.T('{}'.format(a), pad=((23, 27), 0), font='Any 13') for a in 'abcdefgh' ]] # loop though board and create buttons with images for i in range(8): row = [sg.T(str(8 - i) + ' ', font='Any 13')] for j in range(8): piece_image = images[board[i][j]] row.append(render_square(piece_image, key=(i, j), location=(i, j))) row.append(sg.T(str(8 - i) + ' ', font='Any 13')) board_layout.append(row) # add the labels across bottom of board board_layout.append([sg.T(' ')] + [ sg.T('{}'.format(a), pad=((23, 27), 0), font='Any 13') for a in 'abcdefgh' ]) # setup the controls on the right side of screen openings = ('Any', 'Defense', 'Attack', 'Trap', 'Gambit', 'Counter', 'Sicillian', 'English', 'French', 'Queen\'s openings', 'King\'s Openings', 'Indian Openings') board_controls = [ [sg.RButton('New Game', key='Open PGN File'), sg.RButton('Draw')], [sg.RButton('Resign Game'), sg.RButton('Set FEN')], [sg.RButton('Player Odds'), sg.RButton('Training')], [sg.Drop(openings), sg.Text('Opening/Style')], [sg.CBox('Play a White', key='_white_')], [sg.Text('Move List')], [ sg.Multiline([], do_not_clear=True, autoscroll=True, size=(15, 10), key='_movelist_') ], ] # layouts for the tabs controls_layout = [[ sg.Text('Performance Parameters', font='_ 20') ], [sg.T('Put stuff like AI engine tuning parms on this tab')]] statistics_layout = [[sg.Text('Statistics', font=('_ 20'))], [sg.T('Game statistics go here?')]] board_tab = [[sg.Column(board_layout)]] # the main window layout layout = [[sg.Menu(menu_def, tearoff=False)], [ sg.TabGroup([[ sg.Tab('Board', board_tab), sg.Tab('Controls', controls_layout), sg.Tab('Statistics', statistics_layout) ]], title_color='red'), sg.Column(board_controls) ], [sg.Text('Click anywhere on board for next move', font='_ 14')]] window = sg.Window('Chess', default_button_element_size=(12, 1), auto_size_buttons=False, icon='kingb.ico').Layout(layout) # ---===--- Loop taking in user input --- # i = 0 moves = None while True: button, value = window.Read() if button in (None, 'Exit'): break if button == 'Open PGN File': filename = sg.PopupGetFile('', no_window=True) if filename is not None: moves = open_pgn_file(filename) i = 0 board = copy.deepcopy(initial_board) window.FindElement('_movelist_').Update(value='') if button == 'About...': sg.Popup('Powerd by Engine Kibitz Chess Engine') if type(button) is tuple and moves is not None and i < len(moves): move = moves[i] # get the current move window.FindElement('_movelist_').Update(value='{} {}\n'.format( i + 1, str(move)), append=True) move_from = move.from_square # parse the move-from and move-to squares move_to = move.to_square row, col = move_from // 8, move_from % 8 piece = board[row][col] # get the move-from piece button = window.FindElement(key=(row, col)) for x in range(3): button.Update(button_color=('white', 'red' if x % 2 else 'white')) window.Refresh() time.sleep(.05) board[row][col] = BLANK # place blank where piece was row, col = move_to // 8, move_to % 8 # compute move-to square board[row][col] = piece # place piece in the move-to square redraw_board(window, board) i += 1
def MachineLearning(): """ Machine Learning GUI A standard non-blocking GUI with lots of inputs. """ import PySimpleGUI as sg sg.ChangeLookAndFeel('LightGreen') sg.SetOptions(text_justification='right') form = sg.FlexForm('Machine Learning Front End', font=("Helvetica", 12)) # begin with a blank form layout = [[sg.Text('Machine Learning Command Line Parameters', font=('Helvetica', 16))], [sg.Text('Passes', size=(15, 1)), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1)), sg.Text('Steps', size=(18, 1)), sg.Spin(values=[i for i in range(1, 1000)], initial_value=20, size=(6, 1))], [sg.Text('ooa', size=(15, 1)), sg.In(default_text='6', size=(10, 1)), sg.Text('nn', size=(15, 1)), sg.In(default_text='10', size=(10, 1))], [sg.Text('q', size=(15, 1)), sg.In(default_text='ff', size=(10, 1)), sg.Text('ngram', size=(15, 1)), sg.In(default_text='5', size=(10, 1))], [sg.Text('l', size=(15, 1)), sg.In(default_text='0.4', size=(10, 1)), sg.Text('Layers', size=(15, 1)), sg.Drop(values=('BatchNorm', 'other'),auto_size_text=True)], [sg.Text('_' * 100, size=(65, 1))], [sg.Text('Flags', font=('Helvetica', 15), justification='left')], [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.Text('_' * 100, size=(65, 1))], [sg.Text('Loss Functions', font=('Helvetica', 15), justification='left')], [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))], [sg.Submit(), sg.Cancel()]] button, values = form.LayoutAndRead(layout)
sg.InputText(key="plot gne", size=(34, 1)), sg.FileSaveAs(key="plot gne") ], [ sg.Text( "File path to save the plot HTML file too. This will combine all the " "necessary parts to generate a fully usable static HTML file. If this" " is not specified, the plot will be saved in a plot.html in the " "temporary folder.", size=(TEXT_WIDTH, 3)) ], [ TextLabel("Max. intergenic distance"), sg.InputText(default_text="100000", key="max_gap") ], [ TextLabel("Number of samples"), sg.InputText(default_text="100", key="samples") ], [ TextLabel("Sampling space"), sg.Drop(values=["linear", "log"], key="scale") ], ], title_color="blue", font="Arial 10 bold", relief="flat", ) layout = [[gne_frame]]
cluster_name = 'enter cluster name' bucket_name = 'enter bucket name' job_transport = (job_controller_grpc_transport.JobControllerGrpcTransport( address='{}-dataproc.googleapis.com:443'.format(region))) dataproc_job_client = dataproc_v1.JobControllerClient(job_transport) ##GUI Code import PySimpleGUI as sg sg.change_look_and_feel('Light Blue 2') layout = [[sg.Text('Select Offline to train and Online to Predict')], [ sg.Text('Mode', size=(15, 1)), sg.Drop(values=('Offline', 'Online'), auto_size_text=True) ], [sg.Text('Enter data path')], [sg.Text('File Path:', size=(8, 1)), sg.Input(), sg.FileBrowse()], [sg.Text('Enter data table name')], [sg.Text('TableName:', size=(8, 1)), sg.Input()], [sg.Button('Submit'), sg.Button('Exit')]] window = sg.Window('AdTracking Fraud Detection', layout) while True: event, values = window.read() if event == 'Submit': mode = values[0]
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)
[ sg.Text('[Cl-] (ppm)', size=(15, 1)), sg.Input('50', key='pitting_Clm', size=(10, 1)) ], [ sg.Text('Temperature (°C)', size=(15, 1)), sg.Input('28', key='pitting_tempC', size=(10, 1)) ], [ sg.Text('Water velocity (m/s)', size=(15, 1)), sg.Input('10', key='pitting_velocity', size=(10, 1)) ], [ sg.Text('Bacteria biofilm', size=(15, 1)), sg.Drop(values=('Present', 'Absent'), key='pitting_biofilm', auto_size_text=True) ], [sg.Text('\nSteel alloy composition:')], [ sg.Text('% Chromium', size=(15, 1)), sg.Input('13.115', key='pitting_Cr', size=(10, 1)) ], [ sg.Text('% Molybdenum', size=(15, 1)), sg.Input('0.029', key='pitting_Mo', size=(10, 1)) ], [ sg.Text('% Nitrogen', size=(15, 1)), sg.Input('0.019', key='pitting_N', size=(10, 1)) ], [
import PySimpleGUI as sg from analysis.analyzeGUI import Analyze as ag from tracking.trackingGUI import Track as tg layout = [ [sg.Text('What would you like to Do', size=(25, 1)), sg.Drop(key='DO?', values=( 'track', 'analyze'), size = (25, 1))], [sg.Submit(), sg.Cancel()] ] window = sg.Window('Startup GUI', layout) event, expar = window.Read() if expar['DO?'] == 'track': tg() elif expar['DO?'] == 'analyze': ag()