def table_example(): sg.SetOptions(auto_size_buttons=True) filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files", "*.csv"),)) # --- populate table with file contents --- # if filename == '': sys.exit(69) data = [] header_list = [] button = sg.PopupYesNo('Does this file have column names already?') if filename is not None: try: df = pd.read_csv(filename, sep=',', engine='python', header=None) # Header=None means you directly pass the columns names to the dataframe data = df.values.tolist() # read everything else into a list of rows if button == 'Yes': # Press if you named your columns in the csv header_list = df.iloc[0].tolist() # Uses the first row (which should be column names) as columns names data = df[1:].values.tolist() # Drops the first row in the table (otherwise the header names and the first row will be the same) elif button == 'No': # Press if you didn't name the columns in the csv header_list = ['column' + str(x) for x in range(len(data[0]))] # Creates columns names for each column ('column0', 'column1', etc) except: sg.PopupError('Error reading file') sys.exit(69) # sg.SetOptions(element_padding=(0, 0)) col_layout = [[sg.Table(values=data, headings=header_list, display_row_numbers=True, auto_size_columns=False, size=(None, len(data)))]] canvas_size = (13*10*len(header_list), 600) # estimate canvas size - 13 pixels per char * 10 per column * num columns layout = [[sg.Column(col_layout, size=canvas_size, scrollable=True)]] window = sg.Window('Table', grab_anywhere=False) b, v = window.LayoutAndRead(layout) sys.exit(69)
def table_example(): filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files", "*.csv"), )) # --- populate table with file contents --- # if filename == '': sys.exit(69) data = [] header_list = [] button = sg.PopupYesNo('Does this file have column names already?') if filename is not None: with open(filename, "r") as infile: reader = csv.reader(infile) if button == 'Yes': header_list = next(reader) try: data = list(reader) # read everything else into a list of rows if button == 'No': header_list = [ 'column' + str(x) for x in range(len(data[0])) ] except: sg.PopupError('Error reading file') sys.exit(69) sg.SetOptions(element_padding=(0, 0)) col_layout = [[ sg.Table(values=data, headings=header_list, max_col_width=25, auto_size_columns=True, justification='right', size=(None, len(data))) ]] canvas_size = ( 13 * 10 * len(header_list), 600 ) # estimate canvas size - 13 pixels per char * 10 char per column * num columns layout = [ [sg.Column(col_layout, size=canvas_size, scrollable=True)], ] window = sg.Window('Table', grab_anywhere=False).Layout(layout) b, v = window.Read() sys.exit(69)
def main(): button, values = GetFilesToCompare() f1 = values['file1'] f2 = values['file2'] if any((button != 'Submit', f1 == '', f2 == '')): sg.PopupError('Operation cancelled') sys.exit(69) # --- This portion of the code is not GUI related --- with open(f1, 'rb') as file1: with open(f2, 'rb') as file2: a = file1.read() b = file2.read() for i, x in enumerate(a): if x != b[i]: sg.Popup('Compare results for files', f1, f2, '**** Mismatch at offset {} ****'.format(i)) break else: if len(a) == len(b): sg.Popup('**** The files are IDENTICAL ****')
def TableSimulation(): """ Display data in a table format """ sg.SetOptions(element_padding=(0, 0)) sg.PopupNoWait('Give it a few seconds to load please...', auto_close=True) menu_def = [ ['File', ['Open', 'Save', 'Exit']], [ 'Edit', ['Paste', [ 'Special', 'Normal', ], 'Undo'], ], ['Help', 'About...'], ] columm_layout = [[]] MAX_ROWS = 60 MAX_COL = 10 for i in range(MAX_ROWS): inputs = [sg.T('{}'.format(i), size=(4, 1), justification='right')] + [ sg.In(size=(10, 1), pad=(1, 1), justification='right', key=(i, j), do_not_clear=True) for j in range(MAX_COL) ] columm_layout.append(inputs) layout = [ [sg.Menu(menu_def)], [sg.T('Table Using Combos and Input Elements', font='Any 18')], [ sg. T('Type in a row, column and value. The form will update the values in realtime as you type' ), sg.In(key='inputrow', justification='right', size=(8, 1), pad=(1, 1), do_not_clear=True), sg.In(key='inputcol', size=(8, 1), pad=(1, 1), justification='right', do_not_clear=True), sg.In(key='value', size=(8, 1), pad=(1, 1), justification='right', do_not_clear=True) ], [sg.Column(columm_layout, size=(800, 600), scrollable=True)] ] window = sg.Window('Table', return_keyboard_events=True, grab_anywhere=False).Layout(layout) while True: button, values = window.Read() # --- Process buttons --- # if button is None or button == 'Exit': break elif button == 'About...': sg.Popup('Demo of table capabilities') elif button == 'Open': filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files", "*.csv"), )) # --- populate table with file contents --- # if filename is not None: with open(filename, "r") as infile: reader = csv.reader(infile) try: data = list( reader) # read everything else into a list of rows except: sg.PopupError('Error reading file') continue # clear the table [ window.FindElement((i, j)).Update('') for j in range(MAX_COL) for i in range(MAX_ROWS) ] for i, row in enumerate(data): for j, item in enumerate(row): location = (i, j) try: # try the best we can at reading and filling the table target_element = window.FindElement(location) new_value = item if target_element is not None and new_value != '': target_element.Update(new_value) except: pass # if a valid table location entered, change that location's value try: location = (int(values['inputrow']), int(values['inputcol'])) target_element = window.FindElement(location) new_value = values['value'] if target_element is not None and new_value != '': target_element.Update(new_value) except: pass
else: import PySimpleGUI as sg import csv filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files", "*.csv"), )) # --- populate table with file contents --- # data = [] if filename is not None: with open(filename, "r") as infile: reader = csv.reader(infile) try: data = list(reader) # read everything else into a list of rows except: sg.PopupError('Error reading file') sys.exit(69) sg.SetOptions(element_padding=(0, 0)) col_layout = [[ sg.Table(values=data[1:][:], headings=[data[0][x] for x in range(len(data[0]))], max_col_width=25, auto_size_columns=True, display_row_numbers=True, justification='right', size=(None, len(data))) ]] layout = [
def popUpError(ErrorMessage): sg.PopupError(ErrorMessage) pass
def main(): def GetCurrentTime(): ''' Get the current system time in milliseconds :return: milliseconds ''' return int(round(time.time() * 1000)) pback = PlayerGUI() button, values = pback.PlayerChooseSongGUI() if button != 'PLAY': sg.PopupCancel('Cancelled...\nAutoclose in 2 sec...', auto_close=True, auto_close_duration=2) sys.exit(69) if values['device']: midi_port = values['device'][0] else: sg.PopupCancel('No devices found\nAutoclose in 2 sec...', auto_close=True, auto_close_duration=2) batch_folder = values['folder'] midi_filename = values['midifile'] # ------ Build list of files to play --------------------------------------------------------- # if batch_folder: filelist = os.listdir(batch_folder) filelist = [ batch_folder + '/' + f for f in filelist if f.endswith(('.mid', '.MID')) ] filetitles = [os.path.basename(f) for f in filelist] elif midi_filename: # an individual filename filelist = [ midi_filename, ] filetitles = [ os.path.basename(midi_filename), ] else: sg.PopupError('*** Error - No MIDI files specified ***') sys.exit(666) # ------ LOOP THROUGH MULTIPLE FILES --------------------------------------------------------- # pback.PlayerPlaybackGUIStart( NumFiles=len(filelist) if len(filelist) <= 10 else 10) port = None # Loop through the files in the filelist for now_playing_number, current_midi_filename in enumerate(filelist): display_string = 'Playing Local File...\n{} of {}\n{}'.format( now_playing_number + 1, len(filelist), current_midi_filename) midi_title = filetitles[now_playing_number] # --------------------------------- REFRESH THE GUI ----------------------------------------- # pback.PlayerPlaybackGUIUpdate(display_string) # ---===--- Output Filename is .MID --- # midi_filename = current_midi_filename # --------------------------------- MIDI - STARTS HERE ----------------------------------------- # if not port: # if the midi output port not opened yet, then open it port = mido.open_output(midi_port if midi_port else None) try: mid = mido.MidiFile(filename=midi_filename) except: print( '****** Exception trying to play MidiFile filename = {}***************' .format(midi_filename)) sg.PopupError('Exception trying to play MIDI file:', midi_filename, 'Skipping file') continue # Build list of data contained in MIDI File using only track 0 midi_length_in_seconds = mid.length display_file_list = '>> ' + '\n'.join([ f for i, f in enumerate(filetitles[now_playing_number:]) if i < 10 ]) paused = cancelled = next_file = False ######################### Loop through MIDI Messages ########################### while (True): start_playback_time = GetCurrentTime() port.reset() for midi_msg_number, msg in enumerate(mid.play()): #################### GUI - read values ################## if not midi_msg_number % 4: # update the GUI every 4 MIDI messages t = (GetCurrentTime() - start_playback_time) // 1000 display_midi_len = '{:02d}:{:02d}'.format( *divmod(int(midi_length_in_seconds), 60)) display_string = 'Now Playing {} of {}\n{}\n {:02d}:{:02d} of {}\nPlaylist:'.\ format(now_playing_number+1, len(filelist), midi_title, *divmod(t, 60), display_midi_len) # display list of next 10 files to be played. pback.SliderElem.Update(t, range=(1, midi_length_in_seconds)) rc = pback.PlayerPlaybackGUIUpdate(display_string + '\n' + display_file_list) else: # fake rest of code as if GUI did nothing rc = PLAYER_COMMAND_NONE if paused: rc = PLAYER_COMMAND_NONE while rc == PLAYER_COMMAND_NONE: # TIGHT-ASS loop waiting on a GUI command rc = pback.PlayerPlaybackGUIUpdate(display_string) time.sleep(.25) ####################################### MIDI send data ################################## port.send(msg) # ------- Execute GUI Commands after sending MIDI data ------- # if rc == PLAYER_COMMAND_EXIT: cancelled = True break elif rc == PLAYER_COMMAND_PAUSE: paused = not paused port.reset() elif rc == PLAYER_COMMAND_NEXT: next_file = True break elif rc == PLAYER_COMMAND_RESTART_SONG: break if cancelled or next_file: break #------- DONE playing the song ------- # port.reset() # reset the midi port when done with the song if cancelled: break