def main_window(self): folder_select_layout = [ [ sg.Text('Select source folder', size=(20, 1)), sg.In(key='SRC', enable_events=True), sg.FolderBrowse() ], [ sg.Text('Select destination folder', size=(20, 1)), sg.In(key='DST', enable_events=True), sg.FolderBrowse() ], ] layout = [ [ sg.Frame( 'Choose source and destination folders', layout=folder_select_layout, ) ], [sg.Text("Choose Operation to perform:")], [ sg.Combo(['Copy', 'Move'], default_value='Move', key='OPERATION', size=(10, 1)), sg.CBox( "Overwrite files", tooltip= "Incoming files will replace files of the same names in the destination", key="OVERWRITE") ], [ sg.Frame(layout=[[sg.Text("Sort by Type")], [ sg.Radio("Enabled", "RADIO1", default=False, key='SBYTE', enable_events=True), sg.Radio("Disabled", "RADIO1", default=True, key='SBYTD', enable_events=True) ]], title='Sorting Options', title_color='red', relief=sg.RELIEF_SUNKEN) ], [sg.Text("Choose filetype:")], [ sg.Combo( # Options for type of file [ "Archive ('.zip', '.rar'...)", "Image ('.png', '.jpg'...)", "Text ('.txt', '.docx'...)", "Video ('.mp4', '.mov'...)", "Audio ('.mp3', '.wav'...)", "Code ('.cpp', '.py'...)" ], key='FILETYPE', enable_events=True) ], [sg.Ok(), sg.Cancel()] ] window = sg.Window('Choose filetype to move', layout, default_element_size=(40, 1)) while True: event, values = window.read() if event in (sg.WIN_CLOSED, 'Cancel'): break elif event in ['SRC', 'DST']: set_path(event, values[event]) elif event in 'Ok': if not get_path('src') or not get_path('dst'): missing_fields = None if not get_path('src') and not get_path('dst'): missing_fields = "source and destination folders" elif not get_path('src'): missing_fields = "source folder" else: missing_fields = "destination folder" sg.PopupOK("Oops! You didn't select the {}".format( missing_fields)) elif values['FILETYPE'] not in file_type: append_file_type(values['FILETYPE']) run_fmover = FileMover() append_mode(values['OPERATION']) if len(sort_list) == 1: for value in sort_list: if value == 'Sort by Type': run_fmover.filemover(values['OPERATION'], value, values['OVERWRITE']) else: run_fmover.filemover(values['OPERATION'], None, values['OVERWRITE']) else: run_fmover.filemover(values['OPERATION'], None, values['OVERWRITE']) else: run_fmover = FileMover() append_mode(values['OPERATION']) if len(sort_list) == 1: for value in sort_list: if value == 'Sort by Type': run_fmover.filemover(values['OPERATION'], value, values['OVERWRITE']) else: run_fmover.filemover(values['OPERATION'], None, values['OVERWRITE']) else: run_fmover.filemover(values['OPERATION'], None, values['OVERWRITE']) elif event in 'SBYTE': if values['SBYTE'] is True: sort_list.append('Sort by Type') else: pass elif event in 'SBYTD': if values['SBYTD'] is True: sort_list.clear() else: pass else: pass window.close()
There are THREE steps, and they are copy and pastes. 1. At the top of your app to debug add import imwatchingyou 2. When you want to show a debug window, call one of two functions: imwatchingyou.show_debug_window() imwatchingyou.show_popout_window() 3. You must find a location in your code to "refresh" the debugger. Some loop that's executed often. In this loop add this call: imwatchingyou.refresh() """ layout = [ [sg.Text('A typical PSG application')], [sg.Input(key='-IN-')], [sg.Text(' ', key='-OUT-', size=(45, 1))], [sg.CBox('Checkbox 1'), sg.CBox('Checkbox 2')], [sg.Radio('a', 1, key='-R1-'), sg.Radio('b', 1, key='-R2-'), sg.Radio('c', 1, key='-R3-')], [sg.Combo(['c1', 'c2', 'c3'], size=(6, 3), key='-COMBO-')], [sg.Output(size=(50, 6))], [sg.Ok(), sg.Exit(), sg.Button('Enable'), sg.Debug(key='Debug')], ] window = sg.Window('This is your Application Window', layout, debugger_enabled=False) counter = 0 while True: # Your Event Loop event, values = window.read(timeout=100) if event in (sg.WIN_CLOSED, 'Exit'): break
gray_3_channels[:, :, 1] = gray gray_3_channels[:, :, 2] = gray return gray_3_channels # --------------------------------- The GUI --------------------------------- # First the window layout...2 columns left_col = [[ sg.Text('Folder'), sg.In(size=(25, 1), enable_events=True, key='-FOLDER-'), sg.FolderBrowse() ], [ sg.Listbox(values=[], enable_events=True, size=(40, 20), key='-FILE LIST-') ], [sg.CBox('Convert to gray first', key='-MAKEGRAY-')], [sg.Text('Version ' + version, font='Courier 8')]] images_col = [ [ sg.Text('Input file:'), sg.In(enable_events=True, key='-IN FILE-'), sg.FileBrowse() ], [ sg.Button('Colorize Photo', key='-PHOTO-'), sg.Button('Start Webcam', key='-WEBCAM-'), sg.Button('Save File', key='-SAVE-'), sg.Button('Exit') ], [sg.Image(filename='', key='-IN-'),
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 the_gui(): """ Starts and executes the GUI Reads data from a global variable and displays Returns when the user exits / closes the window """ global message, progress sg.theme('Light Brown 3') layout = [ [sg.Text('Long task to perform example')], [sg.Output(size=(80, 12))], [ sg.Text('Number of seconds your task will take'), sg.Input(key='-SECONDS-', size=(5, 1)), sg.Button('Do Long Task', bind_return_key=True), sg.CBox('ONE chunk, cannot break apart', key='-ONE CHUNK-') ], [ sg.Text('Work progress'), sg.ProgressBar(total, size=(20, 20), orientation='h', key='-PROG-') ], [sg.Button('Click Me'), sg.Button('Exit')], ] window = sg.Window('Multithreaded Demonstration Window', layout) thread = None # --------------------- EVENT LOOP --------------------- while True: event, values = window.read(timeout=100) if event in (None, 'Exit'): break elif event.startswith('Do') and not thread: print('Thread Starting! Long work....sending value of {} seconds'. format(float(values['-SECONDS-']))) thread = threading.Thread(target=long_operation_thread, args=(float(values['-SECONDS-']), ), daemon=True) thread.start() elif event == 'Click Me': print('Your GUI is alive and well') if thread: # If thread is running if values[ '-ONE CHUNK-']: # If one big operation, show an animated GIF sg.popup_animated(sg.DEFAULT_BASE64_LOADING_GIF, background_color='white', transparent_color='white', time_between_frames=100) else: # Not one big operation, so update a progress bar instead window['-PROG-'].update_bar(progress, total) thread.join(timeout=0) if not thread.is_alive(): # the thread finished print(f'message = {message}') sg.popup_animated( None) # stop animination in case one is running thread, message, progress = None, '', 0 # reset variables for next run window['-PROG-'].update_bar(0, 0) # clear the progress bar window.close()
justification="left", font=("arial", 16, "bold")), sg.Text('Read Noise Mean', size=(15, 1)), sg.InputText("2", size=(7, 30), justification="right", key="rm", enable_events=True), sg.Text('Read Noise Standard Deviation', size=(25, 1)), sg.InputText("2", size=(7, 30), justification="right", key="rs", enable_events=True), sg.Text("Include Read Noise?", pad=((20, 5), (5, 5))), sg.CBox("", key="irn", default=True) ], [ sg.Text('Fix Shot Noise Seed?', size=(25, 1)), sg.CBox("", default=True, key="fs"), sg.Text("Include Shot Noise?", pad=((20, 5), (5, 5))), sg.CBox("", key="isn", default=True) ], [ sg.Text('Fixed Pattern Deviation', size=(25, 1)), sg.InputText("0.001", size=(7, 30), justification="right", key="fpn", enable_events=True), sg.Text("Include Fixed Pattern Deviation?",
def CheckList(mtxt, lkey, mdstring, disable=False): if mdstring == 'photosMetadata' or mdstring == 'journalStrings' or mdstring == 'walStrings': #items in the if are modules that take a long time to run. Deselects them by default. dstate = False else: dstate = True return [sg.CBox(mtxt, default=dstate, key=lkey, metadata=mdstring, disabled=disable)]
def ToDoItem(num): return [sg.Text(f'{num}. '), sg.CBox(''), sg.In()]
def CheckList(mtxt, lkey, mdstring): return [sg.CBox(mtxt, default=True, key=lkey, metadata=mdstring)]
layout += [[sg.Ok(), sg.Cancel()]] event, values = sg.Window('Choose Stream', layout).read(close=True) choices = [k for k in values if values[k]] if not choices: sg.popup_error('Must choose stream') exit() return streams[choices[0]] # Return the first choice made sg.theme('Dark Teal 7') layout = [[sg.Text('URL', size=(15, 1)), sg.InputText(k='-URL-')], [sg.CBox('Show detailed download window', k='-DETAILS CB-')], [sg.Text(size=(50, 2), key='-OUTPUT-')], [ sg.Text('Status:'), sg.Text('IDLE', size=(15, 1), justification='c', text_color='orange', relief=sg.RELIEF_SUNKEN, k='-STATUS-') ], [ sg.ProgressBar(100, orientation='h', size=(30, 25), k='-METER-'), sg.T(size=(5, 1), k='-% COMPLETE-') ], [
def newGameWindow(): # gameState: config global playerColor global gameTime global newGameState global state global detected global cap global selectedCam global skillLevel windowName = "Configuration" frame_layout = [[ sg.Radio('RPi Cam', group_id='grp', default=True, key="rpicam"), sg.VerticalSeparator(pad=None), sg.Radio('USB0', group_id='grp', key="usb0"), sg.Radio('USB1', group_id='grp', key="usb1") ]] initGame = [[ sg.Text('Game Parameters', justification='center', pad=(25, (5, 15)), font='Any 15') ], [sg.CBox('Play as White', key='userWhite', default=playerColor)], [ sg.Spin([sz for sz in range(1, 300)], initial_value=10, font='Any 11', key='timeInput'), sg.Text('Game time (min)', pad=(0, 0)) ], [ sg.Combo([sz for sz in range(1, 11)], default_value=10, key="enginelevel"), sg.Text('Engine skill level', pad=(0, 0)) ], [ sg.Frame('Camera Selection', frame_layout, pad=(0, 10), title_color='white') ], [sg.Text('_' * 30)], [sg.Button("Exit"), sg.Submit("Next")]] windowNewGame = sg.Window( windowName, default_button_element_size=(12, 1), auto_size_buttons=False, icon='interface_images/robot_icon.ico').Layout(initGame) while True: button, value = windowNewGame.Read() if button == "Next": if value["rpicam"] == True: selectedCam = 0 elif value["usb0"] == True: selectedCam = 1 elif value["usb1"] == True: selectedCam = 2 cap = initCam(selectedCam) if detected: newGameState = "calibration" playerColor = value["userWhite"] skillLevel = value["enginelevel"] * 2 gameTime = float(value["timeInput"] * 60) break if button in (None, 'Exit'): # MAIN WINDOW state = "stby" break windowNewGame.close()
def widget(): sG.change_look_and_feel('GreenTan') # ------ Menu Definition ------ # menu_def = [ ['&File', ['&Open', '&Save', 'E&xit', 'Properties']], [ '&Edit', ['Paste', [ 'Special', 'Normal', ], 'Undo'], ], ['&Help', '&About...'], ] # ------ Column Definition ------ # column1 = [ [ sG.Text('Column 1', background_color='lightblue', justification='center', size=(10, 1)) ], [sG.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 1')], [sG.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 2')], [sG.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')] ] layout = [ [sG.Menu(menu_def, tearoff=True)], [ sG.Text('(Almost) All widgets in one Window!', size=(30, 1), justification='center', font=("Helvetica", 25), relief=sG.RELIEF_RIDGE) ], [sG.Text('Here is some text.... and a place to enter text')], [sG.InputText('This is my text')], [ sG.Frame(layout=[[ sG.CBox('Checkbox', size=(10, 1)), sG.CBox('My second checkbox!', default=True) ], [ sG.Radio('My first Radio! ', "RADIO1", default=True, size=(10, 1)), sG.Radio('My second Radio!', "RADIO1") ]], title='Options', title_color='red', relief=sG.RELIEF_SUNKEN, tooltip='Use these to set flags') ], [ sG.MLine( default_text= 'This is the default Text should you decide not to type anything', size=(35, 3)), sG.MLine(default_text='A second multi-line', size=(35, 3)) ], [ sG.Combo(('Combobox 1', 'Combobox 2'), size=(20, 1)), sG.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85) ], [sG.OptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option 3'))], [ sG.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3)), sG.Frame('Labelled Group', [[ sG.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25, tick_interval=25), sG.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75), sG.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10), sG.Col(column1, background_color='lightblue') ]]) ], [sG.Text('_' * 80)], [sG.Text('Choose A Folder', size=(35, 1))], [ sG.Text('Your Folder', size=(15, 1), justification='right'), sG.InputText('Default Folder'), sG.FolderBrowse() ], [sG.Submit(tooltip='Click to submit this form'), sG.Cancel()] ] window = sG.Window('Everything bagel', layout, default_element_size=(40, 1), grab_anywhere=False) event, values = window.read() sG.popup('Title', 'The results of the window.', 'The button clicked was "{}"'.format(event), 'The values are', values)
import PySimpleGUI as psg column1 = [ [psg.Checkbox("체크박스1", key="-CHECK1-")], [psg.CBox("체크박스2", key="-CHECK2-")], [psg.CB("체크박스3", key="-CHECK3-")], ] column2 = [ [psg.Checkbox("체크박스A", key="-CHECKA-")], [psg.CBox("체크박스B", key="-CHECKB-")], [psg.CB("체크박스C", key="-CHECKC-")], ] layout = [ [psg.Column(column1), psg.VerticalSeparator(), psg.Col(column2)], [psg.Ok(), psg.Cancel()] ] window = psg.Window("Checkbox 테스트", layout) event, values = window.read() window.close() print(event, values)
end_year=int(end_year) if start_year<1917 or start_year>time.localtime().tm_year or end_year<1917 or end_year>time.localtime().tm_year: sg.popup('Invalid input. Must be YYYY in range ['+str(first_year)+';'+str(last_year)+']') elif start_year>end_year: sg.popup('Start year is after end year') else: datavalid=True except: sg.popup('Invalid input. Must be YYYY in range ['+str(first_year)+';'+str(last_year)+']') #Choosing the type to view in plot type_to_viz=[] datavalid=False while datavalid==False: layout = [[sg.Text('Which type of content do you want to visualize ? ')], [[sg.CBox(anitype, default=True) for anitype in anime_types]], [sg.OK(), sg.Cancel()]] window = sg.Window('Choosing anime type', layout) event, values = window.read() window.close() if event==sg.WIN_CLOSED or event=='Cancel': exit() for i in range(len(values)): if values[i]==True: type_to_viz.append(anime_types[i]) if len(type_to_viz)!=0: datavalid=True else:
def gui_format_tab(reg_map_dict): """Format registers in active GUI tab""" response = [] for key in reg_map_dict.keys(): if key >= 0: response.append([ sg.Text(str('[0x%02x] %s' % (key, reg_map_dict[key].get('nicename'))), size=(CONF_REG_DESCR_WIDTH, 1)), sg.CBox('Edit', disabled=reg_map_dict[key].get('rw') == 'r', enable_events=True, key=str('_KEY_EDIT_%s' % key)), sg.In(disabled=True, key=str('_KEY_TEXT_%s' % key), size=(CONF_REG_VALUE_WIDTH, 1), enable_events=True) ]) # Add configuration button if required if reg_map_dict[key].get('conf', False): response[-1].extend([ sg.B('Configure', key=str('_KEY_CONF_%s' % key), enable_events=True, disabled=True, size=(10, 1)) ]) else: response[-1].extend([sg.B('', disabled=True, size=(10, 1))]) response[-1].extend([ sg.B('Write', key=str('_KEY_WRITE_%s' % key), enable_events=True, disabled=True), sg.Radio('Hex', str('_KEY_FORMAT_%s' % key), key=str('_KEY_FORMAT_HEX_%s' % key), default=reg_map_dict[key].get('format') == 'hex'), sg.Radio('Dec', str('_KEY_FORMAT_%s' % key), key=str('_KEY_FORMAT_DEC_%s' % key), default=reg_map_dict[key].get('format') == 'dec'), sg.Radio('Bin', str('_KEY_FORMAT_%s' % key), key=str('_KEY_FORMAT_BIN_%s' % key), default=reg_map_dict[key].get('format') == 'bin'), ]) # Add IP format for network config registers if reg_map_dict[key].get('format') == 'ip': response[-1].extend([ sg.Radio('Ip', str('_KEY_FORMAT_%s' % key), key=str('_KEY_FORMAT_IP_%s' % key), default=reg_map_dict[key].get('format') == 'ip') ]) else: descr_table = reg_map_dict[key].get('data') table_width = reg_map_dict[key].get('col_width') header = reg_map_dict[key].get('header') # Add white space response.append([sg.Text('', font=("Helvetica", 5))]) # Add header if header: response.append([ sg.Text(header, border_width=None, background_color=None, font=("Helvetica", 12), pad=(0, 0), size=(sum(table_width), 1)) ]) # Add description / table data for desc_line in descr_table: if type(desc_line) is list: response.append([ sg.Text(desc_col, border_width=None, background_color=None, pad=(0, 0), size=(table_width[i] if len(desc_line) > 1 else sum(table_width), 1)) for i, desc_col in enumerate(desc_line) ]) return response
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 gui_format_tab_uart(reg_map_dict): """Format registers in UART/RS485 GUI tab""" response = gui_format_tab(reg_map_dict) for key in reg_map_dict.keys(): response.append([ sg.Text(str('[0x%02x] %s' % (key, reg_map_dict[key].get('nicename'))), size=(CONF_REG_DESCR_WIDTH, 1)), sg.CBox('Edit', disabled=reg_map_dict[key].get('rw') == 'r', enable_events=True, key=str('_KEY_EDIT_%s' % key)), sg.In(disabled=True, key=str('_KEY_TEXT_%s' % key), size=(CONF_REG_VALUE_WIDTH, 1), enable_events=True) ]) # Add configuration button if required if reg_map_dict[key].get('conf', False): response[-1].extend([ sg.B('Configure', key=str('_KEY_CONF_%s' % key), enable_events=True, disabled=True, size=(10, 1)) ]) else: response[-1].extend([sg.B('', disabled=True, size=(10, 1))]) response[-1].extend([ sg.B('Write', key=str('_KEY_WRITE_%s' % key), enable_events=True, disabled=True), sg.Radio('Hex', str('_KEY_FORMAT_%s' % key), key=str('_KEY_FORMAT_HEX_%s' % key), default=reg_map_dict[key].get('format') == 'hex'), sg.Radio('Dec', str('_KEY_FORMAT_%s' % key), key=str('_KEY_FORMAT_DEC_%s' % key), default=reg_map_dict[key].get('format') == 'dec'), sg.Radio('Bin', str('_KEY_FORMAT_%s' % key), key=str('_KEY_FORMAT_BIN_%s' % key), default=reg_map_dict[key].get('format') == 'bin'), ]) # Add IP format for network config registers if reg_map_dict[key].get('format') == 'ip': response[-1].extend([ sg.Radio('Ip', str('_KEY_FORMAT_%s' % key), key=str('_KEY_FORMAT_IP_%s' % key), default=reg_map_dict[key].get('format') == 'ip') ]) return response
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')
layout = [[ sg.T('Notes:', pad=((3, 0), 0)), sg.In(size=(44, 1), background_color='white', text_color='black', key='notes') ], [ sg.T('Output:', pad=((3, 0), 0)), sg.T('', size=(44, 1), text_color='white', key='output') ], [ sg.CBox('Checkbox:', default=True, pad=((3, 0), 0), disabled=True, key='cbox'), sg.Listbox((1, 2, 3, 4), size=(8, 3), disabled=True, key='listbox'), sg.Radio('Radio 1', default=True, group_id='1', disabled=True, key='radio1'), sg.Radio('Radio 2', default=False, group_id='1', disabled=True,
str(first_year) + ';' + str(last_year) + ']') elif start_year > end_year: sg.popup('Start year is after end year') else: datavalid = True except: sg.popup('Invalid input. Must be YYYY in range [' + str(first_year) + ';' + str(last_year) + ']') #Choosing the type to view in plot type_to_viz = [] datavalid = False while datavalid == False: layout = [[ sg.Text('Which type of content do you want to visualize ? ') ], [[sg.CBox(anitype, default=True) for anitype in anime_types]], [sg.OK(), sg.Cancel()]] window = sg.Window('Choosing anime type', layout) event, values = window.read() window.close() if event == sg.WIN_CLOSED or event == 'Cancel': exit() for i in range(len(values)): if values[i] == True: type_to_viz.append(anime_types[i]) if len(type_to_viz) != 0: datavalid = True else:
def change_settings(settings, window_location=(None, None)): global APP_DATA, API_KEY try: nearest_postal = json.loads( request.urlopen('http://ipapi.co/json').read())['postal'] except Exception as e: print('Error getting nearest postal', e) nearest_postal = '' layout = [ [sg.T('Enter Zipcode or City for your location')], [ sg.I(settings.get('-location-', nearest_postal), size=(15, 1), key='-LOCATION-'), sg.T('City') ], [ sg.I(settings.get('-country-', 'US'), size=(15, 1), key='-COUNTRY-'), sg.T('Country') ], [ sg.I(settings.get('-friends name-', ''), size=(15, 1), key='-FRIENDS NAME-'), sg.T('Who') ], [sg.I(settings.get('-api key-', ''), size=(32, 1), key='-API KEY-')], [ sg.CBox('Use Metric For Temperatures', default=settings.get('-celsius-', False), key='-CELSIUS-') ], [ sg.B('Ok', border_width=0, bind_return_key=True), sg.B('Register For a Key', border_width=0, k='-REGISTER-'), sg.B('Cancel', border_width=0) ], ] window = sg.Window('Settings', layout, location=window_location, no_titlebar=True, keep_on_top=True, border_depth=0) event, values = window.read() window.close() if event == '-REGISTER-': sg.popup( 'Launching browser so you can signup for the "Current Weather" service from OpenWeatherMap.org to get a Free API Key', 'Click OK and your browser will open', r'Visit https://home.openweathermap.org/ for more information', location=window_location) # Register to get a free key webbrowser.open(r'https://home.openweathermap.org/users/sign_up') if event == 'Ok': user_location = settings['-location-'] = values['-LOCATION-'] settings['-country-'] = values['-COUNTRY-'] API_KEY = settings['-api key-'] = values['-API KEY-'] settings['-celsius-'] = values['-CELSIUS-'] settings['-friends name-'] = values['-FRIENDS NAME-'] else: API_KEY = settings['-api key-'] user_location = settings['-location-'] if user_location is not None: if user_location.isnumeric() and len( user_location) == 5 and user_location is not None: APP_DATA['Postal'] = user_location APP_DATA['City'] = '' else: APP_DATA['City'] = user_location APP_DATA['Postal'] = '' APP_DATA['Country'] = settings['-country-'] if settings['-celsius-']: APP_DATA['Units'] = 'metric' else: APP_DATA['Units'] = 'imperial' return settings
def the_gui(): """ Starts and executes the GUI Reads data from a global variable and displays Returns when the user exits / closes the window """ global thread_done, message, progress sg.theme('Light Brown 3') layout = [ [sg.Text('Long task to perform example')], [sg.Output(size=(80, 12))], [ sg.Text('Number of seconds your task will take'), sg.Input(key='-SECONDS-', size=(5, 1)), sg.Button('Do Long Task', bind_return_key=True), sg.CBox('ONE chunk, cannot break apart', key='-ONE CHUNK-') ], [ sg.Text('Work progress'), sg.ProgressBar(total, size=(20, 20), orientation='h', key='-PROG-') ], [sg.Button('Click Me'), sg.Button('Exit')], ] window = sg.Window('Multithreaded Window', layout) one_chunk = False sg.popup_animated(None) # --------------------- EVENT LOOP --------------------- while True: event, values = window.read(timeout=100) if event in (None, 'Exit'): break elif event.startswith('Do'): seconds = float(values['-SECONDS-']) one_chunk = values['-ONE CHUNK-'] print('Thread Starting! Long work....sending value of {} seconds'. format(seconds)) threading.Thread(target=long_operation_thread, args=(seconds, ), daemon=True).start() elif event == 'Click Me': print('Your GUI is alive and well') # --------------- Check for incoming messages from threads --------------- if thread_done is True: print('The thread has finished!') print(f'message = {message}') # reset everything for the next run sg.popup_animated(None) # just in case one's running, stop it thread_done = one_chunk = False message, progress = '', 0 window['-PROG-'].update_bar(total, total) # show the bar as maxed out if one_chunk: # flag signifies the thread is taking to take one big chunk of time sg.popup_animated(sg.DEFAULT_BASE64_LOADING_GIF, background_color='white', transparent_color='white', time_between_frames=100) elif progress != 0: window['-PROG-'].update_bar( progress, total) # update the progress bar if non-zero # if user exits the window, then close the window and exit the GUI func window.close()
# ------ Column Definition ------ # column1 = [[sg.Text('Column 1', justification='center', size=(10, 1))], [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 1')], [sg.Spin(values=['Spin Box 1', '2', '3'], initial_value='Spin Box 2')], [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]] layout = [ [sg.Menu(menu_def, tearoff=True)], [sg.Text('(Almost) All widgets in one Window!', size=( 30, 1), justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE)], [sg.Text('Here is some text.... and a place to enter text')], [sg.InputText('This is my text')], [sg.Frame(layout=[ [sg.CBox('Checkbox', size=(10, 1)), sg.CBox('My second checkbox!', default=True)], [sg.Radio('My first Radio! ', "RADIO1", default=True, size=(10, 1)), sg.Radio('My second Radio!', "RADIO1")]], title='Options', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')], [sg.MLine(default_text='This is the default Text should you decide not to type anything', size=(35, 3)), sg.MLine(default_text='A second multi-line', size=(35, 3))], [sg.Combo(('Combobox 1', 'Combobox 2'),default_value='Combobox 1', size=(20, 1)), sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)], [sg.OptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option 3'))], [sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3)), sg.Frame('Labelled Group', [[ sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=25, tick_interval=25), sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=75), sg.Slider(range=(1, 100), orientation='v', size=(5, 20), default_value=10), sg.Col(column1)]]) ],
def main_window(self): layout = [ [sg.Text("Choose Operation to perform:")], [ sg.Combo(['Copy', 'Move'], default_value='Move', key='OPERATION'), sg.CBox( "Overwrite files", tooltip= "Incoming files will replace files of the same names in the destination", key="OVERWRITE") ], [ sg.Frame(layout=[[sg.Text("Sort by Type")], [ sg.Radio("Enabled", "RADIO1", default=False, key='SBYTE', enable_events=True), sg.Radio("Disabled", "RADIO1", default=True, key='SBYTD', enable_events=True) ]], title='Sorting Options', title_color='red', relief=sg.RELIEF_SUNKEN) ], [sg.Text("Choose filetype:")], [ sg.Combo( # Options for type of file [ "Archive ('.zip', '.rar'...)", "Image ('.png', '.jpg'...)", "Text ('.txt', '.docx'...)", "Video ('.mp4', '.mov'...)", "Audio ('.mp3', '.wav'...)" ], key='FILETYPE', enable_events=True) ], [sg.Ok(), sg.Cancel()] ] window = sg.Window('Choose filetype to move', layout, default_element_size=(40, 1)) while True: event, values = window.read() if event in (sg.WIN_CLOSED, 'Cancel'): break elif event in 'Ok': if values['FILETYPE'] not in file_type: append_file_type(values['FILETYPE']) run_fmover = FileMover() append_mode(values['OPERATION']) if len(sort_list) == 1: for value in sort_list: if value == 'Sort by Type': run_fmover.filemover(values['OPERATION'], value, values['OVERWRITE']) else: run_fmover.filemover(values['OPERATION'], None, values['OVERWRITE']) else: run_fmover.filemover(values['OPERATION'], None, values['OVERWRITE']) else: run_fmover = FileMover() append_mode(values['OPERATION']) if len(sort_list) == 1: for value in sort_list: if value == 'Sort by Type': run_fmover.filemover(values['OPERATION'], value, values['OVERWRITE']) else: run_fmover.filemover(values['OPERATION'], None, values['OVERWRITE']) else: run_fmover.filemover(values['OPERATION'], None, values['OVERWRITE']) elif event in 'SBYTE': if values['SBYTE'] is True: sort_list.append('Sort by Type') else: pass elif event in 'SBYTD': if values['SBYTD'] is True: sort_list.clear() else: pass else: pass window.close()
def __init__(self): self.front_picture = 'graphic/front_picture.png' sg.theme('DarkBlue') # ------------------------------------ LAYOUT COLUMNS ------------------------------------ # COLUMN 1 self.file_list_column = [ [ sg.Text("Import Video"), sg.In(size=(30, 1), enable_events=True, key="-FOLDER-"), sg.FolderBrowse(), ], [ sg.Button("Videos", enable_events=True, key="-VIDEO FOLDER-"), sg.Button("Analyzes", enable_events=True, key="-ANALYZES-"), ], [ sg.Listbox(values=[], enable_events=True, size=(25, 30), key='-FILE LIST-', auto_size_text=False, font=("Helvetica", 20)), ], ] # COLUMN 2 self.image_viewer_column = [ [ sg.Text(text="Video options", size=(20, 1), font=("Helvetica", 15)), ], [ sg.Button("Delete video", enable_events=True, key="-DELETE VIDEO-", disabled=True, button_color=["white", "red"]), sg.Button("View video", enable_events=True, key="-VIEW VIDEO-", disabled=True), sg.Button("Analyze", enable_events=True, key="-CAM SHIFT-", disabled=True), sg.Text( text="Trace color:", size=(9, 1), key="-TRACE COLOR-", visible=True, ), sg.CBox('Blue', key='-COLOR BLUE-', enable_events=True), sg.CBox('X-Velocity Color', key='-COLOR XV-', enable_events=True, default=True), sg.CBox('Y-Velocity Color', key='-COLOR YV-', enable_events=True), ], [ sg.HSeparator(), ], [ sg.In(size=(5, 1), enable_events=True, key="-H MIN-", default_text='0'), sg.In(size=(5, 1), enable_events=True, key="-H MAX-", default_text='255'), sg.In(size=(5, 1), enable_events=True, key="-S MIN-", default_text='0'), sg.In(size=(5, 1), enable_events=True, key="-S MAX-", default_text='255'), sg.In(size=(5, 1), enable_events=True, key="-V MIN-", default_text='254'), sg.In(size=(5, 1), enable_events=True, key="-V MAX-", default_text='255'), sg.CBox('Video', key='-HSV VIDEO-', default=True), sg.Button("HSV", enable_events=True, key="-HSV-", disabled=True), ], [ sg.HSeparator(), ], [ sg.Text(text="Max speed", size=(9, 1), key="-MS-", visible=True), sg.Text(text="none", size=(9, 1), key="-MAX SPEED-", visible=True), ], [ sg.HSeparator(), ], [ sg.Text(text="file_name", size=(40, 1), key="-TOUT-", visible=True, font=("Helvetica", 25)), ], [ sg.Image(key="-IMAGE FRAME-", filename=self.front_picture), ], ] # ------------------------------------ FULL LAYOUT ------------------------------------ self.layout = [[ sg.Text(text="Disc Golf Video Analyzer", size=(30, 1), key="-DGVA-", visible=True, font=("Helvetica", 40), justification="center", pad=((400, 400), (1, 1))) ], [ sg.HSeparator(), ], [ sg.Column(self.file_list_column), sg.VSeperator(), sg.Column(self.image_viewer_column), ]] self.window = sg.Window("Disc Golf Tracker", self.layout)
_default_vid = getPstateVid(0) _ratio = getRatio(PSTATES[0]) _current_freq = int(_ratio * 100) #sg.theme('Dark Teal 9') sg.set_options(icon='icon.png', element_padding=(5, 5), margins=(1, 1), border_width=0) # The tab 1, 2, 3 layouts - what goes inside the tab tab1_layout = [ [ sg.CBox('OC Mode', default=_oc_mode, key='ocMode', enable_events=True) ], [ sg.Text(' All Core Frequency', size=(18, 1)), sg.Spin(values=[x for x in range(550, 7000, 25)], initial_value=_current_freq, enable_events=True, disabled=not _oc_mode, size=(5, 1), key='cpuOcFrequency'), sg.Text('MHz'), ], [ sg.Text(' Overclock VID', size=(18, 1)), sg.Spin(values=[x for x in range(VID_MAX, VID_MIN, -1)],
def 控件(): menu_def = [['&File', ['&Open', '&Save', 'E&xit', 'Properties']], ['&Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ],['&Help', '&About...'], ] # ------ Column Definition ------ # #当较小的元素左侧有一个较高的元素时,则需要一列。 #将来也放到layout的一个控件里面sg.Column(col, background_color='blue') column1 = [[sg.Text('Column 1', justification='center', size=(10, 1))], [sg.Spin(values=('Spin Box 1', '2', '3'),initial_value='Spin Box 1')], [sg.Spin(values=('Spin Box 1', '2', '3'),initial_value='Spin Box 2')], [sg.Spin(values=('Spin Box 1', '2', '3'), initial_value='Spin Box 3')]] layout = [ [sg.Menu(menu_def, tearoff=True)], #文本显示内容,那个relief参数可以添加阴影效果 #sg.RELIEF_RIDGE,RELIEF_RAISED为外凸效果 #sg.RELIEF_FLAT平滑效果,也就是默认值 #RELIEF_GROOVE,sg.RELIEF_SUNKEN内凹效果 #RELIEF_SOLID黑框选中 [sg.Text('(Almost) All widgets in one Window!', size=( 30, 1), justification='center', font=("Helvetica", 25),relief=sg.RELIEF_RIDGE)], [sg.Text('Here is some text.... and a place to enter text')], # 单行文本输入框 [sg.InputText('This is my text')], #框架组件,之前说过 [sg.Frame(layout=[ #复选框,将来valuse的返回值只有False,True [sg.CBox('这里输什么将来就显示什么', size=(10, 1)), sg.CBox('My second checkbox!', default=True)], #这里是单选框,第一个参数是实际显示值,第二个是id,这个只要学过HTML的都懂吧 [sg.Radio('My first Radio! ', "123",default=True, size=(10, 1)), sg.Radio('My second Radio!', "123")]], title='Options', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')], #这个是多行输入框 [sg.MLine(default_text='This is the default Text should you decide not to type anything', size=(35, 3)), sg.MLine(default_text='A second multi-line', size=(35, 3))], #这个是多选一框(好像叫selectbox),就是那种选择出身年份的,name和value都很好懂 [sg.Combo(('Combobox 1', 'Combobox 2'), default_value='Combobox 1', size=(20, 1)), #用来滑动的条,你可以选择滑动条的范围,方向"h"/"v",尺寸,默认值 #实际值就是你拖动的结果 sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)], #不知道是个啥,跟上面那个Combo很像 [sg.OptionMenu(('Menu Option 1', 'Menu Option 2', 'Menu Option 3'))], #就是你平时用browse实际出来的那个有拖动条的那种 #功能上跟Combo很像 [sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3'), size=(30, 3))], #可以画线,还可以展位(用" ") [sg.Text('_' * 100)], #File选择器,值就是你选中的File的路径 [ sg.FolderBrowse()], #快捷方式按钮,还有提示tooltip就是你把光标移动到控件旁边后会提示的小白色的提示框 [sg.Submit(tooltip='Click to submit this form'), sg.Cancel()]] window = sg.Window('Everything bagel', layout, no_titlebar=True, default_element_size=(40, 1), grab_anywhere=False, ) event, values = window.read()
def HowDoI(): ''' Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle Excellent example of 2 GUI concepts 1. Output Element that will show text in a scrolled window 2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but doesn't close the form :return: never returns ''' # ------- Make a new Window ------- # # give our form a spiffy set of colors sg.change_look_and_feel('GreenTan') layout = [[ sg.Text('Ask and your answer will appear here....', size=(40, 1)) ], [sg.Output(size=(120, 30), font=('Helvetica 10'))], [ sg.Spin(values=(1, 2, 3, 4), initial_value=1, size=(2, 1), key='Num Answers', font='Helvetica 15'), sg.Text('Num Answers', font='Helvetica 15'), sg.CBox('Display Full Text', key='full text', font='Helvetica 15'), sg.Text('Command History', font='Helvetica 15'), sg.Text('', size=(40, 3), text_color=sg.BLUES[0], key='history') ], [ sg.MLine(size=(85, 5), enter_submits=True, key='query', do_not_clear=False), sg.Button('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True), sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0])) ]] window = sg.Window('How Do I ??', layout, default_element_size=(30, 2), font=('Helvetica', ' 13'), default_button_element_size=(8, 2), return_keyboard_events=True, no_titlebar=True, grab_anywhere=True) # ---===--- Loop taking in user input and using it to query HowDoI --- # command_history = [] history_offset = 0 while True: event, values = window.read() if event == 'SEND': query = values['query'].rstrip() # print(query) # send the string to HowDoI QueryHowDoI(query, values['Num Answers'], values['full text']) command_history.append(query) history_offset = len(command_history) - 1 # manually clear input because keyboard events blocks clear window['query'].update('') window['history'].update('\n'.join(command_history[-3:])) elif event == None or event == 'EXIT': # if exit button or closed using X break # scroll back in history elif 'Up' in event and len(command_history): command = command_history[history_offset] # decrement is not zero history_offset -= 1 * (history_offset > 0) window['query'].update(command) # scroll forward in history elif 'Down' in event and len(command_history): # increment up to end of list history_offset += 1 * (history_offset < len(command_history) - 1) command = command_history[history_offset] window['query'].update(command) elif 'Escape' in event: # clear currently line window['query'].update('') window.close()
def change_settings(settings): data_is_deaths = settings.get('data source', 'confirmed') == 'deaths' layout = [ [sg.T('Color Theme')], [ sg.T('Display'), sg.Radio('Deaths', 1, default=data_is_deaths, key='-DATA DEATHS-'), sg.Radio('Confirmed Cases', 1, default=not data_is_deaths, key='-DATA CONFIRMED-') ], [ sg.Combo(sg.theme_list(), default_value=settings.get('theme', DEFAULT_SETTINGS['theme']), size=(20, 20), key='-THEME-') ], [ sg.T('Display Rows', size=(15, 1), justification='r'), sg.In(settings.get('rows', ''), size=(4, 1), key='-ROWS-') ], [ sg.T('Display Cols', size=(15, 1), justification='r'), sg.In(settings.get('cols', ''), size=(4, 1), key='-COLS-') ], [ sg.T('Graph size in pixels'), sg.In(settings.get('graph_x_size', ''), size=(4, 1), key='-GRAPHX-'), sg.T('X'), sg.In(settings.get('graph_y_size', ''), size=(4, 1), key='-GRAPHY-') ], [ sg.CBox('Autoscale Graphs', default=settings.get('autoscale', True), key='-AUTOSCALE-'), sg.T('Max Graph Value'), sg.In(settings.get('graphmax', ''), size=(6, 1), key='-GRAPH MAX-') ], [ sg.T('Number of days to display (0 for all)'), sg.In(settings.get('display days', ''), size=(4, 1), key='-DISPLAY DAYS-') ], [ sg.B('Ok', border_width=0, bind_return_key=True), sg.B('Cancel', border_width=0) ], ] window = sg.Window('Settings', layout, icon=ICON, keep_on_top=True, border_depth=0) event, values = window.read() window.close() if event == 'Ok': settings['theme'] = values['-THEME-'] settings['rows'] = int(values['-ROWS-']) settings['cols'] = int(values['-COLS-']) settings['autoscale'] = values['-AUTOSCALE-'] settings['graphmax'] = values['-GRAPH MAX-'] try: settings['graph_x_size'] = int(values['-GRAPHX-']) settings['graph_y_size'] = int(values['-GRAPHY-']) except: settings['graph_x_size'] = GRAPH_SIZE[0] settings['graph_y_size'] = GRAPH_SIZE[1] try: settings['display days'] = int(values['-DISPLAY DAYS-']) except: settings['display days'] = 0 settings['data source'] = 'deaths' if values[ '-DATA DEATHS-'] else 'confirmed' return settings
def layout(col, sel_func=[]): """ f_path(一番左の列)のみ非表示にしておく """ vm = [True for i in range(len(col))] vm[0] = False """ layoutの部品を先に定義 """ Fit_range_button = sg.Button('Off', size=(3, 1), button_color='white on red', key='-B-') menu_def = [[ '&File', ["&Save as csv", "Save as pkl", "Load pkl", "Undo", 'E&xit'] ]] Browse = [ # sg.Text('Your Folder', size=(15, 1), justification='right'), sg.InputText('', key="path", enable_events=True), sg.FolderBrowse(key="File") ] S = (12, 1) buttons = [[sg.Button("Column Setting", size=S)], [sg.Button("Check fit", size=S, disabled=True)], [sg.Button("Modify data", key="modify", size=S, disabled=True)], [sg.Button("test2")]] def sel(axis): return sg.Frame( "", border_width=0, element_justification="center", pad=(0, 10), layout=[[sg.Text(axis)], [ sg.Listbox([], size=(6, 6), select_mode=sg.LISTBOX_SELECT_MODE_SINGLE, enable_events=True, default_values="", key=axis) ]]) data_sel = [ [ sel("x"), sel("y"), sel("z"), sg.CBox("y_offset?", enable_events=True) ], [ sg.OptionMenu(["Nomal", "Color", "3D"], key="plt_mode"), sg.OptionMenu(DATA_MODES, key="data_mode"), sg.Button("Plot", disabled=True) ], ] plot_menu = sg.Frame("Plot menu", layout=[ [sel("_z")], ]) Fit_controler = FG.layout(sel_func) finfo = sg.Frame("Fitting Info", border_width=0, layout=[[ sg.MLine(default_text="", size=(30, 10), key="info", disabled=True) ]]) """ GUI のレイアウトの設定 """ return [ [sg.Menu(menu_def, tearoff=False)], [ sg.Text("拡張子", size=(5, 1)), sg.Input(".txt", key="fe", size=(5, 1), disabled=True), sg.Input("", key="folder", enable_events=True, visible=False), sg.FolderBrowse(button_text="Add folder", key="add_folder"), sg.FilesBrowse(button_text="Add data files", key="add_files", target="names", enable_events=True), sg.Text("Sort by"), sg.Combo(Vcol, enable_events=True, default_value="filename", key="sort"), sg.CBox("Reverse order", key="sort_order", enable_events=True), sg.Input("", key="names", enable_events=True, visible=False), sg.Button("test") ], # Browse, [ sg.Frame( "", buttons, key="buttons", border_width=1, ), sg.Table( key='-TABLE-', values=[], headings=col, visible_column_map=vm, col_widths=[23, 23, 5], # row_colors=[(0, "red", "white"), (4, "white", "#aaaaff")], justification='right', max_col_width=50, def_col_width=8, auto_size_columns=False, enable_events=True, select_mode=sg.TABLE_SELECT_MODE_EXTENDED, right_click_menu=["", ["Select all", "My fit"]], background_color='#aaaaaa', alternating_row_color='#888888', display_row_numbers=True), finfo ], [sg.HorizontalSeparator()], [ sg.Frame("Data menu", data_sel, element_justification="center"), plot_menu ], [ sg.Frame("Fit panel", Fit_controler, relief=sg.RELIEF_RAISED, border_width=5) ] ]