def Expense_data_win(): sg.theme('LightBlue') # current date date = datetime.date.today() # canvas_size wide = 900 # x tall = 500 # y # expense layout tab1_layout = [ [ sg.Text('Description '), sg.Input(key='-DES-', background_color='white', text_color='Black', do_not_clear=False) ], [ sg.Text('Amount '), sg.Input(key='-AMT-', background_color='white', text_color='Black', do_not_clear=False) ], [ sg.Text(' '), sg.Button('Save', key='-SAVE-'), ], [ sg.Frame('Category', [[sg.Radio('Income', 'expense', key='-IN-')], [sg.Radio('Books', 'expense', key='-BOOKS-')], [sg.Radio('Tutoring fee', 'expense', key='-TUT-')], [sg.Radio('Tuition', 'expense', key='-SCH-')], [sg.Radio('Lodging', 'expense', key='-LODGE-')], [sg.Radio('Transport', 'expense', key='-TRANS-')], [sg.Radio('Outfit', 'expense', key='-OUTFIT-')], [sg.Radio('Entertainment', 'expense', key='-ENT-')], [sg.Radio('Other', 'expense', key='-OTH-')]], title_color='blue') ] ] # categories category = { 'income': 'Income:', 'book': 'Books:', 'tutor': 'Tutoring fee:', 'school': 'Tuition fee:', 'transport': 'Transport:', 'outfit': 'shopping:', 'entertainment': 'Entertainment:', 'lodge': 'Lodging:', 'other': 'Others:' } # this fetches the header from the database cursor.execute('SELECT * FROM EXPENSES') header = [i[0] for i in cursor.description] # this fetches the data from the expenses table cursor.execute('SELECT * FROM EXPENSES') data = cursor.fetchall() # expense list layout tab2_layout = [[ sg.Table( values=data, headings=header, col_widths=(19, 50), auto_size_columns=False, display_row_numbers=False, justification='left', key='-TABLE-', row_height=25, tooltip='this is a table', num_rows=(21), size=(150, 20), alternating_row_color='lightgreen', pad=(0, 0), header_background_color='darkgreen', text_color='Black', background_color='white', ) ], [sg.Button('REFRESH'), sg.Button('Restart Table')]] # graph plot fig = matplotlib.figure.Figure(figsize=(10, 5), dpi=100) # expense graph tab3_layout = [ [sg.T('Your Expense Graph')], [sg.Canvas( size=(wide, tall), key='-CANVAS-', )], [sg.Button('Show')], ] # All layout together layout = [[ sg.Text(' '), sg.Text('EXPENSES TRACKER V1.0', size=(30, 1), justification='center', font=( "Helvetica", 25, ), text_color='Blue') ], [ sg.TabGroup([[ sg.Tab( 'New Expenses', tab1_layout, ), sg.Tab('Expenses', tab2_layout), sg.Tab('Expense Graph', tab3_layout) ]]) ], [ sg.T('Date:', text_color='blue'), sg.T(date, text_color='Blue'), sg.T(' '), sg.T('By: Chidi', text_color='Blue', justification='right') ]] expense_window = sg.Window('Expense Tracker', layout, disable_minimize=False, resizable=False, icon='images/wallet.ico', finalize=True) while True: event, values = expense_window.read() if event == sg.WIN_CLOSED: break if values['-IN-']: """ if true it takes in the input of the user and stores it to the database and then updates the table with with the new values""" income(date, values['-DES-'], category['income'], values['-AMT-']) expense_replace_null() balance_update() cursor.execute("SELECT * FROM EXPENSES") update = cursor.fetchall() expense_window['-TABLE-'].update(update) if values['-TUT-']: """ if true it takes in the input of the user and subtracts it from the balance and stores it to the database depending on the category and then updates the table with with the new values """ expenses(date, values['-DES-'], category['tutor'], values['-AMT-']) balance_update() income_replace_null() cursor.execute("SELECT * FROM EXPENSES") update = cursor.fetchall() expense_window['-TABLE-'].update(update) if values['-BOOKS-']: """ if true it takes in the input of the user and subtracts it from the balance and stores it to the database depending on the category and then updates the table with with the new values """ expenses(date, values['-DES-'], category['book'], values['-AMT-']) balance_update() income_replace_null() cursor.execute("SELECT * FROM EXPENSES") update = cursor.fetchall() expense_window['-TABLE-'].update(update) if values['-TRANS-']: """ if true it takes in the input of the user and subtracts it from the balance and stores it to the database depending on the category and then updates the table with with the new values """ expenses(date, values['-DES-'], category['transport'], values['-AMT-']) balance_update() income_replace_null() cursor.execute("SELECT * FROM EXPENSES") update = cursor.fetchall() expense_window['-TABLE-'].update(update) if values['-SCH-']: """ if true it takes in the input of the user and subtracts it from the balance and stores it to the database depending on the category and then updates the table with with the new values """ expenses(date, values['-DES-'], category['school'], values['-AMT-']) balance_update() income_replace_null() cursor.execute("SELECT * FROM EXPENSES") update = cursor.fetchall() expense_window['-TABLE-'].update(update) if values['-OUTFIT-']: """ if true it takes in the input of the user and subtracts it from the balance and stores it to the database depending on the category and then updates the table with with the new values """ expenses(date, values['-DES-'], category['outfit'], values['-AMT-']) balance_update() income_replace_null() cursor.execute("SELECT * FROM EXPENSES") update = cursor.fetchall() expense_window['-TABLE-'].update(update) if values['-LODGE-']: """ if true it takes in the input of the user and subtracts it from the balance and stores it to the database and then updates the table with with the new values """ expenses(date, values['-DES-'], category['lodge'], values['-AMT-']) balance_update() income_replace_null() cursor.execute("SELECT * FROM EXPENSES") update = cursor.fetchall() expense_window['-TABLE-'].update(update) if values['-ENT-']: """ if true it takes in the input of the user and subtracts it from the balance and stores it to the database depending on the category and then updates the table with with the new values """ expenses(date, values['-DES-'], category['entertainment'], values['-AMT-']) balance_update() income_replace_null() cursor.execute("SELECT * FROM EXPENSES") update = cursor.fetchall() expense_window['-TABLE-'].update(update) if values['-OTH-']: """ if true it takes in the input of the user and subtracts it from the balance and stores it to the database depending on the category and then updates the table with with the new values """ expenses(date, values['-DES-'], category['other'], values['-AMT-']) balance_update() income_replace_null() cursor.execute("SELECT * FROM EXPENSES") update = cursor.fetchall() expense_window['-TABLE-'].update(update) if event == 'REFRESH': # this updates the window balance_update() cursor.execute("SELECT * FROM EXPENSES") update = cursor.fetchall() expense_window['-TABLE-'].update(update) if event == 'Restart Table': """ this deletes all records from database and refreshes the window """ Delete_data() update = cursor.fetchall() expense_window['-TABLE-'].update(update) if event == 'Show': fig.add_subplot().plot(graph_data()) fig_canvas_agg = draw_figure(expense_window['-CANVAS-'].TKCanvas, fig) conn.close() expense_window.close()
def menu(): """Esto es el menu de configuracion donde podras crear la partida segun la dificultad, cantidad de fichas o valor de las fichas. En caso de querer ver el link del repositorio apretar el boton help. Esta funcion del menu no anda en la maquina virtual ya que no tiene un navegador por defecto""" sg.ChangeLookAndFeel('DarkGrey6') fichas_propias = { } #creo un dic para saber si el jugador modifica el valor o la cantidad de una letra # ------ Menu Definicion ------ # menu_def = [['&Help', ('Link del Repositorio')], ["&Reglas", ('Reglas del juego')]] layout = [ [sg.Menu(menu_def, tearoff=False)], [ sg.Text('Configuracion del juego scrabble!', size=(26, 1), justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE) ], [ sg.Frame(layout=[[ sg.Checkbox('Datos predefinidos', size=(29, 1), default=True, key="_predefinido_", enable_events=True), sg.Text("(Valores predefinidos para las letras)") ], [ sg.Radio('Dificultad facil ', "Dificultad", default=True, size=(10, 1)), sg.Radio('Dificultad Media!', "Dificultad"), sg.Radio('Dificultad Dificil', "Dificultad") ]], title='Configuracion del juego', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags') ], [ sg.Text("Tiempo de la partida"), sg.Slider(range=(1, 20), orientation='h', size=(13, 25), default_value=10, enable_events=False) ], [ sg.Frame('Puntuacion de letras', [[ sg.InputOptionMenu( ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'LL', 'M', 'N', 'O', 'P', 'Q', 'R', 'RR', 'S', 'T', 'U', 'V', 'V', 'W', 'X', 'Y', 'Z')) ], [ sg.Text("Modificar cantidad"), sg.Slider(range=(1, 15), orientation='v', size=(10, 25), default_value=6, enable_events=False), sg.Text("Modificar valor"), sg.Slider(range=(1, 20), orientation='v', size=(10, 25), default_value=6, enable_events=False) ], [sg.Button("Modificar", key="_modificar_")]], visible=False, key="slider") ], [sg.Text('_' * 70)], [ sg.Button(("Confirmar configuracion"), key="__jugar__"), sg.Cancel("Cancel") ] ] window = sg.Window('Menu', layout, default_element_size=(40, 1), grab_anywhere=False) while True: event, values = window.Read() if event == sg.WIN_CLOSED: window.Close() break else: if values["_predefinido_"] == False: window["slider"].update( visible=True ) #si valores predefinidos es falso,mostrar tabla para modificar los valores y la cantidad. if values["_predefinido_"] == True: window["slider"].update( visible=False ) #si valores predefinidos es verdadero,no mostrar tabla. if (event == "_modificar_"): fichas_propias[values[5]] = { "cantidad": int(values[6]), "valor": int(values[7]) } #modifico la cantidad y el valor de las letras sg.Popup("Se modifico correctamente!", title="Letra") if ( event == "Link del Repositorio" ): #lleva al link del repositorio si se apreta help y link del repositorio wb.open( "https://github.com/luciomolina365/ScrabbleAR_Grupo18", new=0, autoraise=True) if event == "Reglas del juego": reglas = leer_reglas() sg.popup(reglas, title="Reglas") elif (event == "Cancel"): window.Close() ScrabbleAR.Menu_principal() break elif ( event == "__jugar__" ): #indico en una variable q dificultad va a tener el juego if values[1] == True: Dificultad_final = 1 elif values[2] == True: Dificultad_final = 2 else: Dificultad_final = 3 if ( values["_predefinido_" == True] ): #esto guarda en fichas_finales las fichas que se utilizaran fichas_finales = {} else: fichas_finales = fichas_propias Configuracion = {} Configuracion["minutos"] = values[4] Configuracion["dificultad"] = Dificultad_final Configuracion["letras"] = fichas_finales Configuracion["Puntaje_jugador"] = 0 Configuracion["Puntaje_computadora"] = 0 Config = definir_configuracion( Configuracion ) #se carga la configuracion para poder mandar correctamente todos los datos al tablero window.Close() sg.Popup("Se guardo la configuración correctamente!", title="Configuración") Tablero.juego(Config) break window.Close()
def userform(): """GUI USERFORM TO SET OPTIONS: Add new variable at 3 places, Lookup ADD [n]""" global CAPTURE_FOLDER global LOG_EXTN global REQUEST_FILE global LOG_FOLDER global OUTPUT_FOLDER global OUTPUT_FILE_EXTENSION global LOG_WARNING global LINENO_ON_DEL global ONSCREEN_DISPLAY global SAVE_TO_FILE global CLUB_OUTPUT_FOR_ALL_DEVICE global MOP_EXCEL_TEMPLATE global MOP_OUTPUT_FOLDER global MOP_EXCEL_OUTPUT global LOG_LEVEL_MIN global TASK_COMPLETE_NOTICE global ACL_BASE global USE_SOURCE_NAT_IP global USE_DESTINATION_NAT_IP global NINJA #### ADD 1 # boot = None version = VERSION header = f'FW LMAC REQUEST - {version}' tab1 = [[ sg.Frame(title='Parameters', title_color='red', size=(600, 4), relief=sg.RELIEF_RIDGE, layout=[ [sg.Text('', font=("TimesBold", 5))], [ sg.Text('Configuration backup parameters :' + ' ' * 40, font=('TimesBold', 14)) ], [sg.Text('-' * 200, font=("TimesBold", 5))], [ sg.Text("Configuration captured folder :"), sg.InputText(key='CAPTURE_FOLDER', size=(20, 1), default_text=CAPTURE_FOLDER), sg.FolderBrowse() ], [ sg.Text("Configuration captured files extension :"), sg.InputText(key='LOG_EXTN', size=(20, 1), default_text=LOG_EXTN) ], [sg.Text('', font=("TimesBold", 5))], [ sg.Text('Input/Request File Parameters :', font=('TimesBold', 14)) ], [sg.Text('-' * 200, font=("TimesBold", 5))], [ sg.Text("Rule change request file (Excel) :"), sg.InputText(key='REQUEST_FILE', size=(20, 1), default_text=REQUEST_FILE), sg.FileBrowse() ], [ sg.Text("MOP Template file (Excel) :"), sg.InputText(key='MOP_EXCEL_TEMPLATE', size=(30, 1), default_text=MOP_EXCEL_TEMPLATE), sg.FileBrowse(key='MOP1') ], [sg.Text('', font=("TimesBold", 5))], [sg.Text('Output Parameters :', font=('TimesBold', 14))], [sg.Text('-' * 200, font=("TimesBold", 5))], [ sg.Text("Activity Log folder :"), sg.InputText(key='LOG_FOLDER', size=(20, 1), default_text=LOG_FOLDER), sg.FolderBrowse() ], [ sg.Text("Configuration Output folder :"), sg.InputText(key='OUTPUT_FOLDER', size=(20, 1), default_text=OUTPUT_FOLDER), sg.FolderBrowse() ], [ sg.Text("Configuration Output file extension :"), sg.InputText(key='OUTPUT_FILE_EXTENSION', size=(20, 1), default_text=OUTPUT_FILE_EXTENSION) ], [ sg.Text("MOP Excel Output folder :"), sg.InputText(key='MOP_OUTPUT_FOLDER', size=(20, 1), default_text=OUTPUT_FOLDER), sg.FolderBrowse(key='MOP2') ], [sg.Text('', font=("TimesBold", 5))], ]), ]] tab2 = [[ sg.Frame( title='Options', title_color='red', size=(600, 4), relief=sg.RELIEF_RIDGE, layout=[ [sg.Text('-' * 200, font=("TimesBold", 5))], [ sg.Checkbox('Task Complete Notice', default=TASK_COMPLETE_NOTICE, key='TASK_COMPLETE_NOTICE') ], [ sg.Checkbox('"log warning" suffix in rules output', default=LOG_WARNING, key='LOG_WARNING') ], [ sg.Checkbox('Line numbers on Negating rules', default=LINENO_ON_DEL, key='LINENO_ON_DEL') ], [sg.Text('-' * 200, font=("TimesBold", 5))], [ sg.Checkbox('Delta Changes on debug window', default=ONSCREEN_DISPLAY, key='ONSCREEN_DISPLAY') ], [ sg.Checkbox('Delta Changes in text file', default=SAVE_TO_FILE, key='SAVE_TO_FILE', change_submits=True) ], [ sg.Checkbox('Club Delta output(s)', default=CLUB_OUTPUT_FOR_ALL_DEVICE, key='CLUB_OUTPUT_FOR_ALL_DEVICE') ], [ sg.Checkbox('MOP Excel Output', default=MOP_EXCEL_OUTPUT, key='MOP_EXCEL_OUTPUT', change_submits=True) ], [sg.Text('-' * 200, font=("TimesBold", 5))], [ sg.Checkbox('Use NAT IP for Source(s)', default=USE_SOURCE_NAT_IP, key='USE_SOURCE_NAT_IP') ], [ sg.Checkbox('Use NAT IP for Destinations(s)', default=USE_DESTINATION_NAT_IP, key='USE_DESTINATION_NAT_IP') ], [sg.Text('-' * 200, font=("TimesBold", 5))], [ sg.Text("ACL Base"), sg.InputCombo(['SOURCE', 'DESTINATION'], default_value='SOURCE', key='ACL_BASE') ], [ sg.Text("Minimum Logging Level: "), sg.InputCombo( ['debug', 'info', 'warning', 'error', 'critical'], default_value='info', key='LOG_LEVEL_MIN') ], #### ADD 2 [sg.Text('', font=("TimesBold", 5))], ]), ]] layout = [ [sg.Text("AT&T", font='arial', justification='center', size=(500, 1))], [sg.Text(header, font='arial', justification='center', size=(500, 1))], [ sg.Frame(title='Button Pallete', size=(600, 4), title_color='blue', relief=sg.RELIEF_RIDGE, layout=[ [ sg.OK('Go', size=(10, 1), bind_return_key=True), sg.Cancel('Cancel', size=(10, 1), bind_return_key=True), sg.Text(' ' * 80), sg.Button('Ninja', key='ninja', size=(10, 1), bind_return_key=True) ], ]), ], [ sg.TabGroup([[ sg.Tab(' Request ', tab1), sg.Tab(' Power ', tab2) ]]) ], [ sg.Text( "Note: Executing menu from any module except 'main' will result nothing...", font=('TimesBold', 12), text_color='red') ], ] w = sg.Window( header, layout, resizable=True, size=(768, 768), button_color=("black", "lightgray"), alpha_channel=.92, grab_anywhere=True, ) while True: event, (i) = w.Read(timeout=1000) NINJA = event == 'ninja' if event == 'Cancel': boot = False break if event == 'MOP_EXCEL_OUTPUT': w.Element('MOP_OUTPUT_FOLDER').Update( disabled=not i['MOP_EXCEL_OUTPUT']) w.Element('MOP_EXCEL_TEMPLATE').Update( disabled=not i['MOP_EXCEL_OUTPUT']) w.Element('MOP1').Update(disabled=not i['MOP_EXCEL_OUTPUT']) w.Element('MOP2').Update(disabled=not i['MOP_EXCEL_OUTPUT']) if event == 'SAVE_TO_FILE': w.Element('OUTPUT_FILE_EXTENSION').Update( disabled=not i['SAVE_TO_FILE']) w.Element('CLUB_OUTPUT_FOR_ALL_DEVICE').Update( disabled=not i['SAVE_TO_FILE']) if event in ('Go', 'ninja'): boot = True CAPTURE_FOLDER = i['CAPTURE_FOLDER'] LOG_EXTN = i['LOG_EXTN'] REQUEST_FILE = i['REQUEST_FILE'] LOG_FOLDER = i['LOG_FOLDER'] OUTPUT_FOLDER = i['OUTPUT_FOLDER'] OUTPUT_FILE_EXTENSION = i['OUTPUT_FILE_EXTENSION'] LOG_WARNING = i['LOG_WARNING'] LINENO_ON_DEL = i['LINENO_ON_DEL'] CLUB_OUTPUT_FOR_ALL_DEVICE = i['CLUB_OUTPUT_FOR_ALL_DEVICE'] MOP_EXCEL_TEMPLATE = i['MOP_EXCEL_TEMPLATE'] MOP_OUTPUT_FOLDER = i['MOP_OUTPUT_FOLDER'] MOP_EXCEL_OUTPUT = i['MOP_EXCEL_OUTPUT'] ONSCREEN_DISPLAY = i['ONSCREEN_DISPLAY'] SAVE_TO_FILE = i['SAVE_TO_FILE'] TASK_COMPLETE_NOTICE = i['TASK_COMPLETE_NOTICE'] USE_SOURCE_NAT_IP = i['USE_SOURCE_NAT_IP'] USE_DESTINATION_NAT_IP = i['USE_DESTINATION_NAT_IP'] ACL_BASE = i['ACL_BASE'] LOG_LEVEL_MIN = LOG_LEVELS[i['LOG_LEVEL_MIN']] #### ADD 3 if boot: w.Element('Go').Update(disabled=True) break w.Close() return boot
def main(): # ------ Variaveis ------ # opcao_visivel = False plot_ano = False plot_mes = False plot_media = False dados = {'fontes': [], 'meses': [], 'anos': []} def preencher_fontes(): if i == 1: dados['fontes'].append('Hidreletricas exclusive Itaipu') elif i == 2: dados['fontes'].append('Itaipu') elif i == 3: dados['fontes'].append('Oleo Diesel / Combustivel') elif i == 4: dados['fontes'].append('Gas Natural') elif i == 5: dados['fontes'].append('Carvao') elif i == 6: dados['fontes'].append('Eolicas') elif i == 7: dados['fontes'].append('Biomassas') elif i == 8: dados['fontes'].append('Nuclear') elif i == 9: dados['fontes'].append('Residuos Processos Industriais') elif i == 10: dados['fontes'].append('Energia produzida fora do SIN') def preencher_meses(): if i == 1: dados['meses'].append(1) elif i == 2: dados['meses'].append(2) elif i == 3: dados['meses'].append(3) elif i == 4: dados['meses'].append(4) elif i == 5: dados['meses'].append(5) elif i == 6: dados['meses'].append(6) elif i == 7: dados['meses'].append(7) elif i == 8: dados['meses'].append(8) elif i == 9: dados['meses'].append(9) elif i == 10: dados['meses'].append(10) elif i == 11: dados['meses'].append(11) elif i == 12: dados['meses'].append(12) def preencher_anos(): if i == 1: dados['anos'].append(2000) elif i == 2: dados['anos'].append(2001) elif i == 3: dados['anos'].append(2002) elif i == 4: dados['anos'].append(2003) elif i == 5: dados['anos'].append(2004) elif i == 6: dados['anos'].append(2005) elif i == 7: dados['anos'].append(2006) elif i == 8: dados['anos'].append(2007) elif i == 9: dados['anos'].append(2008) elif i == 10: dados['anos'].append(2009) elif i == 11: dados['anos'].append(2010) elif i == 12: dados['anos'].append(2011) elif i == 13: dados['anos'].append(2012) elif i == 14: dados['anos'].append(2013) elif i == 15: dados['anos'].append(2014) elif i == 16: dados['anos'].append(2015) elif i == 17: dados['anos'].append(2016) elif i == 18: dados['anos'].append(2017) elif i == 19: dados['anos'].append(2018) elif i == 20: dados['anos'].append(2019) elif i == 21: dados['anos'].append(2020) # ------ Definindo o Menu ------ # menu_def = [['&Arquivo', ['&Abrir', '&Salvar', '&Propriedades', 'S&air']], ['&Editar', ['&Colar', ['Especial', 'Normal', ], 'Desfazer'], ], ['&BarraExemplo', ['---', 'Command &1', 'Command &2', '---', 'Command &3', 'Command &4']], ['&Ajuda', '&Sobre...'], ] right_click_menu = ['Unused', ['Right', '!&Click', '&Menu', 'E&xit', 'Properties']] # ------ Modos de plotagem ------ # frame_plot = [ [sg.Button('Despache por ano específico', font='Any 12', size=(35, 3), key='plot_ano')], [sg.Button('Despache por mês específico', font='Any 12', size=(35, 3), key='plot_mes')], [sg.Button('Média de despache para todos os anos', font='Any 12', size=(35, 3), key='plot_media')] ] # ------ Configurações Dataframe ------ # frame_rna = [ [sg.Button('Configurar um dataframe', font='Any 12', size=(35, 3), key='_df_config_')], [sg.Button('Configurar RNA', font='Any 12', size=(35, 3), key='_rna_config_')], [sg.Button('Gerar previsão', font='Any 12', size=(35, 3), key='_gerar_prev_')] ] # ------ Layout Colunas ------ # layout_coluna_fontes = [ [sg.Checkbox(' Hidreletricas Exclusive Itaipu', key='_frame_fontes_1')], [sg.Checkbox(' Itaipu', key='_frame_fontes_2')], [sg.Checkbox(' Oleo Diesel / Combustivel', key='_frame_fontes_3')], [sg.Checkbox(' Gas Natural', key='_frame_fontes_4')], [sg.Checkbox(' Carvao', key='_frame_fontes_5')], [sg.Checkbox(' Eolicas', key='_frame_fontes_6')], [sg.Checkbox(' Biomassas', key='_frame_fontes_7')], [sg.Checkbox(' Nuclear', key='_frame_fontes_8')], [sg.Checkbox(' Residuos Processos Industriais', key='_frame_fontes_9')], [sg.Checkbox(' Energia produzida fora do SIN', key='_frame_fontes_10')] ] layout_coluna_meses = [ [sg.Checkbox(' 1 - Janeiro ', disabled=True, key='_frame_meses_1'), sg.Checkbox(' 11 - Novembro', disabled=True, key='_frame_meses_11')], [sg.Checkbox(' 2 - Fevereiro', disabled=True, key='_frame_meses_2'), sg.Checkbox(' 12 - Dezembro', disabled=True, key='_frame_meses_12')], [sg.Checkbox(' 3 - Março', disabled=True, key='_frame_meses_3')], [sg.Checkbox(' 4 - Abril', disabled=True, key='_frame_meses_4')], [sg.Checkbox(' 5 - Maio', disabled=True, key='_frame_meses_5')], [sg.Checkbox(' 6 - Junho', disabled=True, key='_frame_meses_6')], [sg.Checkbox(' 7 - Julho', disabled=True, key='_frame_meses_7')], [sg.Checkbox(' 8 - Agosto', disabled=True, key='_frame_meses_8')], [sg.Checkbox(' 9 - Setembro', disabled=True, key='_frame_meses_9')], [sg.Checkbox(' 10 - Outubro', disabled=True, key='_frame_meses_10')] ] layout_coluna_anos = [ [sg.Checkbox(' 2000', disabled=True, key='_frame_anos_1'), sg.Checkbox(' 2010', disabled=True, key='_frame_anos_11'), sg.Checkbox(' 2020', disabled=True, key='_frame_anos_21')], [sg.Checkbox(' 2001', disabled=True, key='_frame_anos_2'), sg.Checkbox(' 2011', disabled=True, key='_frame_anos_12')], [sg.Checkbox(' 2002', disabled=True, key='_frame_anos_3'), sg.Checkbox(' 2012', disabled=True, key='_frame_anos_13')], [sg.Checkbox(' 2003', disabled=True, key='_frame_anos_4'), sg.Checkbox(' 2013', disabled=True, key='_frame_anos_14')], [sg.Checkbox(' 2004', disabled=True, key='_frame_anos_5'), sg.Checkbox(' 2014', disabled=True, key='_frame_anos_15')], [sg.Checkbox(' 2005', disabled=True, key='_frame_anos_6'), sg.Checkbox(' 2015', disabled=True, key='_frame_anos_16')], [sg.Checkbox(' 2006', disabled=True, key='_frame_anos_7'), sg.Checkbox(' 2016', disabled=True, key='_frame_anos_17')], [sg.Checkbox(' 2007', disabled=True, key='_frame_anos_8'), sg.Checkbox(' 2017', disabled=True, key='_frame_anos_18')], [sg.Checkbox(' 2008', disabled=True, key='_frame_anos_9'), sg.Checkbox(' 2018', disabled=True, key='_frame_anos_19')], [sg.Checkbox(' 2009', disabled=True, key='_frame_anos_10'), sg.Checkbox(' 2019', disabled=True, key='_frame_anos_20')], ] # ------ Configurando a plotagem ------ # frame_opcoes = [ [sg.Frame('Fontes', layout_coluna_fontes), sg.Frame('Meses', layout_coluna_meses), sg.Frame('Anos', layout_coluna_anos)] ] # ------ PLOT CANVAS ------ # frame_grafico = [ [] ] # ---------- LAYOUT ------------ # layout = [ [sg.Menu(menu_def)], [sg.Frame('RNA', frame_rna, font='Any 20', title_color='black', border_width=5, visible=True, key='_rna_'), sg.Frame('PLOT', frame_plot, font='Any 20', title_color='black', border_width=5, visible=True, key='_plot_'), sg.Frame('OPCOES', frame_opcoes, font='Any 20', title_color='black', border_width=5, visible=False, key='_opcoes_'), sg.Frame('GRAFICO', frame_grafico, font='Any 20', title_color='black', border_width=5, visible=False, key='_grafico_')], [sg.Button('Gerar', font='Any 12', size=(30, 1), visible=False, key='_gerar_'), sg.Button('Plotar', font='Any 12', size=(30, 1), visible=False, key='_plotar_'), sg.Button('Sair', font='Any 12', size=(30, 1), key='sair')], ] # ---------- JANELA ------------ # window = sg.Window('Menu', layout, element_justification='c', default_element_size=(12, 1), right_click_menu=right_click_menu, default_button_element_size=(12, 1)) while True: # ------ Condições de saída ------ # event, values = window.Read() if event in (sg.WIN_CLOSED, 'sair'): break # ------ Escolhas do menu ------ # if event == 'About...': window.disappear() sg.popup('About this program', 'Version 1.0', 'PySimpleGUI rocks...') window.reappear() elif event == 'Open': filename = sg.popup_get_file('file to open', no_window=True) print(filename) elif event == 'Properties': pass elif event == '-BMENU-': print('You selected from the button menu:', values['-BMENU-']) # ================ Menus de plotagem ================ # # 1 - PLOT POR ANO if event == 'plot_ano' and opcao_visivel is False: window.FindElement('_plot_').Update(visible=False) window.FindElement('_rna_').Update(visible=False) for i in range(1, 22): window.FindElement(f'_frame_anos_{str(i)}').Update(disabled=False) window.FindElement('_opcoes_').Update(visible=True) window.FindElement('_plotar_').Update(visible=True) plot_ano = True opcao_visivel = True # 2 - PLOT POR MES if event == 'plot_mes' and opcao_visivel is False: window.FindElement('_plot_').Update(visible=False) window.FindElement('_rna_').Update(visible=False) for i in range(1, 13): window.FindElement(f'_frame_meses_{str(i)}').Update(disabled=False) window.FindElement('_opcoes_').Update(visible=True) window.FindElement('_plotar_').Update(visible=True) plot_mes = True opcao_visivel = True # 3 - PLOT MEDIA if event == 'plot_media' and opcao_visivel is False: window.FindElement('_plot_').Update(visible=False) window.FindElement('_rna_').Update(visible=False) window.FindElement('_opcoes_').Update(visible=True) window.FindElement('_plotar_').Update(visible=True) plot_media = True opcao_visivel = True # ================ Menus RNA ================ # # 1 - Configurar dataframe if event == '_df_config_' and opcao_visivel is False: window.FindElement('_plot_').Update(visible=False) window.FindElement('_rna_').Update(visible=False) for i in range(1, 22): window.FindElement(f'_frame_anos_{str(i)}').Update(disabled=False) for i in range(1, 13): window.FindElement(f'_frame_meses_{str(i)}').Update(disabled=False) window.FindElement('_opcoes_').Update(visible=True) window.FindElement('_gerar_').Update(visible=True) opcao_visivel = True # ------ Menu de opções ------ # if event == '_gerar_': for i in range(1, 11): if values[f'_frame_fontes_{str(i)}']: preencher_fontes() for i in range(1, 13): if values[f'_frame_meses_{str(i)}']: preencher_meses() for i in range(1, 22): if values[f'_frame_anos_{str(i)}']: preencher_anos() df = GenDataFrame(dados['fontes'], dados['meses'], dados['anos']).gerar() print(df) dados['fontes'].clear() dados['meses'].clear() dados['anos'].clear() window.close() sg.popup('Dataframe gerado com sucesso!', title='DATAFRAME', custom_text=' VOLTAR AO MENU ') main() if event == '_plotar_': for i in range(1, 11): if values[f'_frame_fontes_{str(i)}']: preencher_fontes() for i in range(1, 13): if values[f'_frame_meses_{str(i)}']: preencher_meses() for i in range(1, 22): if values[f'_frame_anos_{str(i)}']: preencher_anos() if plot_ano: for ano in dados['anos']: plot_ano_especifico(dados['fontes'], ano) dados['fontes'].clear() dados['anos'].clear() if plot_mes: for mes in dados['meses']: plot_mes_especifico(dados['fontes'], mes) dados['fontes'].clear() dados['meses'].clear() if plot_media: plot_media_anos(dados['fontes']) dados['fontes'].clear() window.Close()
palabras = [] theme = 'SystemDefault' layout1 = [ [sg.InputText(default_text="", key='ingreso')], [ sg.Listbox([], size=(30, 6), key='lista'), sg.Column([[sg.Button('Agregar')], [sg.Button('Eliminar')]]) ], [ sg.Frame('Sustantivos', [[ sg.Column([[ sg.Spin([ i for i in range( len([j for j in dic if j.getClase == 'sustantivo'])) ], initial_value=0, size=(15, 1), key='cantSus') ], [sg.ColorChooserButton('colorSus')]]) ]]), sg.Frame('Adjetivos', [[ sg.Column([[ sg.Spin([ i for i in range( len([j for j in dic if j.getClase == 'adjetivo'])) ], initial_value=0, size=(15, 1), key='cantAdj') ], [sg.ColorChooserButton('colorAdj')]])
video_column = [ [sg.Image(filename='', key='image')], ] result_column = [[ sg.Text("Face Mask Detection", size=(10, 3), font='Helvetica 28 bold', justification='center'), ], [ sg.Frame(layout=[[ sg.Text(key='withMask', font='Helvetica 20', text_color='Green', justification='right', size=(13, 1)) ]], title='Total with mask') ], [ sg.Frame(layout=[[ sg.Text(key='withoutMask', font='Helvetica 20', text_color='Red', justification='right', size=(13, 1)) ]], title='Total without mask') ]]
sg.Cancel()]] layout_two = [[sg.Input(key="input_file"), sg.FileBrowse()], [sg.Input(key="output_folder"), sg.FolderBrowse()], [sg.Input(key="output_name")], [sg.Text(font=("roboto", 1))], [sg.Text(font=("roboto", 13))]] layout_three = [[ sg.Text("Mapping", font=("roboto", 13)), sg.Input(default_text="DLG_Mapping.csv", key="mapping_csv"), sg.FileBrowse() ]] layout = [[sg.Column(layout_one), sg.Column(layout_two)], [sg.Frame("Optional", layout_three, font=("roboto", 15))], [sg.Output(size=(90, 10))]] window = sg.Window("DLG API Parser: Make a CSV from DLG Metadata", layout) # Keeps the GUI open until the user quits the program. Receives user input, verifies the input, # and when all input is correct runs the program. # Future development: add a "reset" button to get the GUI back to original values? while True: # For threading: start garbage collecting. gc.collect() # Gets the user input data and saves the input values to their own variables for easier referencing in the script. event, values = window.read()
sg.Frame(layout=[ [ sg.Text( 'Model type', text_color='#e4e4e4', background_color='#343434', tooltip= 'Choice of rules to apply to the network structure'), sg.Combo(model_type_list) ], [ sg.Text('Boundary conditions', text_color='#e4e4e4', background_color='#343434', tooltip= 'Choice of behavior for nodes without regulators'), sg.Combo(boundary_model_list) ], [ sg.Text( 'Genes initial states', text_color='#e4e4e4', background_color='#343434', tooltip= 'In <<specified>> mode, use the gene list panel to highlight the genes to be set to 1 at start,\n all other genes will be set to 0 (0 or 1 in <<random-specified>> mode)' ), sg.Combo(initial_states_choice_list) ], [ sg.Text( 'Number of initial states :', text_color='#e4e4e4', background_color='#343434', tooltip= 'Choice of how many initial states the model will run from' ), sg.Radio('All possible states', 'RADIO2', background_color='#343434', text_color='#e4e4e4'), sg.Radio('Given number of states', 'RADIO2', background_color='#343434', text_color='#e4e4e4', default=True), sg.InputText(size=(10, 1), default_text='1') ], [ sg.Text( 'KO mutation type', text_color='#e4e4e4', background_color='#343434', tooltip= 'Choice of Knocked Out mutation to apply to the network \n- single KO will run the model mutating each chosen genes one at a time' '\n- multiple KO will run the model once with all chosen genes as KO' '\n- combination KO will go through all combinations of double KO for the chosen genes and run the model for each' ), sg.Combo(KO_mutation_type_list) ], [ sg.Text( 'List of KO genes', text_color='#e4e4e4', background_color='#343434', tooltip= 'Enter gene names separated by a colon e.g. ABC, LMN, XYZ' ), sg.InputText() ], [ sg.Text( 'OA mutation type', text_color='#e4e4e4', background_color='#343434', tooltip= 'Choice of Over Activated mutation to apply to the network \n- single OA will run the model mutating each chosen genes one at a time' '\n- multiple OA will run the model once with all chosen genes as KO' '\n- combination OA will go through all combinations of double KO for the chosen genes and run the model for each' ), sg.Combo(OA_mutation_type_list) ], [ sg.Text( 'List of OA genes', text_color='#e4e4e4', background_color='#343434', tooltip= 'Enter gene names separated by a colon e.g. ABC, LMN, XYZ' ), sg.InputText() ], [sg.Button('Run PYTHONIS')] ], title='Predict System Fates', title_color='#e4e4e4', background_color='#343434', relief=sg.RELIEF_GROOVE)
def layoutStart(): layout_start = [[ sg.Frame( layout=[[ sg.Text('Gene List File', background_color='#343434', text_color='#e4e4e4') ], [sg.Input(), sg.FileBrowse()], [ sg.Text('Network Structure File', background_color='#343434', text_color='#e4e4e4') ], [sg.Input(), sg.FileBrowse()]], title='Import network', title_color='#e4e4e4', relief=sg.RELIEF_SUNKEN, background_color='#343434', tooltip= 'Choose gene list file and network structure file to import a predefined network model' ) ], [ sg.Frame( layout=[[ sg.Text('Number of nodes', background_color='#343434', text_color='#e4e4e4') ], [sg.Input()], [ sg.Text('Number of interactions', background_color='#343434', text_color='#e4e4e4') ], [sg.Input()]], title= 'Gene network Automated Initiation Algorithm (GAIA)', title_color='#e4e4e4', relief=sg.RELIEF_SUNKEN, background_color='#343434', tooltip='Create a random network to work with') ], [ sg.Frame( layout=[[ sg.Radio('Batch Computation Mode', 'RADIO1', default=True, size=(18, 1), background_color='#343434', text_color='#e4e4e4'), sg.Radio('Visual Network Mode', 'RADIO1', background_color='#343434', text_color='#e4e4e4') ]], title='Run mode', title_color='#e4e4e4', relief=sg.RELIEF_SUNKEN, background_color='#343434', tooltip= 'Batch computation for whole network simulation and genes significance study / Interactive network to quick test hypothesis manually and visually' ) ], [sg.CloseButton('Import'), sg.CloseButton('Cancel')]] window_start = sg.Window("Initialize Network", alpha_channel=0.95, layout=layout_start) return window_start
def MainGui(): con, cur = IntroDB() layout1 = [[sg.Menu(menu_def, tearoff=True)], [sg.Column([ [sg.Frame("Perfil de impresora",layout=[ [sg.Combo(values=[element[0] for element in GetThings(cur)], readonly=True, key="-CHOSPRINTER1-",size = (33,1), change_submits=True),sg.Button("Editar",key ="-EDITPRINTER1-")]])]],vertical_alignment='center', justification='center')], [sg.Column([[Collapse([[sg.Text("Selecciona perfil de impresora válido", auto_size_text=True,text_color="red",justification="center")]],"-CHECKPRINTER1-", False)]], vertical_alignment="center",justification="center")], [sg.Column([[sg.Frame(title="",layout=[[sg.Text('· Tiempo de impresión', size=commonParams[0]), sg.Text("(Horas:Minutos)", size=commonParams[0]), sg.Input(key='-INaccess11-', size=commonParams[1], enable_events=True)], [sg.Text('· Material Consumido', size=commonParams[0]), sg.Text("(Gramos)", size=commonParams[0]), sg.Input(key='-INaccess21-', size=commonParams[1], enable_events=True)], [sg.Text('· Coste de laminado', size=commonParams[0]), sg.Text("(Euros)", size=commonParams[0]), sg.Input(key='-INaccess31-', size=commonParams[1], enable_events=True)]])]], vertical_alignment='center', justification='center')], [sg.Column([[Collapse([[sg.Text("Dato mal introducido",key="-CHECKINPUTS1-",size=commonParams[3],text_color="red",justification="center")]],"-COLUMNINPUTS1-", False)]], vertical_alignment="center",justification="center")], [sg.Checkbox('Activar Opciones de Venta', enable_events=True, key='-CHbox1-', font=commonParams[2])], [sg.Column([[Collapse( [[sg.Text("· Margen de Venta (%)", size=commonParams[0]), sg.Input(key='-INaccess41-', size=commonParams[1], enable_events=True)], [sg.Text("· Porcentaje de IVA (%)", size=commonParams[0]), sg.Input(key='-INaccess51-', disabled=True, size=commonParams[1], enable_events=True), sg.Help("Ayuda", tooltip="Margen de ventas debe ser 0 o superior", key="-Help1-", pad=((5, 0), (0, 0)), button_color=("blue"))]], '-Token1-', False)]], vertical_alignment='center', justification='center')], [sg.HorizontalSeparator(pad=((0, 0), (0, 0)))], [sg.Text("")], [sg.Column([[sg.Button("Calcular", font=commonParams[2], key="-INsubmit1-", auto_size_button=True, pad=((0, 0),(0,0))), sg.Button("Reiniciar", key="-Reset1-", font=commonParams[2], pad=((20, 0), (0, 0)))]], justification ="center")], ] layout2 = [[sg.Menu(menu_def, tearoff=True)], [sg.Column([ [sg.Frame("Perfil de impresora",layout=[ [sg.Combo(values=[element[0] for element in GetThings(cur)], readonly=True, key="-CHOSPRINTER2-",size = (33,1), change_submits=True),sg.Button("Editar",key ="-EDITPRINTER2-")]])]],vertical_alignment='center', justification='center')], [sg.Column([[Collapse([[sg.Text("Selecciona perfil de impresora válido", auto_size_text=True,text_color="red",justification="center")]],"-CHECKPRINTER2-", False)]], vertical_alignment="center",justification="center")], [sg.Column([[sg.Frame(title="",layout=[[sg.Text('· Tiempo de impresión', size=commonParams[0]), sg.Text("(Horas:Minutos)", size=commonParams[0]), sg.Input(key='-INaccess12-', size=commonParams[1], enable_events=True)], [sg.Text('· Material Consumido', size=commonParams[0]), sg.Text("(Gramos)", size=commonParams[0]), sg.Input(key='-INaccess22-', size=commonParams[1], enable_events=True)], [sg.Text('· Coste de laminado', size=commonParams[0]), sg.Text("(Euros)", size=commonParams[0]), sg.Input(key='-INaccess32-', size=commonParams[1], enable_events=True)]])]], vertical_alignment='center', justification='center')], [sg.Column([[Collapse([[sg.Text("Dato mal introducido",size=commonParams[3],key="-CHECKINPUTS2-",text_color="red",justification="center")]],"-COLUMNINPUTS2-", False)]], vertical_alignment="center",justification="center")], [sg.Checkbox('Activar Opciones de Venta', enable_events=True, key='-CHbox2-', font=commonParams[2])], [sg.Column([[Collapse( [[sg.Text("· Margen de Venta (%)", size=commonParams[0]), sg.Input(key='-INaccess42-', size=commonParams[1], enable_events=True)], [sg.Text("· Porcentaje de IVA (%)", size=commonParams[0]), sg.Input(key='-INaccess52-', size=commonParams[1], enable_events=True), sg.Help("Ayuda", tooltip="Margen de ventas debe ser 0 o superior", key="-Help2-", pad=((5, 0), (0, 0)), button_color=("blue"))]], '-Token2-', False)]], vertical_alignment='center', justification='center')], [sg.Text("")], [sg.HorizontalSeparator()], [sg.Column([ [sg.Column([[sg.Text("Coste Total", size=commonParams[4],justification="center",font=commonParams[2])]], justification="center")], [sg.Column([[sg.Text("0 €",text_color="orange", key="-Text1-", size=commonParams[4], font=commonParams[5], justification="center")]], justification="center")], [sg.HorizontalSeparator(pad=((0,0), (5,5)))], [sg.Column([[sg.Text("Precio Venta", size=commonParams[4],justification="center",font=commonParams[2])]], justification="center")], [sg.Column([[sg.Text("0 €",text_color="orange", key="-Text2-", size=commonParams[4], font=commonParams[5], justification="center")]], justification="center")]],justification="center"), sg.VerticalSeparator(pad=((0,20),(0,0))), sg.Column([[sg.Multiline(reroute_stderr=False,autoscroll=True,size=(22,9),key="-OUTPUTPRINT-",reroute_stdout=True, disabled=True)]], justification="center", vertical_alignment="center")], [sg.HorizontalSeparator(pad=((0,0), (0,0)))], [sg.Text("")], [sg.Column([[sg.Button("Calcular", font=commonParams[2], key="-INsubmit2-", auto_size_button=True, pad=((0, 0),(0,0))), sg.Button("Reiniciar", key="-Reset2-", font=commonParams[2], pad=((20, 0), (0, 0)))]], justification ="center")], ] layoutMain = [[sg.Column(layout1, key='-COL1-'), sg.Column(layout2, visible=False, key='-COL2-')]] window = sg.Window('Estimador de costes', layoutMain, icon='input/LogoIcon.ico') layout = 1 opened = False checkSaved = False while True: event, values = window.read() if event == f'-CHbox{layout}-': opened = not opened window[f'-CHbox{layout}-'].update(opened) window[f'-Token{layout}-'].update(visible=opened) if event == f"-Help{layout}-": sg.popup("Margen de ventas debe ser 0 o superior para poder introducir el porcentaje de IVA", title="Ayuda IVA", grab_anywhere=False) if event == f"-Reset{layout}-": Reset(window, layout) try: if values[f"-INaccess4{layout}-"] == "": window[f"-INaccess5{layout}-"].update("", disabled=True) else: window[f"-INaccess5{layout}-"].update(disabled=False) except TypeError: break #Al clickar el botón para calcular costes if event == f"-INsubmit{layout}-": ''' Evalúa si hay un perfil de impresora seleccionado ''' chosPrinter = "" if values[f"-CHOSPRINTER{layout}-"] == "": window[f"-CHECKPRINTER{layout}-"].update(visible=True) chosPrinter = False else: window[f"-CHECKPRINTER{layout}-"].update(visible=False) ''' Evalúa si los input introducidos son válidos ''' badInputs = [] checkTime = TimeValidation(values[f"-INaccess1{layout}-"]) if checkTime==False: badInputs.append("Tiempo") if MainValidation(values[f"-INaccess2{layout}-"])==False: badInputs.append("Material") if MainValidation(values[f"-INaccess3{layout}-"])==False and values[f"-INaccess3{layout}-"]!="0": badInputs.append("Laminado") if badInputs == []: window[f"-COLUMNINPUTS{layout}-"].update(visible=False) else: window[f"-CHECKINPUTS{layout}-"].update(value=", ".join(badInputs)+": mala introducción") window[f"-COLUMNINPUTS{layout}-"].update(visible=True) if chosPrinter != "" or badInputs != []: continue ''' Envía la información formateada a las funciones de cálculo de costes ''' marginSales = ManageSales(MainValidation(values[f"-INaccess4{layout}-"])) ivaTax = ManageSales(MainValidation(values[f"-INaccess5{layout}-"])) electricityCost = KwCost(RefactorSupport(cur, values[f"-CHOSPRINTER{layout}-"],"KWprinter"), RefactorSupport(cur, values[f"-CHOSPRINTER{layout}-"],"KWprize"), checkTime) materialCost = FilamentCost(RefactorSupport(cur,values[f"-CHOSPRINTER{layout}-"],"SpoolCost"), RefactorSupport(cur,values[f"-CHOSPRINTER{layout}-"],"SpoolWeight"), MainValidation(values[f"-INaccess2{layout}-"])) amortCost = AmortCost(RefactorSupport(cur,values[f"-CHOSPRINTER{layout}-"],"PrinterCost"), RefactorSupport(cur,values[f"-CHOSPRINTER{layout}-"],"AmortPrinter"), checkTime) designCost = MainValidation(values[f"-INaccess3{layout}-"]) print(f"--------------\nCoste Electricidad: {electricityCost}\nCoste Material: {materialCost}\nCoste Laminado: {designCost}\nCoste Amortización: {amortCost}\n") ''' Gestiona la información recibida de las funciones de costes y las muestra ''' totalCost = round(electricityCost+materialCost+amortCost+designCost,2) salesCost = round((totalCost*marginSales)*ivaTax,2) marginCostPrint = abs(round(totalCost*(marginSales-1),2)) ivaCostPrint = abs(round(salesCost-totalCost-totalCost*(marginSales-1),2)) print(f"Margen de venta: {marginCostPrint}\nCoste IVA: {ivaCostPrint}\n--------------") window["-Text1-"].update(f"{totalCost} €") window["-Text2-"].update(f"{salesCost} €") ''' Guarda la información introducida entre cambio de layouts ''' if checkSaved == False: window[f'-COL{layout}-'].update(visible=False) # layout = 1 if layout == 2 else 2 layout = 2 if opened != False: window[f'-CHbox{layout}-'].update(value=True) window[f'-Token{layout}-'].update(visible=opened) window[f"-CHOSPRINTER{2 if layout == 2 else 1}-"].update( values[f"-CHOSPRINTER{1 if layout == 2 else 2}-"]) for element in range(1, 6): window[f"-INaccess{element}{2 if layout == 2 else 1}-"].update( values[f"-INaccess{element}{1 if layout == 2 else 2}-"]) window[f'-COL{layout}-'].update(visible=True) checkSaved = True ''' Redirige al apartado de gestión de perfiles de impresora ''' if event == "Opciones" or event == f"-EDITPRINTER{layout}-": PopupOptions(con, cur) window.Element(f"-CHOSPRINTER{2 if layout == 2 else 1}-").update(values=[element[0] for element in GetThings(cur)]) ''' Cierra la ventana ''' if event == sg.WIN_CLOSED or event =="Salir": break window.close()
def get_config_actual(guardado, pred): """ Retorna en forma de string las configuaciones del juego actual """ try: if not (guardado): if (pred): datos = open( os.path.join(absolute_path, "lib", "info", "config", "configPred.json"), "r") else: datos = open( os.path.join(absolute_path, "lib", "info", "config", "configUsuario.json"), "r") else: datos = open(os.path.join(absolute_path, "lib", "info", "saves", "datos_guardados.json"), "r", encoding='utf8') data = json.load(datos) table_data = [ ['A,E,O,S,I,U,N,L,R,T', data["grupo_1_cant"], data["grupo_1"]], ['C,D,G', data["grupo_2_cant"], data["grupo_2"]], ['M,B,P', data["grupo_3_cant"], data["grupo_3"]], ['F,H,V,Y', data["grupo_4_cant"], data["grupo_4"]], ['J', data["grupo_5_cant"], data["grupo_5"]], ['K,LL,Ñ,Q,RR,W,X', data["grupo_6_cant"], data["grupo_6"]], ['Z', data["grupo_7_cant"], data["grupo_7"]] ] headings = [' LETRAS ', ' CANTIDAD ', ' PUNTOS '] frame = [[ sg.T("Dificultad: " + data["dificultad"].capitalize()), sg.T("Tiempo: " + data["tiempo"] + " minutos") ]] layout = [[sg.Frame("", layout=frame)], [ sg.Table(values=table_data, headings=headings, max_col_width=400, auto_size_columns=True, text_color='black', font='Courier 14', justification='center', num_rows=7, alternating_row_color='#8fa8bf', key='table', def_col_width=35, header_text_color='white', header_background_color='#8fa8bf') ], [sg.B("OK", key="ok", pad=(170, None))]] window = sg.Window('Configuraciones del juego', layout, grab_anywhere=False) while True: event, values = window.Read() if event is None or event == "ok": break window.close() except (FileNotFoundError): sg.Popup("No se encontro arch de configuraciones")
def Config(): ''' Esta función abre la ventana general de configuración y en cada pestaña permite configurar cada característica de la sopa de letras. Al presionar "Aplicar", se guardan los cambios. Si una o más características no fueron configuradas por el usuario, adoptarán los valores por defecto dados por esta misma función. Retorna un diccionario con todas las selecciones.''' #Lista de fuentes disponibles para el programa: lista_fuentes = [ "Arial", "Helvetica", "Times New Roman", "Courier", "Verdana", "Georgia", "Garamond", "Bookman", "Comic Sans MS", "Trebuchet MS", "Arial Black", "Impact" ] lista_oficinas = [ "Oficina 1", "Oficina 2", "Oficina 3" ] #Luego se recibirán como parámetro desde el archivo json #Layout de la Tab para configurar los colores: colores_layout = layout = [[ sg.Text( 'Seleccione un color para cada tipo de palabra. Al finalizar presione "OK".' ) ], [ sg.Text('Color para sustantivos', key='color_S'), sg.Button('.', button_color=('black', 'cadet blue')) ], [ sg.Text('Color para adjetivos', key='color_A'), sg.Button('..', button_color=('black', 'cadet blue')) ], [ sg.Text('Color para verbos', key='color_V'), sg.Button('...', button_color=('black', 'cadet blue')) ]] #Layout del Frame para configurar la fuente: tipografia_fuente_layout = [[ sg.Text('Seleccione una fuente para las letras:') ], [sg.Combo(lista_fuentes, default_value='Helvetica', key='fuente')]] #Layout del Frame para configurar si las letras se mostrarán en mayúscula o minúscula: tipografia_mayus_minus_layout = [[ sg.Text('Seleccione cómo se mostrarán las letras:') ], [ sg.Radio('Mayúscula', "RADIO1", default=True, key='mayus'), sg.Radio('Minúscula', "RADIO1", key='minus') ]] #Layout de la Tab para configurar la tipografía: tipografia_layout = [[ sg.Frame('Fuente', tipografia_fuente_layout, font='Any 8', title_color='cadet blue') ], [ sg.Frame('Caps', tipografia_mayus_minus_layout, font='Any 8', title_color='cadet blue') ]] #Layout de la Tab para configurar el tipo de ayuda a utilizar: ayuda_layout = [[ sg.Radio('Sin ayuda', "RADIO2", size=(10, 1), key='sin_ayuda', default=True), sg.Radio('Mostrar definiciones', "RADIO2", key='con_definiciones'), sg.Radio('Mostrar palabras', "RADIO2", key='con_palabras'), sg.Radio('Mostrar definiciones y palabras', "RADIO2", key='con_ayuda') ]] #Layout del Frame para configurar las palabras a hallar: contenido_palabras_layout = [ [ sg.Input(default_text='Ingrese una palabra', key='in'), sg.Submit('Ingresar') ], [sg.Listbox(values=[], size=(30, 6), key='palabra_seleccionada')], [ sg.Button( 'Eliminar', tooltip= 'Seleccione una palabra y oprima el botón para eliminarla') ] ] #Layout del Frame para configurar la cantidad de palabras a hallar: contenido_cantidad_palabras_layout = [[ sg.Spin([i for i in range(0, 6)], initial_value=1, key='cant_S'), sg.Text('Sustantivos') ], [ sg.Spin([i for i in range(0, 6)], initial_value=1, key='cant_A'), sg.Text('Adjetivos') ], [ sg.Spin([i for i in range(0, 6)], initial_value=1, key='cant_V'), sg.Text('Verbos') ]] #Layout del Frame para configurar la orientación de las palabras a hallar: contenido_orientacion_layout = [[ sg.Text('Seleccione cómo se mostrarán las letras:') ], [ sg.Radio('Horizontal', "RADIO3", default=True, key='horizontal'), sg.Radio('Vertical', "RADIO3", key='vertical') ]] #Layout de la Tab para configurar el contenido de la sopa de letras: contenido_layout = [[ sg.Frame('Palabras', contenido_palabras_layout, font='Any 8', title_color='cadet blue') ], [ sg.Frame('Cantidad', contenido_cantidad_palabras_layout, font='Any 8', title_color='cadet blue') ], [ sg.Frame('Orientación', contenido_orientacion_layout, font='Any 8', title_color='cadet blue') ]] #Layout del Frame para seleccionar la oficina de la cual se utilizarán los datos para configurar el #estilo "Look and Feel" seleccion_oficinas_layout = [[ sg.Combo(lista_oficinas, default_value='Helvetica', key='oficina') ]] #Layout de la Tab que contendrá la herramienta de selección de oficinas" oficinas_layout = [[ sg.Frame('Oficinas', seleccion_oficinas_layout, font='Any 8', title_color='cadet blue') ]] #Layout de la ventana de configuración: layout = [ [ sg.TabGroup([[ sg.Tab('Colores', colores_layout), sg.Tab('Tipografía', tipografia_layout), sg.Tab('Ayuda', ayuda_layout), sg.Tab('Contenido', contenido_layout), sg.Tab('Oficinas', oficinas_layout) ]]) ], [ sg.Submit( 'Aplicar', tooltip= 'Al presionar este botón todos los cambios serán guardados') ] ] window = sg.Window('Configuración', layout, default_element_size=(24, 1)).Finalize() #Establezco valores por defecto en caso de que el usuario no establezca sus propios valores: colours = { 'Sustantivo': 'spring green', 'Adjetivo': 'sky blue', 'Verbo': 'coral' } tipografia = {'font': 'Helvetica', 'caps': 'mayuscula'} cant_palabras = {'cant_Sust': '0', 'cant_Adjt': '0', 'cant_Verb': '0'} lista_palabras = [] lista_sustantivos = [] lista_sustantivos_final = [] lista_adjetivos = [] lista_adjetivos_final = [] lista_verbos = [] lista_verbos_final = [] lista_palabras_final = [] lista_palabras_eliminar = [] diccionario_palabras = {} nro_reporte = 0 ayuda = { 'sin_ayuda': True, 'definiciones': False, 'palabras': False, 'con_ayuda': False } datos_configurados = { 'colores': colours, 'tipografia': tipografia, 'cant_palabras': cant_palabras, 'palabras': lista_palabras, 'diccionario': diccionario_palabras, 'orientacion': 'horizontal' } while True: event, values = window.Read() print(event, values) if event is None: break #Los colores se pueden elegir múltiples veces, el último seleccionado es el que se guarda: if event is '.': colours['Sustantivo'] = fc.ColorChooser() colores_layout[1][1].Update(button_color=('black', colours['Sustantivo'])) if event is '..': colours['Adjetivo'] = fc.ColorChooser() colores_layout[2][1].Update(button_color=('black', colours['Adjetivo'])) if event is '...': colours['Verbo'] = fc.ColorChooser() colores_layout[3][1].Update(button_color=('black', colours['Verbo'])) #Al ingresar una palabra se verifica que no haya sido ingresada previamente: if event is 'Ingresar': if values['in'] not in lista_palabras: validada = wp.validacion(values['in'], diccionario_palabras)['validez'] #Una vez validada, se agrega a la lista de palabras: if validada: lista_palabras.append(values['in']) contenido_palabras_layout[1][0].Update( values=lista_palabras) else: sg.Popup('La palabra no puede ingresarse.') palabra_pattern = wp.de_pattern(values["in"]) try: de_wik_actual = diccionario_palabras[values[ "in"]] #hago este auxiliar para evitar un posible key error tipo = de_wik_actual["Tipo"] comparado = wp.comparando(palabra_pattern[1], tipo) except KeyError: tipo = "" comparado = wp.comparando(palabra_pattern[1], tipo) if (comparado == "No Coinciden"): wp.no_coinciden(values["in"], tipo, palabra_pattern[1], nro_reporte) nro_reporte = nro_reporte + 1 elif comparado == "No se encontro la palabra": wp.no_existen(values["in"], nro_reporte) nro_reporte = nro_reporte + 1 #Si se oprime 'Eliminar' se elimina la palabra seleccionada: if event is 'Eliminar' and values['palabra_seleccionada'][ 0] in lista_palabras: lista_palabras.remove(values['palabra_seleccionada'][0]) contenido_palabras_layout[1][0].Update(values=lista_palabras) #Si se oprime 'Aplicar', se efectuarán los cambios: if event is 'Aplicar': #Guardo la cantidad de palabras correspondiente: for palabra in lista_palabras: if diccionario_palabras[palabra]['Tipo'] == 'Sustantivo': lista_sustantivos.append(palabra) elif diccionario_palabras[palabra]['Tipo'] == 'Adjetivo': lista_adjetivos.append(palabra) else: lista_verbos.append(palabra) lista_sustantivos_final = LimitePalabras(lista_sustantivos, values['cant_S']) lista_adjetivos_final = LimitePalabras(lista_adjetivos, values['cant_A']) lista_verbos_final = LimitePalabras(lista_verbos, values['cant_V']) lista_palabras_final = lista_sustantivos_final + lista_adjetivos_final + lista_verbos_final for palabra in lista_palabras_final: if palabra not in lista_palabras: lista_palabras_eliminar.append(palabra) #Guardo la configuración de tipografía en el diccionario: tipografia['font'] = values['fuente'] if values['minus']: tipografia['caps'] = 'minuscula' else: tipografia['caps'] = 'mayuscula' #Guardo la configuración de cantidad de palabras en el diccionario: cant_palabras['cant_Sust'] = len(lista_sustantivos_final) cant_palabras['cant_Adjt'] = len(lista_adjetivos_final) cant_palabras['cant_Verb'] = len(lista_verbos_final) #Aquí guarda la configuración de Ayuda: ayuda = { 'sin_ayuda': values['sin_ayuda'], 'definiciones': values['con_definiciones'], 'palabras': values['con_palabras'], 'con_ayuda': values['con_ayuda'] } print(ayuda) #Guardo la orientación de las palabras en la sopa de letras: if values['vertical']: orientacion = 'vertical' else: orientacion = 'horizontal' #Elimino del diccionario las palabras que no imprimo: for palabra in lista_palabras_eliminar: try: diccionario_palabras.pop(palabra) except KeyError: a + 1 #solucion para el key error #Finalmente, guardo todo lo anterior en un solo diccionario y lo retorno: datos_configurados = { 'colores': colours, 'tipografia': tipografia, 'cant_palabras': cant_palabras, 'palabras': lista_palabras_final, 'diccionario': diccionario_palabras, 'orientacion': orientacion, 'ayuda': ayuda } print(datos_configurados) break window.Close() return datos_configurados
import PySimpleGUI as sg from events import check_pigpio_service, run, get_pi_info from devices import * from style import * sg.theme(window_theme) connect_layout = sg.Frame('Access', [[sg.Text('Host:'), sg.InputText(default_text='192.168.122.92', size=(15, 1), key='-host-'), sg.InputText(default_text='8888', size=(6, 1), justification='center', key='-port-'), sg.Button('connect', size=(8, 1), key='-connect-')] ]) status_layout = sg.Frame('Status', [[sg.Button(image_data=icon_status_off, key='-status-', button_color=(sg.theme_background_color(), sg.theme_background_color())), sg.Button(image_data=icon_pi, size=(50, 20), button_color=(sg.theme_background_color(), sg.theme_background_color()), key='-pi-')] ]) device_layout = sg.Frame('Device List', [[sg.Listbox(Devices, size=(18, 10), background_color=sg.theme_background_color(), enable_events=True, key='-device-')]]) description_layout = sg.Frame('Description', [[sg.ML('Here is device description', font='Ubuntu 11', size=(30, 10), key='-description-')]]) column1 = sg.Column([[connect_layout]]) column2 = sg.Column([[status_layout]])
[ sg.Text('All graphic widgets in one form!', 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.Checkbox('Checkbox', size=(10, 1)), sg.Checkbox('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) ], [ sg.Multiline( default_text= 'This is the default Text should you decide not to type anything', size=(35, 3)), sg.Multiline(default_text='A second multi-line', size=(35, 3)) ], [
def __init__(self): sg.set_options(text_justification='right') sg.theme('Reddit') teach_gait0 = [[ sg.Text('Swinging Hip (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=2, key='gait-0-swinging-hip-min'), sg.Text('Swinging Hip (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=2, key='gait-0-swinging-hip-max') ], [ sg.Text('Swinging Knee (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-10, key='gait-0-swinging-knee-min'), sg.Text('Swinging Knee (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-10, key='gait-0-swinging-knee-max') ], [ sg.Text('Planted Hip (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-5, key='gait-0-planted-hip-min'), sg.Text('Planted Hip (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=1, key='gait-0-planted-hip-max') ], [ sg.Text('Planted Knee (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=1, key='gait-0-planted-knee-min'), sg.Text('Planted Knee (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=1, key='gait-0-planted-knee-max') ]] teach_gait1 = [[ sg.Text('Swinging Hip (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=2, key='gait-1-swinging-hip-min'), sg.Text('Swinging Hip (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=2, key='gait-1-swinging-hip-max') ], [ sg.Text('Swinging Knee (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-1, key='gait-1-swinging-knee-min'), sg.Text('Swinging Knee (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-1, key='gait-1-swinging-knee-max') ], [ sg.Text('Planted Hip (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-10, key='gait-1-planted-hip-min'), sg.Text('Planted Hip (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=1, key='gait-1-planted-hip-max') ], [ sg.Text('Planted Knee (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=1, key='gait-1-planted-knee-min'), sg.Text('Planted Knee (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=6, key='gait-1-planted-knee-max') ]] teach_gait2 = [[ sg.Text('Swinging Hip (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-6, key='gait-2-swinging-hip-min'), sg.Text('Swinging Hip (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-6, key='gait-2-swinging-hip-max') ], [ sg.Text('Swinging Knee (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=1, key='gait-2-swinging-knee-min'), sg.Text('Swinging Knee (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=1, key='gait-2-swinging-knee-max') ], [ sg.Text('Planted Hip (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-3, key='gait-2-planted-hip-min'), sg.Text('Planted Hip (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=1, key='gait-2-planted-hip-max') ], [ sg.Text('Planted Knee (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=1, key='gait-2-planted-knee-min'), sg.Text('Planted Knee (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=1, key='gait-2-planted-knee-max') ]] teach_gait3 = [[ sg.Text('Swinging Hip (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=10, key='gait-3-swinging-hip-min'), sg.Text('Swinging Hip (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=10, key='gait-3-swinging-hip-max') ], [ sg.Text('Swinging Knee (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-10, key='gait-3-swinging-knee-min'), sg.Text('Swinging Knee (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-10, key='gait-3-swinging-knee-max') ], [ sg.Text('Planted Hip (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=-3, key='gait-3-planted-hip-min'), sg.Text('Planted Hip (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=2, key='gait-3-planted-hip-max') ], [ sg.Text('Planted Knee (Min)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=1, key='gait-3-planted-knee-min'), sg.Text('Planted Knee (Max)', size=(15, 1)), sg.Slider(range=(-10, 10), orientation='h', size=(7, 10), default_value=5, key='gait-3-planted-knee-max') ]] layout = [[ sg.StatusBar('Gait Phase: Waiting to Start Training.', key='teaching-button-1') ], [sg.Frame('Gait Phase 0: Start', teach_gait0, font='Any 12')], [ sg.Frame('Gait Phase 1: Lift Swinging Leg', teach_gait1, font='Any 12') ], [ sg.Frame('Gait Phase 2: Plant Swinging Leg', teach_gait2, font='Any 12') ], [ sg.Frame('Gait Phase 3: Switch Legs, Swing Leg', teach_gait3, font='Any 12') ], [ sg.Radio('Lesson 1: Practice first step.', "lessons", key='radio-1', default=True), sg.Radio('Lesson 2', "lessons", key='radio-2') ], [sg.Submit(), sg.Cancel()]] sg.set_options(text_justification='left') self.window = sg.Window('Machine Teaching Interface - Bipedal Walker', layout, font=("Helvetica", 12))
def layoutVisuGraph(list_panel, layout_graph_drawing, layout_color_drawing): col_graphs1 = [ [ sg.Text('Input : List of genes', text_color='#e4e4e4', background_color='#343434') ], [ sg.Listbox( values=genes_names_list, select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, size=(20, 15), tooltip= 'Highlighted genes will be set to 1 at the start of each simulation run if the choice of genes initial states parameter is << specified >>' ) ], ] col_graphs2 = [ [ sg.Frame(layout=[ [ sg.Text('State', text_color='#e4e4e4', background_color='#343434', tooltip='Select number state'), sg.Combo(values=list_panel, default_value=list_panel[0]), sg.Text('Layout', text_color='#e4e4e4', background_color='#343434'), sg.Combo(values=layout_graph_drawing, default_value=layout_graph_drawing[0]) ], [ sg.Text('Active genes color', text_color='#e4e4e4', background_color='#343434', tooltip='Select color of inactive genes'), sg.Combo(values=layout_color_drawing, default_value=layout_color_drawing[3]), sg.Text('Inactive genes color', text_color='#e4e4e4', background_color='#343434', tooltip='Select color of inactive genes'), sg.Combo(values=layout_color_drawing, default_value=layout_color_drawing[0]) ], [ sg.Text('Active interaction color', text_color='#e4e4e4', background_color='#343434', tooltip='Select color of active interaction'), sg.Combo(values=layout_color_drawing, default_value=layout_color_drawing[10]), sg.Text('Inactive interaction color', text_color='#e4e4e4', background_color='#343434', tooltip='Select color of inactive interaction'), sg.Combo(values=layout_color_drawing, default_value=layout_color_drawing[10]) ], [ sg.Text('Width active Interaction', text_color='#e4e4e4', background_color='#343434', tooltip='Value must a number'), sg.InputText(size=(5, 1), default_text="1") ], [sg.Button('Launch visualization')] ], title='Vsualization settings', title_color='#e4e4e4', background_color='#343434', relief=sg.RELIEF_GROOVE) ], [ sg.Frame( layout=[[sg.Button('Save graph'), sg.InputText(size=(35, 1))]], title='Save Data', title_color='#e4e4e4', background_color='#343434', relief=sg.RELIEF_GROOVE, tooltip='The file extension CSV will be automatically added') ], [ sg.Frame( layout=[[sg.Button('Save gene activity')]], title='Save gene activity graph', title_color='#e4e4e4', background_color='#343434', relief=sg.RELIEF_GROOVE, tooltip='The file extension CSV will be automatically added') ], [sg.Text('', background_color='#343434')] ] layout_graphs = [[ sg.Column(col_graphs1, background_color='#343434'), sg.Column(col_graphs2, background_color='#343434') ], [ sg.Text('Extract core network :', text_color='#e4e4e4', background_color='#343434') ], [sg.Exit()]] window_graphs = sg.Window("Initialize Network", alpha_channel=0.95, layout=layout_graphs) return window_graphs
def dibujar(): config_dicc, palabras_dicc, _ = config.cargar_configuracion() palabras_lista = config.obtener_lista_palabras(config_dicc) fuente = config_dicc['fuente'] colores_celda = config.colores(config_dicc) color_fondo = colores_celda['fondo'] #Colores marcas color_celda_marcada = colores_celda['marcada'] color_marca = { None: colores_celda[None], 'adj': ('#262730', config_dicc['color_pincel']['adj']), 'verb': ('#262730', config_dicc['color_pincel']['verb']), 'sust': ('#262730', config_dicc['color_pincel']['sust']), 'Erroneas': colores_celda['Erroneas'], 'MIXTO': colores_celda['MIXTO'] } color_celda_default = colores_celda['default'] # ~ print('Cargo en dibujar()',config_dicc['orientacion']) print('Creo lista de palabras random en dibujar()') print('palabras_lista =', palabras_lista) ## Defino el ancho de la grilla como el mayor entre la cantidad de palabras o la palabra mas larga ANCHO = max( len(max(palabras_lista, key=len)), len(palabras_lista) ) # key = len hace que sea por cantidad de char y no alfabeticamente ## O solo la palabra más larga #ANCHO = len(max(palabras_lista, key=len)) ## Y siquieropuede ser cuadrada ALTO = ANCHO ## Crear la matriz de elementos y llenarla con las letras matriz = crear_grilla(palabras_lista) def ayuda(palabras_lista, palabras_dicc, config_dicc): """depende de lo recibido en la configuracion de ayuda modifica el layout para que informe lo correspondiente a cada caso""" """ ayuda_layout lista creada para agregarlo al frame al layout de la sopa""" # cantv, cantadj, cantsust = cantidad_pal(palabras_dicc) ayuda_layout = [] if config_dicc['ayuda'] == 'sin ayuda': column1 = [[ sg.T('Total de palabras a buscar: ' + str(len(palabras_lista)), justification='center') ], [sg.T('Sustantivos: ' + str(config_dicc['max_sust']))], [sg.T('Verbos: ' + str(config_dicc['max_verb']))], [sg.T('Adjetivos: ' + str(config_dicc['max_adj']))]] ayuda_layout = [[sg.Column(column1)]] # si es definiciones agrega al layout un numero para la palabra y su descripcion. # 'palabra num-'+str(j) : asigna un numero a la palabra para mostrar en layout. # palabras_dicc[palabras_lista[j]]['def'] : accese a la descripcion de la palabra a la que referencia el numero para informar. # para referenciado por numero toma la posicion en la lista de palabras. elif config_dicc['ayuda'] == 'definiciones': column1 = [[ sg.T('-' + str(j) + ': ' + palabras_dicc[palabras_lista[j]]['def'], auto_size_text=True) ] for j in range(len(palabras_lista))] ayuda_layout = [[sg.T('Definiciones: ')], [sg.Column(column1)]] elif config_dicc['ayuda'] == 'palabras': column1 = [ ## agrego que el color aparezca en modo fácil, buscar el tipo en el dicc de colores, el segundo elemento porque es una tupla (texto, fondo) [ sg.T(palabras_lista[j], background_color=color_marca[palabras_dicc[ palabras_lista[j]]['tipo']][1]) ] for j in range(len(palabras_lista)) ] ayuda_layout = [[sg.T('Palabras a buscar :')], [sg.Column(column1)]] return ayuda_layout ayuda_layout = ayuda(palabras_lista, palabras_dicc, config_dicc) print('ANCHO:', ANCHO, 'Alto:', ALTO) menu_princ = [[ '&Archivo', [ '&Cargar...::Menu', '&Guardar...::Menu', '---', '!Configuracion::Menu', 'E&xit' ] ], ['&Ayuda', ['Como jugar?::Menu', 'Acerca de...::Menu']]] sopa_layout = [[ sg.Button(matriz.celdas[j][i]['letra'], button_color=color_celda_default, size=(4, 2), pad=(0, 0), font=fuente, key=str(j) + '_' + str(i)) for i in range(ANCHO) ] for j in range(ALTO)] size_pincel = (7, 2) pincel_layout = [[ sg.Text('Adj', size=size_pincel, auto_size_text=False, enable_events=True, relief='raised', text_color=color_marca['adj'][0], background_color=color_marca['adj'][1], justification='center', key='adj', tooltip='Elegir para marcar Adjetivos'), sg.Text('Verb', size=size_pincel, auto_size_text=False, enable_events=True, relief='raised', text_color=color_marca['verb'][0], background_color=color_marca['verb'][1], justification='center', key='verb', tooltip='Elegir para marcar Verbos'), sg.Text('Sust', size=size_pincel, auto_size_text=False, enable_events=True, relief='raised', text_color=color_marca['sust'][0], background_color=color_marca['sust'][1], justification='center', key='sust', tooltip='Elegir para marcar Sustantivos'), ]] #Layout principal. layout = [ [sg.Menu(menu_princ)], [ sg.Frame('Seleccionar color: ', pincel_layout), sg.Button(' Comprobar Victoria', pad=((260, 0), None), key='comprobar victoria', tooltip='Marca con blanco las marcadas erroneamente.') ], [ sg.Frame('', sopa_layout, font=config_dicc['fuente'], pad=(0, 0)), sg.Frame('Ayudas: ', [[sg.Text('Direcciones:', pad=((20, 0), 0))], [ sg.Button(image_filename=config_dicc['orientacion'] + '.png', image_size=(80, 80), image_subsample=4, border_width=0, pad=((30, 0), (10, 30)), button_color=color_fondo) ], [sg.Column(ayuda_layout)]]) ] ] layout.append([sg.Button('Cerrar', pad=((580, 10), (5, 3)))]) window = sg.Window('Sopa de Letras').Layout(layout) start_time = time.time() def comprobar_victoria(layout, matriz): """si seleccionamos boton comprobar victorias marca en blanco todas las letras que hayan sido presionadas erroneamente.""" """recorre toda la matriz comprobando que las celdas marcadas sean correctas""" for j in range(ANCHO): for i in range(ALTO): if matriz.celdas[j][i]['marcada'] == True: if matriz.celdas[j][i]['tipo'] in ('adj', 'verb', 'sust', 'MIXTO'): if matriz.celdas[j][i]['color'] != color_marca[ matriz.celdas[j][i]['tipo']] and matriz.celdas[ j][i]['tipo'] != 'MIXTO': window.FindElement(str(j) + '_' + str(i)).Update( button_color=color_marca['Erroneas']) matriz.celdas[j][i]['color'] = ( color_marca['Erroneas']) window.Refresh() else: window.FindElement(str(j) + '_' + str(i)).Update( button_color=color_marca['Erroneas']) matriz.celdas[j][i]['color'] = ( color_marca['Erroneas']) def Win_Condition(matriz, win): """primera parte: si la celda presionada esta marcada la desmarca y le asigna color Default. Sino la marca y le asigna color de celda marcada.""" """segunda parte: comprueba victoria atravez de un AND. si encuentra una celda que este marcada erroneamente arrastra el False.""" for i in range(ANCHO): for j in range(ALTO): if (matriz.celdas[j][i]['key'] == event): if matriz.celdas[j][i]['marcada']: matriz.celdas[j][i]['marcada'] = False color_celda = color_celda_default else: matriz.celdas[j][i]['marcada'] = True color_celda = color_celda_marcada matriz.celdas[j][i]['color'] = color_celda window.FindElement(event).Update(button_color=color_celda) if matriz.celdas[j][i]['tipo'] != None: if matriz.celdas[j][i]['tipo'] == 'MIXTO': if not (matriz.celdas[j][i]['marcada']): win *= False else: win *= True else: if matriz.celdas[j][i]['color'] != color_marca[ matriz.celdas[j][i] ['tipo']]: #no pudimos extraer el color de pysimplegui por eso le agregamos una key 'color' a la matriz win *= False else: win *= True else: if (matriz.celdas[j][i]['marcada']): win *= False else: win *= True return win def Mensaje_Victoria(): print('\nGanaste!') x_max, y_max = window.GetScreenDimensions() for rep in range(5): margen = 150 x_0, y_0 = random.randrange(x_max - margen - 50), random.randrange(y_max - margen - 50) # ~ x_0, y_0 = 555,450 sign = random.choice([-1, 1]) v_x = sign * random.randrange(1, 50) v_y = -1 * random.randrange(10, 30) # ~ v_x, v_y = 10,10 g = 5 t = 0 rebote = 0 x, y = x_0, y_0 while rebote < 3 and t < 500: x = x + v_x v_y = v_y + g y = y + v_y rand_col = [ '#' + ''.join( [random.choice('0123456789ABCDEF') for j in range(6)]) for i in range(4) ] # ~ print(rand_col)## ['#C7980A', '#F4651F', '#82D8A7', '#CC3A05', '#575E76', '#156943', '#0BD055', '#ACD338'] sg.Popup( ' W I N N E R ', button_color=( rand_col[0], rand_col[1] ), # Color of buttons (text_color, background_color) background_color=rand_col[2], # Color of background text_color=rand_col[3], # Color of text # ~ button_type = 'POPUP_BUTTONS_NO_BUTTONS', auto_close=True, # If True window will automatically close auto_close_duration=5, # Number of seconds for autoclose non_blocking=True, # If True returns immediately line_width=50, # Width of lines in characters font='Fixedsys', # Font to use for characters no_titlebar=False, # If True no titlebar will be shown grab_anywhere= False, # If True can move window by grabbing anywhere keep_on_top= True, # If True window will be on top of other windows location=(x, y) # (x,y) coordinates to show the window ) if x < 5: v_x = -1 * v_x if y < 5: v_y = -1 * v_y if x > x_max - margen: v_x = -1 * v_x if y > y_max - margen: rebote += 1 v_y = -1 * v_y t += 1 elapsed_time = time.time() - start_time elapsed_time = time.strftime("%H:%M:%S", time.gmtime(elapsed_time)) playsound('mlg-airhorn.mp3') sg.Popup('¡¡GANASTE!!\nTiempo: ' + elapsed_time, font='Fixedsys', keep_on_top=True) while True: # Event Loop event, val = window.Read() if event is None or event == 'Cerrar': break if event == 'Guardar...::Menu': filename = 'savegame.sav' print('Guardo en ', filename) window.SaveToDisk(filename) if event == 'Cargar...::Menu': filename = 'savegame.sav' print('Cargar ', filename) window.LoadFromDisk(filename) if event == 'Como jugar?::Menu': window.SetAlpha(0.5) sg.Popup(HOWTO, font='System', keep_on_top=True) window.Reappear() if event == 'Acerca de...::Menu': window.SetAlpha(0.5) sg.Popup(CREDITS, font='System', keep_on_top=True) window.Reappear() if event == 'comprobar victoria': comprobar_victoria(layout, matriz) if event in ('adj', 'verb', 'sust'): # Si toco el pincel color_celda_marcada = color_marca[event] for element in ('adj', 'verb', 'sust'): window.FindElement(element).Update(value=element) window.FindElement(event).Update(value='* ' + event.upper() + ' *') win = True win = Win_Condition(matriz, win) if win == True and event == 'comprobar victoria': Mensaje_Victoria() print(event) window.Close()
def layoutBooleanModelVisu(): col_visu1 = [ [ sg.Text('Input : List of genes', text_color='#e4e4e4', background_color='#343434') ], [ sg.Listbox( values=genes_names_list, select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, size=(20, 35), tooltip= 'Highlighted genes will be set to 1 at the start of each simulation run if the choice of genes initial states parameter is << specified >>' ) ], ] col_visu2 = [ [ sg.Text('Input : Interactions in the network', text_color='#e4e4e4', background_color='#343434') ], [ sg.Listbox( values=network_as_list, select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, size=(30, 35), tooltip= 'Format is [Source gene, interaction (-1: repression, 1 : activation), target gene]' ) ], ] # col_subbatch3 = [[sg.Listbox(values=model_type_list, select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, size=(15, 4), # tooltip='Highlight the models to run through ARGOS'), # sg.Listbox(values=boundary_model_list, select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, size=(15, 4), # tooltip='Highlight the models to run through ARGOS')]] col_visu3 = [[ sg.Frame(layout=[ [ sg.Text( 'Model type', text_color='#e4e4e4', background_color='#343434', tooltip='Choice of rules to apply to the network structure' ), sg.Combo(values=model_type_list, default_value=model_type_list[0]) ], [ sg.Text( 'Boundary conditions', text_color='#e4e4e4', background_color='#343434', tooltip='Choice of behavior for nodes without regulators'), sg.Combo(values=boundary_model_list, default_value=boundary_model_list[0]) ], [ sg.Text( 'Genes initial states', text_color='#e4e4e4', background_color='#343434', tooltip= 'In <<specified>> mode, use the gene list panel to highlight the genes to be set to 1 at start,\n all other genes will be set to 0 (0 or 1 in <<random-specified>> mode)' ), sg.Combo(values=initial_states_choice_list, default_value=initial_states_choice_list[0]) ], [ sg.Text( 'Number of initial states :', text_color='#e4e4e4', background_color='#343434', tooltip= 'Choice of how many initial states the model will run from' ), sg.Radio('All possible states', 'RADIO2', background_color='#343434', text_color='#e4e4e4'), sg.Radio('Given number of states', 'RADIO2', background_color='#343434', text_color='#e4e4e4', default=True), sg.InputText(size=(10, 1), default_text='1') ], [ sg.Text( 'KO mutation type', text_color='#e4e4e4', background_color='#343434', tooltip= 'Choice of Knocked Out mutation to apply to the network \n- single KO will run the model mutating each chosen genes one at a time' '\n- multiple KO will run the model once with all chosen genes as KO' '\n- combination KO will go through all combinations of double KO for the chosen genes and run the model for each' ), sg.Combo(values=KO_mutation_type_list, default_value=KO_mutation_type_list[0]) ], [ sg.Text( 'List of KO genes', text_color='#e4e4e4', background_color='#343434', tooltip= 'Enter gene names separated by a colon e.g. ABC, LMN, XYZ' ), sg.InputText() ], [ sg.Text( 'OA mutation type', text_color='#e4e4e4', background_color='#343434', tooltip= 'Choice of Over Activated mutation to apply to the network \n- single OA will run the model mutating each chosen genes one at a time' '\n- multiple OA will run the model once with all chosen genes as KO' '\n- combination OA will go through all combinations of double KO for the chosen genes and run the model for each' ), sg.Combo(values=OA_mutation_type_list, default_value=OA_mutation_type_list[0]) ], [ sg.Text( 'List of OA genes', text_color='#e4e4e4', background_color='#343434', tooltip= 'Enter gene names separated by a colon e.g. ABC, LMN, XYZ' ), sg.InputText() ], [sg.Button('Run HELIOS'), sg.Button('Run HELIOS 2')] ], title='Predict System Fates', title_color='#e4e4e4', background_color='#343434', relief=sg.RELIEF_GROOVE) ], [ sg.Frame(layout=[[ sg.Text('Source', text_color='#e4e4e4', background_color='#343434', tooltip='Value must a number'), sg.InputText(size=(10, 1)), sg.Text( 'Interaction', text_color='#e4e4e4', background_color='#343434', tooltip='1 for activation or -1 for inhibition'), sg.InputText(size=(10, 1)), sg.Text('Target', text_color='#e4e4e4', background_color='#343434', tooltip='Value must a '), sg.InputText(size=(10, 1)), sg.Button('Add element') ]], title='Add element to graph', title_color='#e4e4e4', background_color='#343434', relief=sg.RELIEF_GROOVE) ], [ sg.Frame(layout=[[ sg.Button('Add element from CSV'), sg.Input(), sg.FileBrowse() ]], title='Add element from CSV', title_color='#e4e4e4', background_color='#343434', relief=sg.RELIEF_GROOVE) ], [ sg.Frame(layout=[[ sg.Input(), sg.FileBrowse(), sg.Button("Load") ]], title='Load saved graph', title_color='#e4e4e4', background_color='#343434', relief=sg.RELIEF_GROOVE) ], [sg.Text('', background_color='#343434')]] layout_visu = [[ sg.Column(col_visu1, background_color='#343434'), sg.Column(col_visu2, background_color='#343434'), sg.Column(col_visu3, background_color='#343434') ], [ sg.Text('Extract core network :', text_color='#e4e4e4', background_color='#343434') ], [sg.Exit()]] window_visu = sg.Window("Initialize Network", alpha_channel=0.95, layout=layout_visu) return window_visu
col_widths=[15, 6], justification='left', key="_TOTAL_PIZZA_", num_rows=5, enable_events=True), sg.Button('Remove') ], [sg.T(" ", pad=((0, 0), (1, 0)))]] tab1_layout = [[ sg.T('Create Order', font='sfprodisplay 25 bold', justification='center', size=(49, 0)) ], [ sg.Frame("", frame1_layout, border_width=0, pad=((0, 70), (0, 0))), sg.Frame("", frame2_layout, border_width=0, pad=((70, 0), (0, 0))) ], [ sg.T('Total Cost', size=(26, 0), font='sfprodisplay 18 bold underline', justification='center', pad=((300, 0), (0, 0))) ], [ sg.T('$0.00',
def start_filter_GUI(): OG_IMG = None F_IMG = None menu_toolbar = [['&File', ['&Open', '&Save', '&Exit']], ['&Filters', ['&Grayscales' , ['Average Grayscale', 'Grayscale', 'Luma Grayscale', '---', 'Max and Min Grayscale', 'Max Grayscale', 'Min Grayscale', '---', 'Red Grayscale', 'Green Grayscale', 'Blue Grayscale', '---', 'Shades of Gray'], '&Brightness', '&Mosaics', ['&Mosaic', '&Image BnW', '&Image true colors'], '&High contrast', '&Inverted', '&RGB components', '&Convolution', ['&Blur', '&Motion blur', '&Find edges' , '&Sharpen', '&Emboss'], '&Text', ['&Color Ms', '&Grayscale Ms', '---', '&Color characters', '&Black and White characters', '&Grayscale characters', '---', '&Sign', '---', '&Black dominoes', '&White dominoes','---', '&Cards'], '&Blending' , '&Watermark', '&Semitones', ['&Semitone a', '&Semitone b', '&Semitone c'], '&Max Min', ['Max', 'Min'], 'Dithering', ['Random', 'Clustered', 'Scattered'], 'Fotomorsaics', ['Fotomorsaic'] ]], ['&Tools', ['Create Library',]], ['&Help', '&About...'], ] column1_layout = [ [sg.Frame(title='Original image', layout=[[sg.Image(size=IMG_SIZE, pad=(0, 5), key='-OG_IMAGE-', background_color=BG_COLOR)]], background_color=BG_COLOR, size=FRM_SIZE, key='-OGF_IMAGE-', relief=sg.RELIEF_RAISED)] ] column2_layout = [ [sg.Frame(title='Modified image', layout=[[sg.Image(size=IMG_SIZE, pad=(0, 5), key='-F_IMAGE-', background_color=BG_COLOR)]], background_color=BG_COLOR, size=FRM_SIZE, key='-FF_IMAGE-', relief=sg.RELIEF_RAISED)] ] main_layout = [ [sg.Menu(menu_definition=menu_toolbar, tearoff=False, background_color=MAIN_COLOR, text_color=TXT_COLOR)], [sg.Column(column1_layout, size=COL_SIZE, background_color= MAIN_COLOR, ), sg.VerticalSeparator(), sg.Column(column2_layout, size=COL_SIZE, background_color=MAIN_COLOR) ], ] main_window = sg.Window('Filter app', layout=main_layout, size=RESOLUTION, resizable=True, background_color=MAIN_COLOR, ) while True: event, values = main_window.read() if event in (sg.WIN_CLOSED, 'Exit'): break # ------ Process menu choices ------ # if event == 'Open': filename = sg.popup_get_file('File to open', no_window=True, keep_on_top=True, modal=True, file_types=(("PNG, JPG", "*.png *.jpg"),)) img, img_bytes = convert_to_bytes(filename) if img != None and img_bytes != None: pb_layout = [[sg.Text('Loading...')], [sg.ProgressBar(max_value=10, orientation='h', size=(40, 15), key='-PGRB-')] ] pb_window = sg.Window('Loading image', pb_layout, finalize=True, disable_close=True, modal=True) progress_bar = pb_window['-PGRB-'] progress_bar.update_bar(2) OG_IMG = img.copy() F_IMG = OG_IMG.copy() progress_bar.update_bar(5) T_IMG = F_IMG.copy() T_IMG.thumbnail(size=IMG_SIZE) img.thumbnail(size=IMG_SIZE) progress_bar.update_bar(8) main_window['-OG_IMAGE-'].update(data=get_bytes(img), size=IMG_SIZE) main_window['-F_IMAGE-'].update(data=get_bytes(T_IMG), size=IMG_SIZE) progress_bar.update_bar(9) pb_window.close() if F_IMG != None: if event == 'Save': filename = ask_for_filename(default_filename='My_filter_img.png') if filename != None: F_IMG.save(filename, format='PNG') if OG_IMG != None: pb_layout = [[sg.Text('Loading...')], [sg.ProgressBar(max_value=10, orientation='h', size=(45, 15), key='-PGRB-')] ] if event == 'Average Grayscale': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Grayscale': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Luma Grayscale': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Max and Min Grayscale': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Max Grayscale': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Min Grayscale': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Red Grayscale': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Green Grayscale': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Blue Grayscale': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Shades of Gray': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Brightness': b_event, b_values = sg.Window('Brightness', [ [sg.T('Adjust brightness')], [sg.Slider(range=(-180, 180), default_value=0, resolution=1, tick_interval=100, orientation='h', border_width=3, size=(40, 10), key='-BRGHT-', tooltip='Brightness')], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) brightness_value = b_values['-BRGHT-'] if brightness_value != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, int(brightness_value)) elif event == 'Mosaic': b_event, b_values = sg.Window('Mosaic', [ [sg.T('Adjust mosaic size')], [sg.T('Height')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-H_VALUE-', tooltip='Height')], [sg.T('Width')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-W_VALUE-', tooltip='Width')], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) w_value = b_values['-W_VALUE-'] h_value = b_values['-H_VALUE-'] if w_value != None and h_value != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, int(w_value), int(h_value)) elif event == 'High contrast': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Inverted': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'RGB components': b_event, b_values = sg.Window('RGB components', [ [sg.T('Adjust RGB components')], [sg.T('Red')], [sg.Slider(range=(0, 255), default_value=0, resolution=1, tick_interval=40, orientation='h', border_width=3, size=(40, 10), key='-R_VALUE-', tooltip='Red')], [sg.T('Green')], [sg.Slider(range=(0, 255), default_value=0, resolution=1, tick_interval=40, orientation='h', border_width=3, size=(40, 10), key='-G_VALUE-', tooltip='Green')], [sg.T('Blue')], [sg.Slider(range=(0, 255), default_value=0, resolution=1, tick_interval=40, orientation='h', border_width=3, size=(40, 10), key='-B_VALUE-', tooltip='Blue')], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) red = b_values['-R_VALUE-'] green = b_values['-G_VALUE-'] blue = b_values['-B_VALUE-'] if red != None and green != None and blue != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, int(red), int(green), int(blue)) elif event == 'Blur': b_event, b_values = sg.Window('Blur', [ [sg.T('Select intensity matrix for blur filter')], [sg.Radio(text='3x3 Matrix', group_id=1, default=True, key='-3_M-'), sg.Radio(text='5x5 Matrix', group_id=1, default=False, key='-5_M-') ], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) selection = 0 if b_values['-3_M-'] else 1 if selection != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, selection) elif event == 'Motion blur': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Find edges': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Sharpen': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Emboss': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Color Ms': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Grayscale Ms': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Black and White characters': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Color characters': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Grayscale characters': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Sign': s_event, s_values = sg.Window('Sign', layout=[ [sg.T('Type a message for sign filter (20 characters maximum)')], [sg.Input(default_text='This is my message', size=(80, 10), tooltip='Type something!', do_not_clear=False, key='-SIGN_TXT-')], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) message = s_values['-SIGN_TXT-'] if message != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, message) elif event == 'Black dominoes': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'White dominoes': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Cards': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Blending': filename = sg.popup_get_file('Image to blend', no_window=True, keep_on_top=True, modal=True, file_types=(("PNG, JPG", "*.png *.jpg"),)) img_to_blend, img_bytes = convert_to_bytes(filename) if img_to_blend != None and img_bytes != None: b_event, b_values = sg.Window('Blending', [ [sg.T('Adjust blending')], [sg.Column([[sg.Frame(title='Image to blend', layout=[[sg.Image(size=(230, 230), pad=(0, 5), key='-OG_IM-', data=get_bytes(img_to_blend.copy().resize((230,230))), background_color=BG_COLOR)]], background_color=BG_COLOR, size=(240, 240), key='-OGF_IM-', relief=sg.RELIEF_RAISED)]], size=(250, 250), background_color= MAIN_COLOR, ), sg.VerticalSeparator(), sg.Column([[sg.Frame(title='Original image', layout=[[sg.Image(size=(230, 230), pad=(0, 5), key='-BD_IM-', data=get_bytes(OG_IMG.copy().resize((230,230))), background_color=BG_COLOR)]], background_color=BG_COLOR, size=(240, 240), key='-BDF_IM-', relief=sg.RELIEF_RAISED)]], size=(250, 250), background_color= MAIN_COLOR, ), ], [sg.Slider(range=(0, 100), default_value=50, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-BLDN-', tooltip='Blending')], [sg.Button('Ok')] ], element_justification='center', modal=True, keep_on_top=True).read(close=True) blending_value = b_values['-BLDN-'] if blending_value != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, img_to_blend, blending_value * 0.01) elif event == 'Watermark': w_layout = [[sg.T('Set your watermark')], [sg.HorizontalSeparator()], [sg.T('Position')], [sg.T('Horizontal'), sg.Radio(text='Left', group_id=1, default=True, key='-L_H-'), sg.Radio(text='Center', group_id=1, default=False, key='-C_H-'), sg.Radio(text='Right', group_id=1, default=False, key='-R_H-'), sg.VerticalSeparator(), sg.T('Vertical'), sg.Radio(text='Top', group_id=2, default=True, key='-T_V-'), sg.Radio(text='Center', group_id=2, default=False, key='-C_V-'), sg.Radio(text='Bottom', group_id=2, default=False, key='-B_V-')], [sg.T('Text (60 characters maximum)')], [sg.Input(default_text='This is my watermark', size=(80, 10), tooltip='Type something!', do_not_clear=False, key='-WM_TXT-')], [sg.T('Alpha')], [sg.Slider(range=(0, 100), default_value=50, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-ALPHA-', tooltip='Alpha')], [sg.Button('Ok')] ] w_event, w_values = sg.Window(title='Watermark', layout=w_layout, element_justification='center', modal=True, keep_on_top=True).read(close=True) text = w_values['-WM_TXT-'] w_h = 2 if w_values['-L_H-']: w_h = 0 elif w_values['-C_H-']: w_h = 1 w_v = 2 if w_values['-T_V-']: w_v = 0 elif w_values['-C_V-']: w_v = 1 position = (w_h, w_v) alpha = w_values['-ALPHA-'] if text != None and alpha != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, text, position, alpha * 0.01) elif event =='Image BnW': filename = sg.popup_get_file('Image for grid', no_window=True, keep_on_top=True, modal=True, file_types=(("PNG, JPG", "*.png *.jpg"),)) img_for_grid, img_bytes = convert_to_bytes(filename) if img_for_grid != None and img_bytes != None: b_event, b_values = sg.Window('Mosaic', [ [sg.Column([[sg.Frame(title='Image for grid', layout=[[sg.Image(size=(230, 230), pad=(0, 5), key='-OG_IM-', data=get_bytes(img_for_grid.copy().resize((230,230))), background_color=BG_COLOR)]], background_color=BG_COLOR, size=(240, 240), key='-OGF_IM-', relief=sg.RELIEF_RAISED)]], size=(250, 250), background_color= MAIN_COLOR, ), sg.VerticalSeparator(), sg.Column([[sg.Frame(title='Base image', layout=[[sg.Image(size=(230, 230), pad=(0, 5), key='-BD_IM-', data=get_bytes(OG_IMG.copy().resize((230,230))), background_color=BG_COLOR)]], background_color=BG_COLOR, size=(240, 240), key='-BDF_IM-', relief=sg.RELIEF_RAISED)]], size=(250, 250), background_color= MAIN_COLOR, ), ], [sg.T('Adjust mosaic size')], [sg.T('Height')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-H_VALUE-', tooltip='Height')], [sg.T('Width')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-W_VALUE-', tooltip='Width')], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) w_value = b_values['-W_VALUE-'] h_value = b_values['-H_VALUE-'] if w_value != None and h_value != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, img_for_grid, int(w_value), int(h_value)) elif event == 'Image true colors': filename = sg.popup_get_file('Image for grid', no_window=True, keep_on_top=True, modal=True, file_types=(("PNG, JPG", "*.png *.jpg"),)) img_for_grid, img_bytes = convert_to_bytes(filename) if img_for_grid != None and img_bytes != None: b_event, b_values = sg.Window('Mosaic true colors', [ [sg.Column([[sg.Frame(title='Image for grid', layout=[[sg.Image(size=(230, 230), pad=(0, 5), key='-OG_IM-', data=get_bytes(img_for_grid.copy().resize((230,230))), background_color=BG_COLOR)]], background_color=BG_COLOR, size=(240, 240), key='-OGF_IM-', relief=sg.RELIEF_RAISED)]], size=(250, 250), background_color= MAIN_COLOR, ), sg.VerticalSeparator(), sg.Column([[sg.Frame(title='Base image', layout=[[sg.Image(size=(230, 230), pad=(0, 5), key='-BD_IM-', data=get_bytes(OG_IMG.copy().resize((230,230))), background_color=BG_COLOR)]], background_color=BG_COLOR, size=(240, 240), key='-BDF_IM-', relief=sg.RELIEF_RAISED)]], size=(250, 250), background_color= MAIN_COLOR, ), ], [sg.T('Adjust mosaic size')], [sg.T('Height')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-H_VALUE-', tooltip='Height')], [sg.T('Width')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-W_VALUE-', tooltip='Width')], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) w_value = b_values['-W_VALUE-'] h_value = b_values['-H_VALUE-'] if w_value != None and h_value != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, img_for_grid, int(w_value), int(h_value)) elif event == 'Semitone a': b_event, b_values = sg.Window('Semitone a', [ [sg.T('Adjust mosaic size')], [sg.T('Height')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-H_VALUE-', tooltip='Height')], [sg.T('Width')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-W_VALUE-', tooltip='Width')], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) w_value = b_values['-W_VALUE-'] h_value = b_values['-H_VALUE-'] if w_value != None and h_value != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, 0, int(w_value), int(h_value)) elif event == 'Semitone b': b_event, b_values = sg.Window('Semitone b', [ [sg.T('Adjust mosaic size')], [sg.T('Height')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-H_VALUE-', tooltip='Height')], [sg.T('Width')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-W_VALUE-', tooltip='Width')], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) w_value = b_values['-W_VALUE-'] h_value = b_values['-H_VALUE-'] if w_value != None and h_value != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, 1, int(w_value), int(h_value)) elif event == 'Semitone c': b_event, b_values = sg.Window('Semitone c', [ [sg.T('Adjust mosaic size')], [sg.T('Height')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-H_VALUE-', tooltip='Height')], [sg.T('Width')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-W_VALUE-', tooltip='Width')], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) w_value = b_values['-W_VALUE-'] h_value = b_values['-H_VALUE-'] if w_value != None and h_value != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, 2, int(w_value), int(h_value)) elif event == 'Max': b_event, b_values = sg.Window('Max', [ [sg.T('Select intensity matrix for Max filter')], [sg.Radio(text='3x3 Matrix', group_id=1, default=True, key='-3_M-'), sg.Radio(text='5x5 Matrix', group_id=1, default=False, key='-5_M-') ], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) selection = 3 if b_values['-3_M-'] else 5 if selection != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, (selection,selection), True) elif event == 'Min': b_event, b_values = sg.Window('Min', [ [sg.T('Select intensity matrix for Min filter')], [sg.Radio(text='3x3 Matrix', group_id=1, default=True, key='-3_M-'), sg.Radio(text='5x5 Matrix', group_id=1, default=False, key='-5_M-') ], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) selection = 3 if b_values['-3_M-'] else 5 if selection != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, (selection,selection), False) elif event == 'Random': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Clustered': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Scattered': F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window) elif event == 'Fotomorsaic': filename = sg.popup_get_file('Library idx', no_window=True, keep_on_top=True, modal=True, file_types=(("IDX", "*.idx"),)) foldername = sg.popup_get_folder('Images library', no_window=True, keep_on_top=True, modal=True) b_event, b_values = sg.Window('Mosaic', [ [sg.T('Adjust mosaic size')], [sg.T('Height')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-H_VALUE-', tooltip='Height')], [sg.T('Width')], [sg.Slider(range=(10, 100), default_value=10, resolution=1, tick_interval=20, orientation='h', border_width=3, size=(40, 10), key='-W_VALUE-', tooltip='Width')], [sg.T('Image selection')], [sg.Radio(text='Best fit', group_id=1, default=True, key='-BF-'), sg.Radio(text='Randomize', group_id=1, default=False, key='-RM-') ], [sg.Button('Ok')] ], modal=True, keep_on_top=True).read(close=True) w_value = b_values['-W_VALUE-'] h_value = b_values['-H_VALUE-'] selection = b_values['-BF-'] if w_value != None and h_value != None and filename != None and foldername != None and selection != None: F_IMG = OG_IMG.copy() apply_filter(event, F_IMG, main_window, (foldername, filename), (int(w_value), int(h_value)), selection) if event == 'Create Library': foldername = sg.popup_get_folder('Images folder', no_window=True, keep_on_top=True, modal=True) if foldername != None and foldername != '': create_library(foldername) if event == 'About...': sg.popup('Filter App', 'Version 2.00', 'Carlos Eduardo Orozco Viveros', 'Release date: 08/11/21', grab_anywhere=True, modal=True, background_color=MAIN_COLOR, text_color=TXT_COLOR, no_titlebar=True) main_window.close()
sg.Col([ ss.record('Item.name'), ss.record( 'Item.fkMenu', sg.Combo, size=(30, 10), auto_size_text=False), ss.record('Item.price'), ss.record('Item.description', sg.MLine, (30, 7)) ]) ], ss.actions('actions1', 'Item', edit_protect=False, navigation=False, save=False, search=False) ] layout += [[sg.Frame('Items', sub_layout)]] layout += [ss.actions('actions2', 'Restaurant')] # Initialize our window and database, then bind them together win = sg.Window('places to eat', layout, finalize=True) db = ss.Database(':memory:', win, sql_script='example.sql' ) # <=== load the database and bind it to the window # NOTE: ":memory:" is a special database URL for in-memory databases while True: event, values = win.read() if db.process_events( event, values): # <=== let PySimpleSQL process its own events! Simple! logger.info('PySimpleDB event handler handled the event!')
# ----- Globals ----- # # ----- Window setup ----- # sg.theme('Dark Grey') # sg.set_options(element_padding=(0, 0)) title = sg.Text('Solve-O-Matic!') def btn(name, state=False): return sg.Button(name, size=(11, 1), disabled=state) # ----- User Input window layout ----- # col1 = sg.Col([[ sg.Frame('Step 1 | Insert cube', [[sg.Sizer(200, 1)], [btn('GRAB')], [btn('SCAN', True)]], pad=(0, 0), element_justification='center') ], [ sg.Frame('Step 2 | Pick a pattern', [[sg.Sizer(200, 1)], [ sg.Button('', image_filename='images/{}'.format( PATTERNS[cube.solveto_name][0]), border_width=2, key='-SOLVETOBTN-') ], [ sg.T(cube.solveto_name, size=(15, 2),
def __init__(self, defaultWidth, defaultHeight, loader, visApp): sg.ChangeLookAndFeel('NeutralBlue') #NeutralBlue self.focusedCell = None self.focusedPath = None self.columnID = 0 self.cellID = 0 self.visApp = visApp self.loader = loader self._defaultWidth = defaultWidth self._defaultHeight = defaultHeight self.ResetCommands() self.init = False self.terminating = False try: with open('guiValues.ini', 'r') as file: self.defaults = json.loads(file.read()) except: # guiValues doesn't exist, probably is this the first time run with open('guiDefaults.ini', 'r') as file: self.defaults = json.loads(file.read()) self.showProximalSynapses = self.getDefault("proximalSynapses") self.showOnlyActiveProximalSynapses = self.getDefault( "showOnlyProximalSynapses") self.showDistalSynapses = self.getDefault("distalSynapses") self.showInputOverlapWithPrevStep = self.getDefault( "inputPrevStepOverlap") self.showPredictionCorrectness = self.getDefault( "predictionCorrectness") self.showBursting = self.getDefault("showBursting") self.wireframeChanged = True self.wireframe = self.getDefault("wireFrame") self.transparency = self.getDefault("transparencySlider") self.transparencyChanged = True self.LODvalue1 = self.getDefault("LODSlider1") self.LODvalue2 = self.getDefault("LODSlider2") self.LODChanged = True self.updateLegend = True self.updateDescriptionWindow = True self.legend = None self.description = None self.showLegend = self.getDefault("legend") self.showDescription = self.getDefault("desc") self.capture = False self.iteration = 0 self.cntIterations = 0 layout = [ [sg.Text('Iteration no. 0 ', key='iteration')], [sg.Button('STEP -1'), sg.Button('STEP +1')], [sg.Button('RUN'), sg.Button('STOP')], [ sg.InputText(self.getDefault("iterationGoto"), key="iterationGoto"), sg.Button('GOTO step') ], [ sg.Checkbox('Show proximal synapes', key="proximalSynapses", enable_events=True) ], [ sg.Checkbox('Show only active proximal synapes', key="onlyActiveProximalSynapses", enable_events=True) ], [ sg.Checkbox('Show distal synapes', key="distalSynapses", enable_events=True) ], [ sg.Checkbox('Show input overlap with prev.step', key="inputPrevStepOverlap", enable_events=True) ], [ sg.Checkbox('Show prediction correctness', key="predictionCorrectness", enable_events=True) ], [ sg.Checkbox('Show bursting', key="showBursting", enable_events=True) ], [ sg.Checkbox('Wireframe mode', key="wireFrame", enable_events=True) ], [sg.Checkbox('Show legend', key="legend", enable_events=True)], [sg.Checkbox('Show description', key="desc", enable_events=True)], [ sg.Text('Layer transparency'), sg.Slider(key='transparencySlider', range=(1, 100), orientation='h', size=(10, 10), default_value=100, enable_events=True) ], [ sg.Frame('Level of detail for columns', [[ sg.Slider(key='LODSlider1', range=(1, 1000), orientation='h', size=(20, 10), default_value=100, enable_events=True) ], [ sg.Slider(key='LODSlider2', range=(1, 10000), orientation='h', size=(20, 10), default_value=100, enable_events=True) ]]) ], [sg.Button('capture')], ] self.window = sg.Window( 'Main panel', keep_on_top=True, location=self.getDefault("mainWinPos")).Layout(layout)
def cal_layout(): col1 = sg.Col([[ sg.Frame( 'Gripper A', [[ cal_btn('Open', 'grip-open-A'), cal_btn('<', 'dec-open-A', 1), sg.T(cal.grip_pos['A']['o'], size=(4, 1), key='openA'), cal_btn('>', 'inc-open-A', 1) ], [ cal_btn('Load', 'grip-load-A'), cal_btn('<', 'dec-load-A', 1), sg.T(cal.grip_pos['A']['l'], size=(4, 1), key='loadA'), cal_btn('>', 'inc-load-A', 1) ], [ cal_btn('Close', 'grip-close-A'), cal_btn('<', 'dec-close-A', 1), sg.T(cal.grip_pos['A']['c'], size=(4, 1), key='closeA'), cal_btn('>', 'inc-close-A', 1) ], [ cal_btn('CCW', 'twist-ccw-A'), cal_btn('<', 'dec-ccw-A', 1), sg.T(cal.twist_pos['A']['ccw'], size=(4, 1), key='ccwA'), cal_btn('>', 'inc-ccw-A', 1) ], [ cal_btn('Center', 'twist-center-A'), cal_btn('<', 'dec-center-A', 1), sg.T(cal.twist_pos['A']['center'], size=(4, 1), key='centerA'), cal_btn('>', 'inc-center-A', 1) ], [ cal_btn('CW', 'twist-cw-A'), cal_btn('<', 'dec-cw-A', 1), sg.T(cal.twist_pos['A']['cw'], size=(4, 1), key='cwA'), cal_btn('>', 'inc-cw-A', 1) ], [ cal_btn('Min', 'twist-min-A'), cal_btn('<', 'dec-min-A', 1), sg.T(cal.servo_range['twistA']['min'], size=(4, 1), key='minA'), cal_btn('>', 'inc-min-A', 1) ], [ cal_btn('Max', 'twist-max-A'), cal_btn('<', 'dec-max-A', 1), sg.T(cal.servo_range['twistA']['max'], size=(4, 1), key='maxA'), cal_btn('>', 'inc-max-A', 1) ]]) ]]) col2 = sg.Col([[ sg.Frame( 'Gripper B', [[ cal_btn('Open', 'grip-open-B'), cal_btn('<', 'dec-open-B', 1), sg.T(cal.grip_pos['B']['o'], size=(4, 1), key='openB'), cal_btn('>', 'inc-open-B', 1) ], [ cal_btn('Load', 'grip-load-B'), cal_btn('<', 'dec-load-B', 1), sg.T(cal.grip_pos['B']['l'], size=(4, 1), key='loadB'), cal_btn('>', 'inc-load-B', 1) ], [ cal_btn('Close', 'grip-close-B'), cal_btn('<', 'dec-close-B', 1), sg.T(cal.grip_pos['B']['c'], size=(4, 1), key='closeB'), cal_btn('>', 'inc-close-B', 1) ], [ cal_btn('CCW', 'twist-ccw-B'), cal_btn('<', 'dec-ccw-B', 1), sg.T(cal.twist_pos['B']['ccw'], size=(4, 1), key='ccwB'), cal_btn('>', 'inc-ccw-B', 1) ], [ cal_btn('Center', 'twist-center-B'), cal_btn('<', 'dec-center-B', 1), sg.T(cal.twist_pos['B']['center'], size=(4, 1), key='centerB'), cal_btn('>', 'inc-center-B', 1) ], [ cal_btn('CW', 'twist-cw-B'), cal_btn('<', 'dec-cw-B', 1), sg.T(cal.twist_pos['B']['cw'], size=(4, 1), key='cwB'), cal_btn('>', 'inc-cw-B', 1) ], [ cal_btn('Min', 'twist-min-B'), cal_btn('<', 'dec-min-B', 1), sg.T(cal.servo_range['twistB']['min'], size=(4, 1), key='minB'), cal_btn('>', 'inc-min-B', 1) ], [ cal_btn('Max', 'twist-max-B'), cal_btn('<', 'dec-max-B', 1), sg.T(cal.servo_range['twistB']['max'], size=(4, 1), key='maxB'), cal_btn('>', 'inc-max-B', 1) ]]) ]]) layout = [[col1, col2], [ sg.Text('', font=('Computerfont', 14), size=(20, 1), key='-STATUS-') ], [cal_btn('Done', '-DONE-')]] return layout
def get_params(): global window my_ip = get_my_ip() sg.theme('LightBrown1') #layout = [[sg.Text("Parametry do wyświetlenia:")]] layout = [] frame_layout = [] for pr in properties: frame_layout.append([ sg.Checkbox(text=pr.name, tooltip=pr.description, default=pr.enabled, key='property-' + pr.name) ]) layout.append([ sg.Frame('Parameter list', frame_layout, title_color='black'), ]) layout.append([ sg.Checkbox(text='export to Excel', default=False, key='save-xlsx', tooltip='Zapis wyników wyszukiwania do pliku Excela.') ], ) layout.append([ sg.Submit("OK", pad=((20, 10), 3)), ]) layout.append([sg.HorizontalSeparator()], ) layout.append([ sg.Checkbox( text='use the following addr range', default=False, key='use-iprange', tooltip= 'Użycie poiższego zakresu adresów zamiast podanego w pliku konfiguracujnym.' ) ]) layout.append([ sg.Text(f'IP addr range ', pad=(1, 3)), sg.InputText(size=(3, 1), default_text=my_ip[0], key='ips1', pad=(1, 3)), sg.InputText(size=(3, 1), default_text=my_ip[1], key='ips2', pad=(1, 3)), sg.InputText(size=(3, 1), default_text=my_ip[2], key='ips3', pad=(1, 3)), sg.InputText(size=(3, 1), default_text='1', key='ips4', pad=(1, 3)), sg.Text(f' - ', pad=(1, 3)), sg.InputText(size=(3, 1), default_text=my_ip[0], key='ipe1', pad=(1, 3)), sg.InputText(size=(3, 1), default_text=my_ip[1], key='ipe2', pad=(1, 3)), sg.InputText(size=(3, 1), default_text=my_ip[2], key='ipe3', pad=(1, 3)), sg.InputText(size=(3, 1), default_text='170', key='ipe4', pad=(1, 3)) ]) layout.append([sg.HorizontalSeparator()], ) layout.append([ sg.ProgressBar(1, orientation='h', size=(20, 20), key='progress'), ], ) layout.append([sg.HorizontalSeparator()], ) layout.append([ sg.Button( "Update database", button_color='red4', tooltip= 'Odpytanie komputerów w zakresie wszystkich właściwosći i aktualizacja bazy danych.\nTrwa długo.\n Można zawęzić zakres adresacji opcją powyżej.' ), ]) #layout.append([sg.ProgressBar(1, orientation='h', size=(20, 20), key='progress')],) window = sg.Window("ipscanner 2.0 beta", layout) while True: event, values = window.read() if event == "OK": # TODO disable controls of the form window.Element('OK').update(disabled=True) break if event == sg.WIN_CLOSED: sys.exit(0) # TODO close running threads if event == "Update database": window.Element("Update database").update(disabled=True) return {'Update database': True} #window.close() prop_list = [ k.replace('property-', '') for k, v in values.items() if v and k.startswith('property-') ] fun_list = {p.func for p in properties if p.name in prop_list} #lista funkcji do wykonania prop_list = ['No', 'IP'] + prop_list + [ 'Time', ] #lista kolumn do wyświetlenia return { 'property_list': prop_list, 'function_list': fun_list, 'use-iprange': values['use-iprange'], 'ips1': values['ips1'], 'ips2': values['ips2'], 'ips3': values['ips3'], 'ips4': values['ips4'], 'ipe1': values['ipe1'], 'ipe2': values['ipe2'], 'ipe3': values['ipe3'], 'ipe4': values['ipe4'], 'save-xlsx': values['save-xlsx'], }
['&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.Checkbox('Checkbox', size=(10,1)), sg.Checkbox('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.Multiline(default_text='This is the default Text should you decide not to type anything', size=(35, 3)), sg.Multiline(default_text='A second multi-line', size=(35, 3))], [sg.InputCombo(('Combobox 1', 'Combobox 2'), size=(20, 1)), sg.Slider(range=(1, 100), orientation='h', size=(34, 20), default_value=85)], [sg.InputOptionMenu(('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.Column(column1, background_color='lightblue')]])], [sg.Text('_' * 80)], [sg.Text('Choose A Folder', size=(35, 1))], [sg.Text('Your Folder', size=(15, 1), auto_size_text=False, justification='right'),
menu_layout = [['Help', ['Update aPai (beta)', 'About']]] window_layout = [ [sg.Menu(menu_layout, )], [sg.Text("Welcome to aPai!", font=("helvetica", 25))], [ sg.Frame(title="Options", layout=[[ sg.Txt("YouTube URL:"), sg.Input(size=(40, 1), tooltip="Paste your youtube URL into this box", font=("helvetica", 12)) ], [ sg.Txt("Format Selection:"), sg.Drop(["Default", "Audio", "Video"], font=("Helvetica", 12)) ], [ sg.Txt("File Destination:"), sg.InputText(font=("helvetica", 12)), sg.FolderBrowse() ]]) ], [sg.Submit(button_text="Download"), sg.Quit()] ] def main(): window = sg.Window("aPai Downloader").Layout(window_layout)
def setup(self): self.mDisplay = md(800, 640, self.timeX) # heigth in rows, witdth in pixels size_progressBar = (50, 32) padding = ((0, 0), 0) colpadding = ((0, 0), 8) col1 = [ [ sg.Button(button_text="<", size=(1, 30), key='mv_left'), self.mDisplay.labelGraphLeft, self.mDisplay.graph, self.mDisplay.labelGraphRight, sg.Button(button_text=">", size=(1, 30), key='mv_right') ], ] self.enableDoubleclickButtons() col2 = [ [ sg.Text("Cur", size=(4, 1), pad=padding), sg.Text(' 0.00', key='_sensor', size=(5, 1), pad=padding), ], [ sg.Text("Dest", size=(4, 1), pad=padding), sg.Text('0.00', key='_output', size=(5, 1), pad=padding) ], [ sg.Button('Show', key='_show'), ], [ sg.Button('Hide', key='_hide'), ], ] col3 = [ [ sg.Text("Set", size=(5, 1), justification='right'), ], [ sg.Slider(range=(0, 100), default_value=0, orientation='v', size=(24, 20), key='temp', pad=padding), ], ] temperature_frame_layout = [ [ sg.Column(col2, pad=colpadding), sg.Column(col3, pad=colpadding), ], ] layout = [ [sg.Menu(self.menu_def, key='menu')], [ sg.Column(col1, pad=colpadding), sg.Frame("Temperature in °C", temperature_frame_layout), ], ] self.window = sg.Window('serial control', layout, auto_size_text=True, default_element_size=(40, 1)) event, self.oldValues = self.window.Read(timeout=1) print(self.oldValues) self.mDisplay.AddDataStream(self.timeX, self.sensValue, (0, 100), 'temperature', color='red', label='T in °C', yAxis='left') self.mDisplay.AddDataStream(self.timeX, self.sensValue2, (0, 50), 'humidity', label='rf in %', yAxis='right') self.startTime = int(round(time.time() * 1000))
def main_window(client) -> sG.Window: """ Construct a main program window :param client: The client object calling for a window layout. :type client: :class:`Client` """ sG.theme(client.options['THEME'].split()[1]) main_menu = [['&File', ['E&xit']], [ '&Server', ['Start Server', 'Kill Server', 'Connect to Server'] ], ['&Options', ['Options Menu']]] keys = [[]] media_player_panel = [ [sG.T('Host Folder:', size=(40, 1))], [ sG.Input(client.options['HOST_FOLDER'], size=(22, 1), pad=((5, 0), 3), enable_events=True, k='HOST_FOLDER'), sG.B('Browse', k='HOST_BROWSE', metadata='folders', pad=((0, 5), 3)) ], [ sG.B('', k='BACK', image_filename='icons/back.png'), sG.B('', k='PAUSE', image_filename='icons/pause.png'), sG.B('', k='PLAY', image_filename='icons/play.png'), sG.B('', k='FORWARD', image_filename='icons/forward.png') ], ] srv_folder = 'Not Connected' if not client.connected else\ client.session.srv_folder server_media = [ [sG.T('Server Folder:', size=(40, 1))], [ sG.Input(srv_folder, size=(22, 1), pad=((5, 0), 3), disabled=True, k='SRV_FOLDER'), sG.B('Browse', k='SRV_BROWSE', pad=((0, 5), 3)) ], [ sG.B('', k='SRV_BACK', image_filename='icons/back.png'), sG.B('', k='SRV_PAUSE', image_filename='icons/pause.png'), sG.B('', k='SRV_PLAY', image_filename='icons/play.png'), sG.B('', k='SRV_FORWARD', image_filename='icons/forward.png') ], ] tab1_layout = keys tab2_layout = media_player_panel tab3_layout = server_media tab_group_layout = [[ sG.Tab('Hot Keys', tab1_layout), sG.Tab('My Media', tab2_layout), sG.Tab('Server Media', tab3_layout) ]] sidebar = [ [sG.vbottom(sG.T('Online Users:'))], [sG.vbottom(sG.Output((37, 3), k='ONLINE_USERS'))], [sG.Output(size=(37, 6), k='CHAT')], [ sG.vbottom( sG.In('', k='INPUT', size=(21, 1), font='ANY 14', pad=((5, 0), 3))), sG.vbottom( sG.Button('Submit', size=(8, 1), k='Submit', pad=((0, 5), (4, 3)), font='ANY 9', use_ttk_buttons=True, bind_return_key=True)) ], [sG.vbottom(sG.TabGroup(tab_group_layout, k='TABS'))], ] media = [[ sG.Image(size=(math.floor(client.res_x * 0.8), math.floor(client.res_y * 0.9)), k='IMAGE', pad=(0, 0), background_color='#000000') ]] layout = [[sG.Menu(main_menu, tearoff=False, pad=(0, 0))], [sG.Frame('', media), sG.Column(layout=sidebar, k='SIDEBAR')], [ sG.StatusBar('', relief=sG.RELIEF_RIDGE, font='ANY 11', size=(40, 1), pad=(5, (5, 5)), k='SERVER_STATUS'), sG.StatusBar('Not connected to any server', relief=sG.RELIEF_RIDGE, font='ANY 11', size=(40, 1), pad=((2, 5), (5, 5)), k='CLIENT_STATUS') ]] win = sG.Window("TeaseAI", layout, margins=(0, 0), location=(0, 0), size=(client.res_x, client.res_y), resizable=True, finalize=True, return_keyboard_events=True) win['IMAGE'].expand(True, True) win['SIDEBAR'].expand(True, True) win['ONLINE_USERS'].expand(True, False, True) win['CHAT'].expand(True, True, True) win['INPUT'].expand(True) win['TABS'].expand(True) return win
citation_frame = sg.Frame( "Citation", layout=[ [sg.Text("If you found cblaster useful, please cite:")], *get_citation("cblaster", "Gilchrist et al. XX (2020)."), [sg.Text("cblaster makes use of the following tools:")], *get_citation( "DIAMOND", "Buchfink, B., Xie, C. & Huson, D. H." " Fast and sensitive protein alignment using DIAMOND." " Nat. Methods 12, 59–60 (2015).", ), *get_citation( "NCBI BLAST API", "Acland, A. et al." " Database resources of the National Center for Biotechnology Information." " Nucleic Acids Res. 42, 7–17 (2014)", ), *get_citation( "HMMER", "Eddy, S. R. " " Accelerated Profile HMM Searches." " PLOS Computational Biology, 7(10) (2011)", ), ], title_color="blue", font="Arial 10 bold", relief="flat", )