def menu_cadastrar(self):
     background = '#20660C'
     text = '#FAE98E'
     button_color=('#F3EE44', '#06470F')
     menu = [['Arquivo', ['Abrir', 'Salvar', 'Propriedades', 'Sair']]]
     layout = [[sgui.Menu(menu)],
               [sgui.Text('Cadastrar time', text_color='#FAE98E', background_color=background, size=(55,2), font=('Candara', 25), justification='center')],
               [sgui.Frame('Informe o nome do time', font=('Candara', 12,'bold'), title_color='#FAE98E', background_color='#06470F',
                     layout=[[sgui.Column(vertical_alignment='b', background_color='#06470F', size=(1000,40), 
                             layout=[[sgui.Text('Nome do time:', size=(50,0), background_color='#06470F', font=('Candara', 12,'bold')), 
                             sgui.InputText(size=(40,1), font=(16), pad=((25,20),0), key=('time_nome'))]])]])],
               [sgui.Frame('Informe as cores do time', font=('Candara', 12,'bold'), title_color='#FAE98E', background_color='#06470F', vertical_alignment='top',
                     layout=[[sgui.Column(vertical_alignment='b', background_color='#06470F', size=(1000,200), 
                             layout=[[sgui.Text('Escolha no botão a cor primária do time:', size=(40,1), background_color='#06470F', font=('Candara', 12,'bold')),
                             sgui.ColorChooserButton('Botão cor primária', font=('Candara', 12, 'bold'), pad=(0,10), 
                             button_color=button_color, size=(10,3), target='cor1', key='cor_p'), 
                             sgui.InputText(size=(40,1), font=(16), pad=(20,20), key=('cor1'), disabled=True)],
                             [sgui.Text('Escolha no botão a cor secundária do time:', size=(40,1), background_color='#06470F', font=('Candara', 12,'bold')),
                             sgui.ColorChooserButton('Botão cor secundária', font=('Candara', 12, 'bold'), pad=(0,10), 
                             button_color=button_color, size=(10,3), target='cor2', key='cor_s'), 
                             sgui.InputText(size=(40,1), font=(16), pad=(20,20), key=('cor2'), disabled=True)]])]])],
               [sgui.Button('Confirmar', size=(15,2), font=('Candara', 12, 'bold'), button_color=button_color, pad=((15,15), (30,30))),
                     sgui.Button('Voltar', size=(15,2), font=('Candara', 12, 'bold'), button_color=button_color, pad=((15,15), (30,30)))]]
     window = sgui.Window('', layout, background_color=background, element_justification='left', finalize=True, keep_on_top = True)
     self.janela = window
     return
예제 #2
0
파일: sgadt.py 프로젝트: gitthious/ADT
def ColorWidget(valtype, val, key, disabled=False, size=(None,None)):
    if val is None: val = ''
    return [
        sg.In(val, size=(8,1), key=key, change_submits=True, do_not_clear=True,
              disabled=disabled),
        sg.ColorChooserButton('' if val else '?', key='__'+key, size=(2,1),
                              target=key, button_color=(val,val) if val else (None,None)),
        ]
예제 #3
0
파일: gui.py 프로젝트: alesplana/rm-mapping
def color_picker(k):
    # global colors, err_win1
    layout = [[
        sg.Text('Color Picker for ' + str(k) + ' cluster/s:', size=(20, 1))
    ]]

    for i in range(k):
        layout.append([
            sg.Text('Cluster ' + str(i) + ': ', size=(8, 1)),
            sg.Input(visible=True,
                     enable_events=True,
                     key='color' + str(i),
                     size=(8, 1),
                     readonly=True),
            sg.Text(' '),
            sg.ColorChooserButton('Pick Color', target='color' + str(i))
        ])

    layout.append([sg.Ok(), sg.Cancel()])

    window = sg.Window('Color Picker',
                       layout,
                       grab_anywhere=False,
                       size=(220, 80 + (k * 20)),
                       return_keyboard_events=False,
                       finalize=True,
                       modal=True)

    while True:
        event, values = window.read()
        print(event, values)
        if event in ('Exit', sg.WIN_CLOSED, 'Cancel'):
            globals()['err_win1'] = 1
            break
        if event == 'Ok':
            globals()['colors'] = list(values.values())
            if globals()['colors'].count('') > 0:
                sg.Popup('Please pick all colors!', title='Error!')
            elif globals()['colors'].count('') == 0:
                print(globals()['colors'])
                globals()['err_win1'] = 0
                break

    window.close()
예제 #4
0
lista2 = []

layout1 = [
    [sg.InputText(default_text="", key='ingreso')],
    [
        sg.Listbox(lista, 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(dic['sustantivo']))],
                        initial_value=0,
                        size=(15, 1),
                        key='cantSus')
            ], [sg.ColorChooserButton('Color Sustantivos')]])
        ]]),
        sg.Frame('Adjetivos', [[
            sg.Column([[
                sg.Spin([i for i in range(len(dic['adjetivo']))],
                        initial_value=0,
                        size=(15, 1),
                        key='cantAdj')
            ], [sg.ColorChooserButton('Color Adjetivos')]])
        ]]),
        sg.Frame('Verbos', [[
            sg.Column([[
                sg.Spin([i for i in range(len(dic['verbo']))],
                        initial_value=0,
                        size=(15, 1),
                        key='cantVerb')
    def menu_alterar(self, time_dict_dados):
        def ordenacao(lista_jogadores):
            g = []
            d = []
            m = []
            a = []
            for jogador in lista_jogadores:
                if jogador[1] == 'Goleiro':
                    g.append(jogador)
                elif jogador[1] == 'Defensor':
                    d.append(jogador)
                elif jogador[1] == 'Meio campista':
                    m.append(jogador)
                else:
                    a.append(jogador)
            g = sorted(g, key=lambda jogador: jogador[0])
            d = sorted(d, key=lambda jogador: jogador[0])
            m = sorted(m, key=lambda jogador: jogador[0])
            a = sorted(a, key=lambda jogador: jogador[0])
            return g + d + m + a

        background = '#20660C'
        text = '#FAE98E'
        button_color=('#F3EE44', '#06470F')
        txt_jogadores = 'Nome' + '\t' * 2 + 'Posição' + '\t' * 2 + 'Gols marcados' + '\n'

        for jogador in ordenacao(time_dict_dados['jogadores']):
            txt_jogadores += jogador[0] + '\t' * 2 + jogador[1] + '\t' * 2 + f'{jogador[2]}' + '\n'

        stats = f"""Técnico\t\t{time_dict_dados['tecnico']}
Partidas jogadas:\t\t{time_dict_dados['vitorias'] + time_dict_dados['empates'] + time_dict_dados['derrotas']}
Vitórias:\t\t{time_dict_dados['vitorias']}
Empates:\t\t{time_dict_dados['empates']}
Derrotas:\t\t{time_dict_dados['derrotas']}
Gols marcados:\t\t{time_dict_dados['gols_m']}
Gols sofridos:\t\t{time_dict_dados['gols_s']}
Jogadores no time:\t\t{len(time_dict_dados['jogadores'])}"""

        header = [[sgui.Column(layout=[[sgui.Text(time_dict_dados['nome'].upper(), text_color=time_dict_dados['cor_s'], background_color=time_dict_dados['cor_p'], 
                        font=('Candara', 25, 'bold'), size=(50,1), justification='center')],
                        [sgui.Button('Confirmar', size=(15,2), font=('Candara', 12, 'bold'), button_color=button_color, pad=((15,15), (30,30))), 
                        sgui.Button('Voltar', size=(15,2), font=('Candara', 12, 'bold'), button_color=button_color, pad=((15,15), (30,30)))]], 
                  element_justification='center', vertical_alignment='c', background_color=background)]]
        nome = [sgui.Frame('Alterar nome do time', font=('Candara', 12,'bold'), title_color='#FAE98E', background_color='#06470F',
                        layout=[[sgui.Column(vertical_alignment='b', background_color='#06470F', size=(1000,40), 
                                layout=[[sgui.Text('Nome:', size=(50,0), background_color='#06470F', font=('Candara', 12,'bold')), 
                                sgui.InputText(default_text=time_dict_dados['nome'], size=(40,1), font=(16), pad=((25,20),0), key=('time_nome'))]])]])]
        cores = [sgui.Frame('Alterar cores do time', font=('Candara', 12,'bold'), title_color='#FAE98E', background_color='#06470F', vertical_alignment='top',
                        layout=[[sgui.Column(vertical_alignment='b', background_color='#06470F', size=(1000,200), 
                                layout=[[sgui.Text('Escolha no botão a cor primária do time:', size=(40,1), background_color='#06470F', font=('Candara', 12,'bold')),
                                sgui.ColorChooserButton('Botão cor primária', font=('Candara', 12, 'bold'), pad=(0,10), 
                                    button_color=button_color, size=(10,3), target='cor1', key='cor_p'), 
                                sgui.InputText(default_text=time_dict_dados['cor_p'], size=(40,1), font=(16), pad=(20,20), key=('cor1'), disabled=True)],
                                [sgui.Text('Escolha no botão a cor secundária do time:', size=(40,1), background_color='#06470F', font=('Candara', 12,'bold')),
                                sgui.ColorChooserButton('Botão cor secundária', font=('Candara', 12, 'bold'), pad=(0,10), 
                                    button_color=button_color, size=(10,3), target='cor2', key='cor_s'), 
                                sgui.InputText(default_text=time_dict_dados['cor_s'], size=(40,1), font=(16), pad=(20,20), key=('cor2'), disabled=True)]])]])]

        lista_jogadores = [sgui.Multiline(txt_jogadores, text_color='white', font=(12) , background_color=background, size=(50,11), disabled=True)]
        estatisticas = [sgui.Multiline(stats, text_color='white', font=(12), background_color=background, size=(30,11), no_scrollbar=True, disabled=True)]
        frame_jogadores = [sgui.Frame('Jogadores', layout = [lista_jogadores], title_color='#FAE98E', background_color='#06470F')]
        frame_estatisticas = [sgui.Frame('Informações', layout = [estatisticas], title_color='#FAE98E', background_color='#06470F')]
        botao_ctecnico = [sgui.Button('Contratar técnico', size=(15,3), font=('Candara', 14,'bold'), border_width=6, focus=True, button_color=('white', '#5161F9'), key='contratar_tecnico')]
        botao_dtecnico = [sgui.Button('Demitir técnico', size=(15,3), font=('Candara', 14,'bold'), border_width=6, focus=True, button_color=('white', '#D351F9'), key='demitir_tecnico')]
        botao_contratar = [sgui.Button('Contratar jogador', size=(15,3), font=('Candara', 14,'bold'), border_width=6, focus=True, button_color=('white', '#01c906'), key='contratar')]
        botao_vender = [sgui.Button('Vender jogador', size=(15,3), font=('Candara', 14,'bold'), border_width=6, focus=True, button_color=('white', '#ff9f11'), key='vender')]
        col_botoes1 = [sgui.Column([botao_contratar, botao_vender], background_color='#06470F')]
        col_botoes2 = [sgui.Column([botao_ctecnico, botao_dtecnico], background_color='#06470F')]
        frame_dados = [sgui.Frame('', layout = [col_botoes2 + frame_estatisticas + frame_jogadores + col_botoes1], background_color='#06470F')]
        botao_excluir = [sgui.Button('Declarar falência', size=(10,2), font=('Candara', 14), border_width=2, focus=True, button_color=('white', 'dark red'), key='excluir')]
        coluna = [sgui.Column(layout = [nome] + [cores] + [frame_dados] + [botao_excluir], element_justification='center', background_color=background, 
                scrollable=True, vertical_scroll_only=True)]
        layout = header +  [coluna]
        window = sgui.Window('Cadastro de time', layout, background_color=background, finalize=True, element_padding=(10,10), element_justification='center')
        self.janela = window
        return
예제 #6
0
     sg.FileBrowse('search',
                   target='path_model',
                   file_types=(
                       ('Imagens JPG', '*.jpg'),
                       ('Imagens PNG', '*.png'),
                   ))
 ],
 [
     sg.Text('Input spreadsheet'),
     sg.Input(key='path_sheet'),
     sg.FileBrowse('search', target='path_sheet')
 ],
 [
     sg.Text('Certificate text'),
     sg.Multiline(key='certificate_text'),
     sg.ColorChooserButton('Text color', key='color')
 ],
 [sg.Text('Font'),
  sg.Combo(font_list, key='font', readonly=True)],
 [
     sg.Text('Font size'),
     sg.Slider(range=(12, 172),
               orientation='h',
               size=(48, 20),
               change_submits=True,
               key='slider_font')
 ],
 [
     sg.Text('Line spacing'),
     sg.Slider(range=(1, 50),
               orientation='h',
예제 #7
0
#texto = sg.PopupGetText('Titulo', 'Ingresá algo')

#sg.Popup('Resultados', 'Ingresaste el siguiente texto: ', texto)
layout = [[sg.Text('Ingresá primer valor'),
           sg.InputText()], [sg.Text('Ingresá segundo valor'),
                             sg.InputText()],
          [sg.Button('Ok'), sg.Button('Cancel')]]

window = sg.Window("Segundo Demo", layout, margins=(200, 150))
while True:
    event, values = window.read()
    if event == "Cancel" or event == sg.WIN_CLOSED:
        break
    print('Datos ingresados: ', values)
window.close()

layout = [[sg.Input('Ingresa algo')],
          [sg.Listbox(values=('Item 1', 'Item 2', 'Item 3'))], [sg.OK()]]
window = sg.Window("Elementos básicos", layout, margins=(200, 150))
event, values = window.read()
sg.Popup(event, values, line_width=200)

#esta no anduvo
sg.ChangeLookAndFeel('DarkAmber')
layout = [[
    sg.Listbox(values=('Item 1', 'Item 2', 'Item 3'),
               background_color='yellow',
               size=(20, 3)), [sg.Input('Last input')],
    [sg.ColorChooserButton(" Elegi color")], [sg.OK()]
]]
예제 #8
0
                      readonly=True)
    ],
    [
        sg.T('● Oficina',
             background_color='#80cbc4',
             font=('Time New Roman', 12)),
        sg.InputCombo(values=list(promedio().keys()),
                      key='oficinas',
                      readonly=True)
    ],
    [
        sg.T('● Elegir colores: ',
             text_color='black',
             font=('Time New Roman', 12),
             background_color='#80cbc4'),
        sg.ColorChooserButton('Sustantivos',
                              button_color=('#000000', '#03A9F4')),
        sg.ColorChooserButton('Adjetivos',
                              button_color=('#000000', '#03A9F4')),
        sg.ColorChooserButton('Verbos', button_color=('#000000', '#03A9F4'))
    ], [sg.Submit('Generar sopa de letras'),
        sg.Cancel('Salir')]
]
window = sg.Window('Seminario de Lenguajes 2019: Python',
                   font=('Arial', 10),
                   background_color='#80cbc4').Layout(layout)

listaSustantivos = []
listaAdjetivos = []
listaVerbos = []
listaPalabrasAceptadas = []
listaPalabras = []
예제 #9
0
sg.theme('Reddit')

layout = [
    [sg.Button('Botão comum')],
    [sg.Cancel()],
    [sg.Ok()],
    [sg.Yes()],
    [sg.No()],
    [sg.Quit()],
    [sg.Exit()],
    [
        sg.CalendarButton('Escolha uma data', target='alvo1'),
        sg.InputText(key='alvo1', size=(20, 1))
    ],
    [
        sg.ColorChooserButton('Escolha uma cor', target='alvo2'),
        sg.Input(key='alvo2', size=(30, 1))
    ],
    [
        sg.FileBrowse('Escolha um arquivo', target='alvo3'),
        sg.Input(key='alvo3', size=(30, 1))
    ],
    [
        sg.FilesBrowse('Escolher arquivos', target='alvo4'),
        sg.Input(key='alvo4', size=(30, 10))
    ],
    [
        sg.FolderBrowse('Escolher uma pasta', target='alvo5'),
        sg.Input(key='alvo5', size=(30, 10))
    ],
]
예제 #10
0
def ciyun_gui(win_main):  # 词云图生成GUI
    import ciyun as cy
    win_main.Hide()
    layout_c = [
        [
            sg.Text('字体颜色范围:', key='font_color_range'),
            sg.Text('最小值', key='min'),
            sg.Spin([i for i in range(1, 360)],
                    initial_value=190,
                    key='min_select'),
            sg.Text('最大值', key='max'),
            sg.Spin([i for i in range(1, 360)],
                    initial_value=250,
                    key='max_select')
        ],
        [
            sg.InputText(
                '关于字体颜色范围取值(H),可以参考https://www.webfx.com/web-design/color-picker/',
                key='font_color_range_p',
                disabled=True)
        ],
        [
            sg.Text('词云图形状:', key='shape'),
            sg.Combo(['方形', '圆形', '图片形状'],
                     key='shape_select',
                     default_value='图片形状',
                     enable_events=True,
                     size=(8, 1))
        ],
    ]
    layout_d = [[
        sg.FileBrowse('打开图片', key='filebrowser', target='image_shape'),
        sg.InputText('', key='image_shape', disabled=True)
    ]]

    layout = [
        [
            sg.Text('字体颜色模式:', key='font_color_type'),
            sg.Combo(['图片颜色', '自定义颜色'],
                     key='font_color_type_select',
                     default_value='自定义颜色',
                     size=(12, 1),
                     enable_events=True)
        ], [sg.Text('即是按照给定图片的颜色给字上色还是自定义字体颜色', key='font_color_type_p')],
        [sg.Column(layout_c, key='is_visible')],
        [sg.Column(layout_d, key='open_image')],
        [
            sg.Text('词云图尺寸:', key='size'),
            sg.Text('宽', key='width'),
            sg.Spin([i for i in range(1, 2001)],
                    initial_value=1000,
                    key='width_select'),
            sg.Text('高', key='highth'),
            sg.Spin([i for i in range(1, 2001)],
                    initial_value=800,
                    key='higth_select')
        ],
        [
            sg.Text('字体:', key='font'),
            sg.Combo(['微软雅黑', '楷体', '宋体', '仿宋', '隶书', 'Times New Roman'],
                     key='font_select',
                     default_value='微软雅黑')
        ],
        [
            sg.Text('背景颜色:', key='back_color'),
            sg.ColorChooserButton('颜色选择', key='back_color_select'),
            sg.Button('透明色点我', key='color_none')
        ],
        [
            sg.Text('分词模式:', key='word_split_type'),
            sg.Combo(['自定义模式', '自动分词模式'],
                     key='word_split_type_select',
                     default_value='自动分词模式',
                     size=(8, 1))
        ],
        [
            sg.Text(
                '注:自定义模式即按照你所给的词组进行绘制,词组之间用空格分隔\n自动分词模式即给定一段话,程序自动进行分词并按照频率进行绘制'
            )
        ],
        [
            sg.Text('最大词数:', key='max_words'),
            sg.Spin([i for i in range(1, 5001)],
                    initial_value=1000,
                    key='max_words_select'),
            sg.Text('词云图上显示的词数量,退格键删除有问题,建议delete键')
        ],
        [
            sg.Text('输\n入\n文\n本'),
            sg.Multiline(size=(30, 10), font=("宋体", 10), key='inputtext'),
            sg.Text('程\n序\n运\n行\n记\n录'),
            sg.Output(size=(30, 10), font=("宋体", 10))
        ],
        [
            sg.FolderBrowse('保存路径',
                            key='folderbrowser',
                            enable_events=True,
                            target='backup'),
            sg.InputText('wordcloud.png',
                         key='savefile_name',
                         enable_events=True,
                         size=(15, 1)),
            sg.InputText('', key='file_path', disabled=True, size=(40, 1))
        ],
        [
            sg.Button('开始生成!', key='generate'),
            sg.Button('保存图片', key='saveas'),
            sg.Button('返回工具箱', key='back'),
            sg.Text('', key='backup', visible=False)
        ]
    ]

    window = sg.Window('词云图生成',
                       layout,
                       font=("宋体", 12),
                       default_element_size=(50, 1))
    while True:
        event, values = window.Read()
        if event in (None, 'back'):
            window.close()
            win_main.UnHide()
            sys.modules.pop('ciyun')  # 释放已导入模块
            break

        if event == 'font_color_type_select':  # 判断字体颜色模式并隐藏相应控件
            if values['font_color_type_select'] == '图片颜色':
                window['shape_select'].Update('图片形状')
                window['is_visible'].Update(visible=False)
            else:
                window['is_visible'].Update(visible=True)

        if event == 'shape_select':  # 判断形状模式并决定是否隐藏打开文件控件
            if values['shape_select'] == '图片形状':
                window['open_image'].Update(visible=True)
            else:
                window['open_image'].Update(visible=False)
        bgcolor = 'none'
        if event == 'color_none':  # 判断是否选择透明背景色
            bgcolor = 'none'
        if event == 'color_none':
            bgcolor = values['back_color_select']

        if event == 'generate':
            color_type = values['font_color_type_select']
            if color_type == '图片颜色':
                n, m = (0, 0)
            else:
                n = min(values['min_select'], values['max_select'])
                m = max(values['min_select'], values['max_select'])
            font = values['font_select']

            w, h = (values['width_select'], values['higth_select'])
            shape = values['shape_select']
            if shape == '图片形状':
                image_path = values['filebrowser']
            else:
                image_path = ''
            segment_mode = values['word_split_type_select']
            text = values['inputtext']
            maxword = values['max_words_select']
            wordcloud = cy.generate(color_type, n, m, font, image_path,
                                    bgcolor, w, h, shape, segment_mode, text,
                                    maxword)
            wordcloud.to_file('cache\image.png')
            image_view('cache\image.png')
            print('词云图生成成功')
        if event in ('folderbrowser', 'savefile_name', 'saveas'):
            window['file_path'].update(values['folderbrowser'] + '/' +
                                       values['savefile_name'])

        if event == 'saveas':
            print(values['file_path'])
            try:
                wordcloud.to_file(values['file_path'])
                print('词云图保存成功')
            except:
                print('你还没有生成相应的词云图')
예제 #11
0
    import PySimpleGUI27 as sg

"""
    Demonstrates the new change_submits parameter for inputtext elements
    It ONLY submits when a button changes the field, not normal user input
    Be careful on persistent forms to not clear the input
"""
layout = [[ sg.Text('Test of reading input field') ],
          [sg.T('This input is normal'), sg.In()],
          [sg.T('This input is normal'), sg.In(), sg.FileBrowse()],
          [sg.T('File Browse submits'), sg.In(change_submits=True,
                                             do_not_clear=True,
                                             key='_in1_'), sg.FileBrowse()],
          [sg.T('Color Chooser submits'), sg.In(change_submits=True,
                                             do_not_clear=True,
                                             key='_in2_'), sg.ColorChooserButton('Color...', target=(sg.ThisRow, -1))],
          [sg.T('Folder Browse submits'), sg.In(change_submits=True,
                                             do_not_clear=True,
                                             key='_in3_'), sg.FolderBrowse()],
          [sg.T('Calendar Chooser submits'), sg.In(change_submits=True,
                                             do_not_clear=True,
                                             key='_in4_'), sg.CalendarButton('Date...', target=(sg.ThisRow, -1))],
          [sg.T('Disabled input submits'), sg.In(change_submits=True,
                                             do_not_clear=True,
                                             disabled=True,
                                             key='_in1_'), sg.FileBrowse()],
          [sg.T('This input clears after submit'),sg.In(change_submits=True,
                                                        key='_in5_'), sg.FileBrowse()],
          [ sg.RButton('Read')]]

window = sg.Window('Demonstration of InputText with change_submits',
def main(filelist=[]):
    """
    pysimplegui menu.
    from pysimplegui cookbook  https://pysimplegui.readthedocs.io/en/latest/cookbook/#recipe-pattern-1a-one-shot-window-the-simplest-pattern
    """
    ## nautilus right-click pass all selected file/foldernames as command line arguments!
    if len(filelist) > 0:
        goodlist = []
        #remove everything that has no extension
        for name in filelist:
            if "." not in name:
                #print("has no dot:", name)
                continue
            # remove everything that has no valid image extension
            extension = name.split(".")[-1]
            if extension.lower() not in IMAGE_EXTENSIONS:
                print("unknown extension in", name)
                continue
            goodlist.append(name)
        filelist = goodlist
        #im = None

    left_part = sg.Column(layout=[
        [sg.Text("meme text :")],
        [
            sg.Multiline(
                key="memetext", size=(50, 5), default_text="hello\nmy\nlove")
        ],
        [
            sg.ColorChooserButton(
                "select text color:", target="hexcolor", key="color"),
            sg.InputText(key="hexcolor", size=(10, 1), default_text="#FF0000")
        ],
        [
            sg.Text("font size:"),
            sg.Slider(range=(10, 1000),
                      default_value=120,
                      key="fontsize",
                      orientation="h",
                      size=(35, 15))
        ],
        [
            sg.Button("select font file", key="font"),
            sg.InputText(
                key="fontfile",
                size=(35, 1),
                default_text=
                "/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf"),
        ],
        [
            sg.Text("output filename:"),
            sg.InputText(key='outputfilename',
                         default_text="merged_image.jpg",
                         size=(50, 1)),
        ],
        [
            sg.Text("add suffix to filename:"),
            sg.Checkbox(text="_YYYY_MM_DD", default=False, key="suffix_date"),
            sg.Checkbox(text="_hh_mm_ss", default=True, key="suffix_time")
        ],
        [
            sg.Button(button_text="Create!", bind_return_key=True, key="ok"),
            sg.Button(button_text="Quit", key="cancel")
        ],
    ])
    right_part = sg.Column(
        layout=[
            [
                sg.Text("image filenames:"),
                sg.Button("add image file:", key="add_imagefile")
            ],
            #                   [sg.Text("zweite Zeile")],
            [
                sg.Listbox(
                    values=[filename.split("/")[-1] for filename in filelist],
                    size=(65, 13),
                    key="imagefilenames",
                    enable_events=True,
                )
            ],
            [
                sg.Text("selected file:"),
                sg.Button("\u2191", key="move_up", disabled=True),
                sg.Button("\u2193", key="move_down", disabled=True),
                sg.Button("remove", key="remove", disabled=True)
            ],
            [sg.Text('layout: merge (concatenate) images:')],
            [
                sg.Radio("horizontal",
                         default=True,
                         group_id="hv",
                         key="horizontal"),
                sg.Radio("vertical",
                         default=False,
                         group_id="hv",
                         key="vertical"),
                sg.Radio("quadratic",
                         default=False,
                         group_id="hv",
                         key="quadratic"),
            ],
        ],
        vertical_alignment="top",
        element_justification="left")
    layout = [
        [left_part, sg.VerticalSeparator(), right_part],
        [
            sg.Text("preview of:"),
            sg.Text(text="<no image created yet>",
                    key="previewtext",
                    size=(100, 1))
        ],
        [
            sg.Image(filename=None,
                     key="preview",
                     size=PREVIEW_SIZE,
                     pad=((WINDOW_SIZE[0] - PREVIEW_SIZE[0]) / 2, 0))
        ],
    ]

    window = sg.Window('Window Title', layout, size=WINDOW_SIZE)
    while True:
        event, values = window.read()
        # file-entry buttons enable/disable?
        if len(values["imagefilenames"]) > 0:
            window["move_up"].update(disabled=False)
            window["move_down"].update(disabled=False)
            window["remove"].update(disabled=False)
        else:
            window["move_up"].update(disabled=True)
            window["move_down"].update(disabled=True)
            window["remove"].update(disabled=True)

        # --------- event handler ----
        if event == sg.WINDOW_CLOSED or event == "cancel":
            break  # end of GUI loop
        elif event in ["move_up", "move_down", "remove"]:
            if values["imagefilenames"] is None or len(
                    values["imagefilenames"]) == 0:
                print("no action because of: empty list or no item selected")
                continue
            name = values["imagefilenames"][0]
            #i = [filename.split("/")[-1] for filename in filelist].index(values["imagefilenames"][0])
            #print("i", i, "name:", name)
            #print("Widget:", window.Element('imagefilenames').Widget.curselection() )
            index = window.Element('imagefilenames').Widget.curselection()[0]
            print("index:", index, "fillist", filelist)
            if event == "move_up":
                if index > 0:
                    filelist.insert(index - 1,
                                    filelist.pop(index))  # moving up
                    index -= 1
                else:
                    print("already at top position")
            elif event == "move_down":
                if index <= len(filelist):
                    filelist.insert(index + 2, filelist[index])
                    filelist.pop(index)
                    index += 1
                else:
                    print("already at last position")
            elif event == "remove":
                filelist.pop(index)
            # update listbox entries, generated from filelist
            window["imagefilenames"].update(
                values=[filename.split("/")[-1] for filename in filelist],
                set_to_index=index)

        elif event == "add_imagefile":
            # let user choose an file to add to filelist
            newfile = sg.PopupGetFile(message="select imagefile(s) to add",
                                      title="choose file",
                                      multiple_files=True)
            if newfile is None:
                continue  # cancel this operation
            # newfile can contain a single filename or a string of multiple filenames seperated by semicolon (;)
            if ";" in newfile:
                for one_new_file_name in newfile.split(";"):
                    filelist.append(one_new_file_name)
            else:
                filelist.append(newfile)
            window["imagefilenames"].update(
                values=[filename.split("/")[-1] for filename in filelist])
        elif event == "font":
            window["fontfile"].update(
                sg.popup_get_file(
                    message="select true type font:",
                    title="choose folder and file",
                    default_path=
                    "/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf",
                    initial_folder="/usr/share/fonts/truetype/freefont/",
                ))
        elif event == "ok":  # create image
            # quadratic needs at minimum 4 images:
            if values["quadratic"] and len(filelist) < 4:
                sg.PopupError(
                    "I need a minimum of 4 images to arrange quadratic")
                continue
            output_name = ""
            timestampstring = generate_time_stamp(
                values["suffix_date"], values["suffix_time"])  # can be ""
            if values["outputfilename"] is None or len(
                    values["outputfilename"]) == 0:
                if timestampstring == "":
                    sg.PopupError(
                        "please enter an outputfilename or enable date/time suffix"
                    )
                    continue
                output_name = timestampstring + ".jpg"
            elif "." not in values["outputfilename"]:
                # check if ouputfilename is has an extension
                output_name = values[
                    "outputfilename"] + timestampstring + ".jpg"
            else:
                left_part = "".join(values["outputfilename"].split(".")
                                    [:-1])  # the part before the last dot
                right_part = values["outputfilename"].split(".")[
                    -1]  # the part after the last dot
                output_name = left_part + timestampstring + "." + right_part

            width, height = create(filenames=filelist,
                                   horizontal=values["horizontal"],
                                   vertical=values["vertical"],
                                   memetext=values["memetext"],
                                   fontsize=int(values["fontsize"]),
                                   fontfile=values["fontfile"],
                                   outputfilename=output_name,
                                   fontcolor=values["hexcolor"],
                                   make_tiles=values["quadratic"])
            sg.PopupOK(
                f"images created:\npreview.png: {PREVIEW_SIZE[0]}x{PREVIEW_SIZE[1]} pixel\n{output_name}: {width} x {height} pixel"
            )
            window["preview"].update(filename="preview.png", size=(800, 600))
            window["previewtext"].update(
                value=f"{output_name} dimension: {width} x {height} pixel")

    window.close()
        def diseño_del_juego(botones_por_defecto, colores, orientacion,
                             mayusculas, tipografias, tipografia):
            '''En la columna derecha, permite la visualización, y modificación de
            los colores de cada tipo de palabra, la orientación de las palabras,
            si estarán en mayúsculas o minúsculas, y la tipografía del reporte'''
            colores_frame = [
                [
                    sg.ColorChooserButton("Sustantivos",
                                          size=(12, 1),
                                          key='color_sustantivos',
                                          button_color=('white', colores[0])),
                ],
                [
                    sg.ColorChooserButton("Adjetivos",
                                          size=(12, 1),
                                          key='color_adjetivos',
                                          button_color=('white', colores[1])),
                ],
                [
                    sg.ColorChooserButton("Verbos",
                                          size=(12, 1),
                                          key='color_verbos',
                                          button_color=('white', colores[2]))
                ],
            ]

            orientacion_frame = [[
                sg.Radio("Horizontal",
                         "orientacion",
                         default=orientacion,
                         key='orientacion_horizontal'),
            ],
                                 [
                                     sg.Radio("Vertical",
                                              "orientacion",
                                              default=not orientacion,
                                              key='orientacion_vertical')
                                 ]]

            maymin_frame = [[
                sg.Radio("Mayusculas",
                         "maymin",
                         default=mayusculas,
                         key='mayusculas'),
            ],
                            [
                                sg.Radio("Minusculas",
                                         "maymin",
                                         default=not mayusculas,
                                         key='minusculas')
                            ]]

            tipografia_frame = [[
                sg.Combo(values=tipografias,
                         default_value=tipografia,
                         key='tipografia')
            ]]

            orientacion_maymin_column = [
                [
                    sg.Frame("Seleccionar orientación ", orientacion_frame),
                ],
                [sg.Frame("Mayusculas/Minusculas", maymin_frame)],
            ]

            color_tipografia_frame = [
                [sg.Frame('Seleccionar tipografia', tipografia_frame)],
                [
                    sg.Frame("Seleccionar colores", colores_frame),
                ],
            ]

            diseño_del_juego = [[
                sg.Column(orientacion_maymin_column),
                sg.Column(color_tipografia_frame)
            ], botones_por_defecto]

            return diseño_del_juego
예제 #14
0
def configuracion():
    """Interfaz de la pantalla de configuración, guarda las nuevas configuraciones, en caso de que no se haya modificado
        algún item, se deja el valor guardado anteriormente."""

    with open(os.path.join('configuracion', 'archivos', 'configuracion.json'), 'r') as ar_config:
        dato = json.load(ar_config)

    palabras_max = tamanio_ventana()
    fonts = fuentes()
    text0 = Sg.InputText('')
    text1 = Sg.InputText('')

    Sg.SetOptions(element_padding=(10, 15), auto_size_buttons=True, auto_size_text=True, )

    layout = [[Sg.Text('Agregar Palabra'), text0, Sg.Button('Agregar')],
              [Sg.Text('Eliminar Palabra'), text1, Sg.Button('Eliminar')],
              [Sg.Frame(layout=[[Sg.Text('Colores con los que se representarán las palabras a encontrar en la Sopa de '
                                         'Letras')], [Sg.ColorChooserButton('Adjetivos', pad=(50, 0), key='ColorAdj'),
                                                      Sg.ColorChooserButton('Sustantivos', pad=(50, 0), key='ColorSus'),
                                                      Sg.ColorChooserButton('Verbos', pad=(50, 0), key='ColorVer')],
                                [Sg.Text('Ayuda'), Sg.Radio('Si', 'ayuda', key='ayudaS',
                                                            default=dato['tipo_Ayuda'] != "Palabras por tipo"),
                                 Sg.Radio('No', 'ayuda', key='ayudaN',
                                          default=dato['tipo_Ayuda'] == "Palabras por tipo"),
                                 Sg.Text('Tipo de Ayuda'), Sg.InputCombo(('', 'Definiciones', 'Lista de Palabras'),
                                                                         key='TipoAyuda')],
                                [Sg.Text('Orientación de las palabras'),
                                 Sg.Radio('Horizontal', 'pos', key='OHor', default=dato['orientacion'] == 'H'),
                                 Sg.Radio('Vertical', 'pos', key='OVer', default=dato['orientacion'] == 'V')],
                                [Sg.Text('Cantidad de'), Sg.Text('Adjetivos'),
                                 Sg.InputText(default_text=str(dato["cantidad_Adj_Sus_Ver"][0]), size=(5, 4),
                                              key='CantAdj'), Sg.Text('Sustantivos'),
                                 Sg.InputText(default_text=str(dato["cantidad_Adj_Sus_Ver"][1]), size=(5, 4),
                                              key='CantSus'), Sg.Text('Verbos'),
                                 Sg.InputText(default_text=str(dato["cantidad_Adj_Sus_Ver"][2]), size=(5, 4),
                                              key='CantVer')],
                                [Sg.Text('    Máximo ' + str(palabras_max) + ' palabras en total', pad=(0, 0),
                                         font=(any, 8, 'bold', 'italic'))],
                                [Sg.Text('Tipografía del reporte'), Sg.InputCombo(fonts, size=(30, 20), key='font')],
                                [Sg.Text('Oficina'), Sg.InputCombo(cargar_oficinas(), key='Oficina')],
                                [Sg.Text('Letras'), Sg.Radio('MAYUSCULA', 'M/m', key='M', default='M' == dato['M/m']),
                                 Sg.Radio('minúscula', 'M/m', key='m', default='m' == dato['M/m'])]],
                        title='Configuración', title_location='n', pad=(30, 10))],
              [Sg.Button('', pad=(200, 0), border_width=0), Sg.Button('Aceptar'), Sg.CButton('Cancelar')]]

    ventana_config = Sg.Window('Configuracion', size=(650, 650)).Layout(layout)

    seguir = True

    while seguir:
        event, values = ventana_config.Read()
        if event is None or event == 'Quit':
            break
        try:
            if event == 'Agregar':
                agregar_palabras.agregar_palabra(values[0])
                text0.Update('')
                raise
            if event == 'Eliminar':
                eliminar_palabra.eliminar(values[1])
                text1.Update('')
                raise
            if event == 'Aceptar':
                # Verifico que se hayan seleccionado colores para representar los distintos tipos de palabras y
                # si no quedan los seleccionados por defecto.
                if values['ColorAdj'] != '' and values['ColorAdj'] != 'None':
                    dato['colores'][0] = values['ColorAdj']
                if values['ColorSus'] != '' and values['ColorSus'] != 'None':
                    try:
                        if values['ColorAdj'] != values['ColorSus']:
                            dato['colores'][1] = values['ColorSus']
                        else:
                            raise
                    except:
                        Sg.PopupError('El color seleccionado ya ha sido seleccionado para otro tipo de palabra \n Puede'
                                      ' elegir otro color o dejar el color anterior')
                        raise
                if values['ColorVer'] != '' and values['ColorVer'] != 'None':
                    try:
                        if values['ColorAdj'] != values['ColorVer'] and values['ColorSus'] != values['ColorVer']:
                            dato['colores'][2] = values['ColorVer']
                        else:
                            raise
                    except:
                        Sg.PopupError('El color seleccionado ya ha sido seleccionado para otro tipo de palabra \n Puede'
                                      ' elegir otro color o dejar el color anterior')
                        raise

                # Si quiere ayuda y se seleccionó un tipo de ayuda se modifica, si no por defecto habrá ayuda y será el
                # listado de palabras a buscar
                if values['ayudaS']:
                    if values['TipoAyuda'] != '':
                        dato['tipo_Ayuda'] = values['TipoAyuda']
                    else:
                        dato['tipo_Ayuda'] = 'Lista de Palabras'
                elif values['ayudaN']:
                    dato['tipo_Ayuda'] = 'Palabras por tipo'

                # Orientación de las palabras
                if values['OHor']:
                    dato['orientacion'] = 'H'
                elif values['OVer']:
                    dato['orientacion'] = 'V'

                # Cantidad de Adjetivos, Verbos y Sustantivos a usar en la Sopa de Letras
                pt = 0
                if values['CantAdj'] != '':
                    pt += int(values['CantAdj'])
                else:
                    pt += int(dato['cantidad_Adj_Sus_Ver'][0])
                if values['CantSus'] != '':
                    pt += int(values['CantSus'])
                else:
                    pt += int(dato['cantidad_Adj_Sus_Ver'][1])
                if values['CantVer'] != '':
                    pt += int(values['CantVer'])
                else:
                    pt += int(dato['cantidad_Adj_Sus_Ver'][2])
                try:
                    if 0 < pt <= int(palabras_max):
                        if values['CantAdj'] != '':
                            dato['cantidad_Adj_Sus_Ver'][0] = int(values['CantAdj'])
                        if values['CantSus'] != '':
                            dato['cantidad_Adj_Sus_Ver'][1] = int(values['CantSus'])
                        if values['CantVer'] != '':
                            dato['cantidad_Adj_Sus_Ver'][2] = int(values['CantVer'])
                    else:
                        if pt == 0:
                            Sg.PopupError('Debe haber mínimo una palabra para hacer la sopa de letras \n Por favor '
                                          'cambie algún valor a mayor que 0')
                        elif pt > palabras_max:
                            Sg.PopupError('Demasiadas palabras intente nuevamente con menos cantidad', keep_on_top=True)
                        raise
                except:
                    raise

                # Si las palabras van a ir en Mayúscula o Minúscula
                if values['M']:
                    dato['M/m'] = 'M'
                elif values['m']:
                    dato['M/m'] = 'm'

                # tipografía del reporte
                if values['font'] != '@MS Gothic':
                    dato['tipografia'] = values['font']

                # estilo(Change_Look_And_Feel)
                dato['estilo'] = cambiar_aspecto(values['Oficina'])
        except:
            seguir = True
        else:
            with open(os.path.join('configuracion', 'archivos', 'configuracion.json'), 'w') as ar_config:
                json.dump(dato, ar_config)
            break

    ventana_config.Close()
    return True
예제 #15
0
 [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')]])
     ]]),
     sg.Frame('Verbos', [[
         sg.Column([[
             sg.Spin([j for j in dic if j.getClase == 'verbo'],
예제 #16
0
class Life_World(World):

    WHITE = '#ffffff'
    BLACK = '#000000'

    fg_color_chooser = sg.ColorChooserButton('foreground',
                                             button_color=(WHITE, WHITE),
                                             size=(10, 1))
    bg_color_chooser = sg.ColorChooserButton('background',
                                             button_color=(BLACK, BLACK),
                                             size=(10, 1))

    SELECT_FOREGROUND_TEXT = 'Select foreground color  '
    SELECT_BACKGROUND_TEXT = 'Select background color'

    def get_color_and_update_button(self,
                                    button,
                                    default_color_string,
                                    values=None):
        if not values:
            values = self.values
        key = button.get_text()
        color_string = values.get(key, '')
        if color_string in {'None', '', None}:
            color_string = default_color_string
        button.update(button_color=(color_string, color_string))
        color = Color(color_string)
        return color

    def get_colors(self):
        Life_Patch.bg_color = self.get_color_and_update_button(
            self.bg_color_chooser,
            default_color_string=rgb_to_hex(Life_Patch.bg_color))
        Life_Patch.fg_color = self.get_color_and_update_button(
            self.fg_color_chooser,
            default_color_string=rgb_to_hex(Life_Patch.fg_color))

    def handle_event_and_values(self):
        """
        This method handles the color chooser. It does it in a round-about way because
        the color chooser can't generate events. Consequently, the user is asked to click
        a button next to the color-chooser. In processing that button-click, we ".click()"
        the color-chooser button. The user selects a color, which we retrieve by reading
        the window. We then color the color-chooser button with that color.
        """
        foreground = self.event == Life_World.SELECT_FOREGROUND_TEXT
        # There are two color-choosers: foreground and background. Determine and select the
        # desired color chooser based on the label on the button the user clicked.
        color_chooser_button = Life_World.fg_color_chooser if foreground else Life_World.bg_color_chooser
        # Run it
        color_chooser_button.click()

        # Create a default color_string in case the user had cancelled color selection.
        # The default color string is the string of the current color.
        default_color_string = rgb_to_hex(
            Life_Patch.fg_color if foreground else Life_Patch.bg_color)
        # Retrieve the color choice by reading the window.
        (_event, values) = gui.WINDOW.read(timeout=10)

        color = self.get_color_and_update_button(color_chooser_button,
                                                 default_color_string, values)

        # Set the color to the new choice
        if foreground:
            Life_Patch.fg_color = color
        else:
            Life_Patch.bg_color = color

        # Update the patches.
        for patch in self.patches:
            patch.set_alive_or_dead(patch.is_alive)

    def mouse_click(self, xy: Tuple[int, int]):
        """ Toggle clicked patch's aliveness. """
        patch = self.pixel_tuple_to_patch(xy)
        patch.set_alive_or_dead(not patch.is_alive)

    def setup(self):
        self.get_colors()
        density = self.get_gui_value('density')
        for patch in self.patches:
            is_alive = randint(0, 100) < density
            patch.set_alive_or_dead(is_alive)

    def step(self):
        # Count the live neighbors in the current state.
        for patch in self.patches:
            patch.count_live_neighbors()

        # Determine and set whether each patch is_alive in the next state.
        self.get_colors()
        for patch in self.patches:
            is_alive = patch.live_neighbors == 3 or patch.is_alive and patch.live_neighbors == 2
            patch.set_alive_or_dead(is_alive)
예제 #17
0
import PySimpleGUI as sg

layout = [[sg.CalendarButton('Calendrio')],
          [sg.ColorChooserButton('Cor Escolhe')],
          [sg.InputText(),
           sg.FileBrowse()], [sg.InputText(), sg.FilesBrowse()],
          [sg.InputText(), sg.FileSaveAs()],
          [sg.InputText(), sg.FolderBrowse()]]

sg.Window('Choose', layout).read()
예제 #18
0
pidePalabra = [
                [sg.T('Ingrese la palabra:'), sg.InputText('', key = 'palabraIngresada')],
                [sg.Button('Ok', key = 'ok'), sg.Button('Cancelar', key = 'cancelar')]
            ]

column1 = [
            [sg.T('Sustantivos', font = ('Arial', 12), key = 'tituloSustantivos')],
            [sg.Button('Agregar sustantivo', key = 'agregarSustantivo')],
            [sg.Listbox(values = datos['sustantivos'], size=(15, 6), key = 'listboxSustantivos'), sg.T('Cantidad: '),
            sg.Spin(values = listaNula + list(map(lambda x: x + 1, (range(len(datos['sustantivos']))))), key = 'spinSustantivos', initial_value = datos['cantSustantivos'])],
            [sg.Button('Eliminar sustantivo', key = 'eliminarSustantivo')],
            [sg.T('-----------------------')],
            [sg.B('Cargar cantidad', key = 'cantSustantivos')],
            [sg.T('Cargado!', visible = False, key = 'cargadoSustantivos')],
            [sg.T('-----------------------')],
            [sg.ColorChooserButton('Seleccionar color', key = 'colorSustantivos'), sg.B('Cargar color', key = 'cargarColorSustantivos')]
        ]

column2 = [
            [sg.T('Adjetivos', font = ('Arial', 12), key = 'tituloAdjetivos')],
            [sg.Button('Agregar adjetivos', key = 'agregarAdjetivo')],
            [sg.Listbox(values = datos['adjetivos'], size=(15, 6), key = 'listboxAdjetivos'), sg.T('Cantidad: '),
            sg.Spin(values = listaNula + list(map(lambda x: x + 1, (range(len(datos['adjetivos']))))), key = 'spinAdjetivos', initial_value = datos['cantAdjetivos'])],
            [sg.Button('Eliminar adjetivos', key = 'eliminarAdjetivo')],
            [sg.T('-----------------------')],
            [sg.B('Cargar cantidad', key = 'cantAdjetivos')],
            [sg.T('Cargado!', visible = False, key = 'cargadoAdjetivos')],
            [sg.T('-----------------------')],
            [sg.ColorChooserButton('Seleccionar color', key = 'colorAdjetivos'), sg.B('Cargar color', key = 'cargarColorAdjetivos')]

        ]
def main(cantVB, cantNN, cantJJ):
    sg.SetOptions(element_padding=(10, 10),
                  background_color='#C0C0C0',
                  element_background_color='#C0C0C0')

    file_palabras = 'archivos/palabras.csv'

    f_colores = [[
        sg.ColorChooserButton('Verbos',
                              key='__cVB__',
                              size=(10, 3),
                              button_color=None),
        sg.ColorChooserButton('Sustantivos',
                              key='__cNN__',
                              size=(10, 3),
                              button_color=None),
        sg.ColorChooserButton('Adjetivos',
                              key='__cJJ__',
                              size=(10, 3),
                              button_color=None)
    ]]

    f_orientacion = [[
        sg.Combo(['horizontal', 'vertical'],
                 key='__ORIENTACION__',
                 readonly=True)
    ]]

    tipografias = [
        'Helvetica', 'Times', 'Arial', 'Georgia', 'Verdana', 'Tahoma',
        'Times New Roman', 'Trebuchet', 'Courier', 'Comic', 'Fixedsys'
    ]
    f_tipografia = [[
        sg.T('Titulo'),
        sg.Combo(tipografias, key='TIPOGRAFIA_TIT', readonly=True)
    ],
                    [
                        sg.T('Texto'),
                        sg.Combo(tipografias,
                                 key='TIPOGRAFIA_TEX',
                                 readonly=True)
                    ]]

    f_grafia = [[
        sg.Combo(['minusculas', 'MAYUSCULAS'],
                 key='__CAPITALIZACION__',
                 readonly=True,
                 size=(20, 3))
    ]]

    layout = [[
        sg.Frame('Seleccionar color para los tipos de palabra', f_colores),
        sg.Frame('Elegir orientacion para jugar', f_orientacion)
    ],
              [
                  sg.Frame('Seleccione la tipografia a usar en el reporte',
                           f_tipografia),
                  sg.Frame('Seleccion de Grafía a usar',
                           f_grafia,
                           size=(100, 3))
              ], [sg.Checkbox('Mostrar Ayuda', key='ayuda')],
              [sg.Submit('Empezar a Jugar'),
               sg.Exit('Salir')]]

    window = sg.Window('Menu de Juego').Layout(layout)
    event, buttons = window.Read()

    if event == 'Salir':
        exit()
    elif event == 'Empezar a Jugar':
        dic = listadoPalabras(file_palabras, cantVB, cantNN, cantJJ)

        window.Close()
        sopaDeLetras.main(dic, buttons)
예제 #20
0
def generar_layout():
    '''
        Genera layout menu principal
    '''
    cantidad = devolver_cantidades_tipos()
    columna1 = [[sg.Text('Verbos', background_color='#dbdbdb')],
                [
                    sg.T('cantidad', background_color='#dbdbdb'),
                    sg.InputCombo([x for x in range(cantidad[0])],
                                  key='cantidad_verbo',
                                  size=(20, 20),
                                  change_submits=True,
                                  enable_events=True)
                ],
                [
                    sg.T('Color para representarlo ',
                         background_color='#dbdbdb'),
                    sg.ColorChooserButton('Elegir color', key='color_Verbos')
                ]]
    columna2 = [[sg.T('Sustantivos', background_color='#dbdbdb')],
                [
                    sg.T('cantidad', background_color='#dbdbdb'),
                    sg.InputCombo([x for x in range(cantidad[1])],
                                  key='cantidad_sustantivo',
                                  size=(20, 20),
                                  enable_events=True)
                ],
                [
                    sg.T('Color para representarlo ',
                         background_color='#dbdbdb'),
                    sg.ColorChooserButton('Elegir color',
                                          key='color_Sustantivos')
                ]]
    columna3 = [[sg.T('Adjetivos', background_color='#dbdbdb')],
                [
                    sg.T('cantidad', background_color='#dbdbdb'),
                    sg.InputCombo([x for x in range(cantidad[2])],
                                  key='cantidad_adjetivo',
                                  size=(20, 20),
                                  enable_events=True)
                ],
                [
                    sg.T('Color para representarlo ',
                         background_color='#dbdbdb'),
                    sg.ColorChooserButton('Elegir color',
                                          key='color_Adjetivos')
                ]]
    orientacion = ['Horizontal', 'vertical']
    ayuda = ['Ninguna', 'definiciones', 'Lista de palabras']
    letra = ['Mayuscula', 'Minuscula']
    layout = [[sg.T('Menu de opciones')],
              [
                  sg.Column(columna1, background_color='#dbdbdb'),
                  sg.Column(columna2,
                            background_color='#dbdbdb',
                            key='columna2'),
                  sg.Column(columna3, background_color='#dbdbdb')
              ],
              [
                  sg.T('    Seleccione la orientacion'),
                  sg.InputCombo(orientacion, key='orientacion', size=(20, 20)),
                  sg.T('Seleccione el tipo de ayuda'),
                  sg.InputCombo(ayuda, key='ayuda')
              ],
              [
                  sg.T('    seleccione como desea que aparezcan las letras'),
                  sg.InputCombo(letra, key='letra')
              ], [sg.Submit('Aceptar'),
                  sg.Submit('Cancelar')]]
    return layout
예제 #21
0
config2 = [
    [sg.T(" " * 30)],
    [
        sg.T(" " * 50),
        sg.T("GUIA DE CONFIGURACION", font="Trebuchet 9"),
        sg.RButton("",
                   image_filename=SIGNO,
                   button_color=sg.TRANSPARENT_BUTTON,
                   size=(2, 2),
                   auto_size_button=True,
                   key='Guia')
    ],
    [sg.T(" " * 30)],
    [
        sg.T(" " * 35),
        sg.ColorChooserButton("COLOR", key="color_sustantivos"),
        sg.Text(" " * 4, background_color='white', key="cuadrado_sustantivos"),
        sg.Text("SUSTANTIVOS    -", font="Trebuchet"),
        sg.Text("CANT:", font="Trebuchet"),
        sg.InputCombo([0, 1, 2, 3, 4, 5, 6],
                      key="cant_sustantivos",
                      font="Trebuchet 11",
                      readonly=True)
    ],
    [
        sg.T(" " * 35),
        sg.ColorChooserButton("COLOR", key="color_verbos"),
        sg.Text(" " * 4, key="cuadrado_verbos", background_color="white"),
        sg.Text("VERBOS    -", font="Trebuchet"),
        sg.Text("CANT:", font="Trebuchet"),
        sg.InputCombo([0, 1, 2, 3, 4, 5, 6],
예제 #22
0
                   [
                       sg.Output(size=(40, 20), key='-Output-'),
                       sg.Graph(canvas_size=(500, 300),
                                graph_top_right=(0, 0),
                                graph_bottom_left=(500, 300),
                                key="graph",
                                change_submits=True,
                                background_color='white',
                                drag_submits=True)
                   ],
                   [
                       sg.InputText(key='-TextBox-', size=(43, 1)),
                       sg.Radio('ペン', 1, key='-Pen-', default=True),
                       sg.Radio('消しゴム', 1, key='-Erase-'),
                       sg.InputText('#000000', key='-Color-'),
                       sg.ColorChooserButton('カラー選択', target='-Color-')
                   ],
                   [
                       sg.Submit(button_text='送信'),
                       sg.Text('名前'),
                       sg.InputText("Anonymous", key='-Name-')
                   ]]


def create_client():
    skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    skt.connect(('localhost', 50007))
    thread = threading.Thread(target=handler, args=(skt, ), daemon=True)
    thread.start()
    skt.sendall(b'connected')
    return skt
예제 #23
0
class OnOffWorld(World):

    WHITE = '#ffffff'
    BLACK = '#000000'

    on_color_chooser = sg.ColorChooserButton('on',
                                             button_color=(WHITE, WHITE),
                                             size=(10, 1))
    off_color_chooser = sg.ColorChooserButton('off',
                                              button_color=(BLACK, BLACK),
                                              size=(10, 1))

    SELECT_ON_TEXT = 'Select "on" color  '
    SELECT_OFF_TEXT = 'Select "off" color'

    @staticmethod
    def get_color_and_update_button(button, default_color_string):
        key = button.get_text()
        color_string = SimEngine.get_gui_value(key)
        if color_string in {'None', '', None}:
            color_string = default_color_string
        button.update(button_color=(color_string, color_string))
        color = Color(color_string)
        return color

    def get_colors(self):
        OnOffPatch.off_color = self.get_color_and_update_button(
            self.off_color_chooser,
            default_color_string=rgb_to_hex(OnOffPatch.off_color))
        OnOffPatch.on_color = self.get_color_and_update_button(
            self.on_color_chooser,
            default_color_string=rgb_to_hex(OnOffPatch.on_color))

    def handle_event_and_values(self):
        """
        This method handles the color chooser. It does it in a round-about way because
        the color chooser can't generate events. Consequently, the user is asked to click
        a button next to the color-chooser. In processing that button-click, we ".click()"
        the color-chooser button. The user selects a color, which we retrieve by reading
        the window. We then color the color-chooser button with that color.
        """
        event = SimEngine.get_gui_event()
        if event not in {
                OnOffWorld.SELECT_ON_TEXT, OnOffWorld.SELECT_OFF_TEXT
        }:
            return

        selecting_on = event == OnOffWorld.SELECT_ON_TEXT
        # There are two color-choosers: selecting_on and selecting_off. Determine and select the
        # desired color chooser based on the label on the button the user clicked.
        color_chooser_button = OnOffWorld.on_color_chooser if selecting_on else OnOffWorld.off_color_chooser
        # Run it
        color_chooser_button.click()

        # Create a default color_string in case the user had cancelled color selection.
        # The default color string is the string of the current color.
        default_color_string = rgb_to_hex(
            OnOffPatch.on_color if selecting_on else OnOffPatch.off_color)
        # Retrieve the color choice by reading the window.
        (_event, SimEngine.values) = gui.WINDOW.read(timeout=10)

        color = self.get_color_and_update_button(color_chooser_button,
                                                 default_color_string)

        # Set the color to the new choice
        if selecting_on:
            OnOffPatch.on_color = color
        else:
            OnOffPatch.off_color = color

        # Update the patches.
        for patch in self.patches:
            patch.set_on_off(patch.is_on)

    def mouse_click(self, xy: Tuple[int, int]):
        """ Toggle clicked patch's aliveness. """
        patch = self.pixel_tuple_to_patch(xy)
        patch.set_on_off(not patch.is_on)

    def setup(self):
        self.get_colors()
        for patch in self.patches:
            is_on = randint(0, 100) < 10
            patch.set_on_off(is_on)

    def step(self):
        self.get_colors()

        # Run this only if we're running this on its own.
        if isinstance(self, OnOffWorld):
            for patch in self.patches:
                is_on = patch.is_on and randint(
                    0, 100) < 90 or not patch.is_on and randint(0, 100) < 1
                patch.set_on_off(is_on)
예제 #24
0
def configPalabras(dic_palabras):
    '''Modulo encargado de procesar toda la informacion relacionada a la configuracion del juego'''

    #------------------------------------ Funciones ------------------------------------
    def borrar_valor(valor, dic_palabras):
        '''borra un valor del diccionario de palabras'''

        valido = ''
        if valor in dic_palabras['__verbos__']:
            dic_palabras['__verbos__'].remove(valor)
            valido = '__verbos__'
        elif valor in dic_palabras['__adjetivos__']:
            dic_palabras['__adjetivos__'].remove(valor)
            valido = '__adjetivos__'
        elif valor in dic_palabras['__sustantivos__']:
            dic_palabras['__sustantivos__'].remove(valor)
            valido = '__sustantivos__'

        return valido

    #---------------------------- Procesamiento de temperaturas -------------------------------
    dirJsonOficinas = os.path.abspath(
        os.path.join(os.path.join(os.pardir, 'Raspberry'),
                     'datos-oficinas.json'))  #archivo en carpeta padre
    oficinas_temp = {}
    try:
        oficinas_registroAmbiental = {}
        jsonOficinas = open(dirJsonOficinas)
        oficinas_registroAmbiental = json.load(
            jsonOficinas)  #levantar json registro
        listaTemperaturas = []
        for oficina in oficinas_registroAmbiental:
            for dic_registro in oficinas_registroAmbiental[oficina]:
                listaTemperaturas.append(int(dic_registro['Temperatura']))
            oficinas_temp[oficina] = statistics.mean(
                listaTemperaturas
            )  #calcular promedio de tempemperatura de una oficina
    except:  #En caso de que no exista, valor predeterminado = 20
        oficinas_temp['Vacio'] = 20
        sg.PopupNoButtons('Registro Ambiental no encontrado o no es operable.',
                          title='Advertencia',
                          auto_close=True,
                          auto_close_duration=4
                          )  #aviso: el registro no se encontro o esta vacio

    # ------------------------------------ Layout & Design ------------------------------------

    sg.ChangeLookAndFeel('Purple')

    columna_verbos = [[
        sg.Frame('Verbos', [[
            sg.Listbox(
                dic_palabras['__verbos__'], key='__verbos__', size=(25, 5))
        ],
                            [
                                sg.Text('Cantidad:'),
                                sg.Spin([i for i in range(0, 6)],
                                        initial_value=0,
                                        size=(3, 3),
                                        key='__cantverbos__'),
                                sg.ColorChooserButton(
                                    'Elegir color',
                                    key='__verbColorChooser__',
                                )
                            ]],
                 relief=sg.RELIEF_RIDGE)
    ]]
    columna_adj = [[
        sg.Frame('Adjetivos',
                 [[
                     sg.Listbox(dic_palabras['__adjetivos__'],
                                key='__adjetivos__',
                                size=(25, 5))
                 ],
                  [
                      sg.Text('Cantidad:'),
                      sg.Spin([i for i in range(0, 6)],
                              initial_value=0,
                              size=(3, 3),
                              key='__cantadjetivos__'),
                      sg.ColorChooserButton('Elegir color',
                                            key='__adjColorChooser__')
                  ]],
                 relief=sg.RELIEF_RIDGE)
    ]]
    columna_sust = [[
        sg.Frame('Sustantivos', [[
            sg.Listbox(dic_palabras['__sustantivos__'],
                       key='__sustantivos__',
                       size=(25, 5))
        ],
                                 [
                                     sg.Text('Cantidad:'),
                                     sg.Spin([i for i in range(0, 6)],
                                             initial_value=0,
                                             size=(3, 3),
                                             key='__cantsustantivos__'),
                                     sg.ColorChooserButton(
                                         'Elegir color',
                                         key='__sustColorChooser__',
                                     )
                                 ]],
                 relief=sg.RELIEF_RIDGE)
    ]]

    Config = [[
        sg.Text(' ' * 43),
        sg.Text(
            'Ingrese de a una las palabras a utilizar (sin espacios en blanco)',
            font=('Helvetica', 11))
    ],
              [
                  sg.Text(' ' * 40),
                  sg.Input(do_not_clear=False, key='__input__'),
                  sg.Submit('Agregar', key='__addbutton__'),
                  sg.Button('Eliminar', key='__deletebutton__')
              ], [sg.Text('_' * 113)],
              [sg.Text('Palabras ingresadas', font=('Helvetica', 13))],
              [
                  sg.Column(columna_verbos),
                  sg.Column(columna_adj),
                  sg.Column(columna_sust)
              ], [sg.Text('_' * 113)],
              [
                  sg.Text('Ayuda'),
                  sg.InputOptionMenu(('Si', 'No'), key='__ayuda__'),
                  sg.Text('Orientacion'),
                  sg.InputOptionMenu(('Horizontal', 'Vertical'),
                                     key='__orientacion__'),
                  sg.Text('Letras'),
                  sg.InputOptionMenu(('Mayúsculas', 'Minúsculas'),
                                     key='__letras__'),
                  sg.Text('Oficina'),
                  sg.InputOptionMenu(values=list(oficinas_temp.keys()),
                                     key='__oficinas__'),
                  sg.Text(' ' * 5),
                  sg.Ok('Aceptar', button_color=('white', '#475841'))
              ]]

    layout_selectAyuda = [
        [sg.Text('Seleccione las ayudas a usar')],
        [
            sg.Checkbox('Definicion de palabra',
                        key='__ayudaDefinicion__',
                        default=True),
            sg.Checkbox('Lista de Palabras',
                        key='__ayudalistaPalabras__',
                        default=True)
        ],
        [sg.Submit('Aceptar')],
    ]

    # ------------------------------------ Window Loop ------------------------------------

    ventana_IngVen = sg.Window('Configuracion', layout=Config)
    window_selectAyuda = sg.Window('Ayudas', layout=layout_selectAyuda)

    while True:
        event, values = ventana_IngVen.Read()
        tipo = ''
        if event is None:
            sys.exit()
        elif event == '__addbutton__':
            valores = Web.ProcesarPalabra(values['__input__'].lower(),
                                          dic_palabras, tipo)
            if valores[0]:
                ventana_IngVen.FindElement(valores[1]).Update(
                    dic_palabras[valores[1]])
            ventana_IngVen.Refresh()

        elif event == '__deletebutton__':
            tipo_borrado = borrar_valor(values['__input__'], dic_palabras)
            if tipo_borrado != '':  #Chequear que la palabra a eliminar sea valida
                ventana_IngVen.FindElement(tipo_borrado).Update(
                    dic_palabras[tipo_borrado])
            else:
                sg.PopupError('Palabra no existente', title='')

        elif event == 'Aceptar':
            # corroborar que no se haya equivocado
            if values['__cantverbos__'] == '0' and values[
                    '__cantadjetivos__'] == '0' and values[
                        '__cantsustantivos__'] == '0':
                continuar = sg.PopupYesNo(
                    'Se eligieron 0 verbos, 0 adjetivos y 0 sustantivos. \n'
                    'Esto finalizará el juego y perderá todos los datos ingresados.\n'
                    'Desea continuar?',
                    title='Peligro',
                    font=('Helvetica', 9, 'bold'),
                    button_color=('#000000', '#ff1919'))
                if continuar == 'Yes':
                    sys.exit()
                else:
                    pass
            else:
                break
    # convertir valores string a numericos para facilitar el procesamiento luego
    values['__cantsustantivos__'] = int(values['__cantsustantivos__'])
    values['__cantverbos__'] = int(values['__cantverbos__'])
    values['__cantadjetivos__'] = int(values['__cantadjetivos__'])

    if (values['__cantverbos__'] != 0) or (values['__cantadjetivos__'] !=
                                           0) or (values['__cantsustantivos__']
                                                  != 0):
        if values['__ayuda__'] == 'Si':  #en caso de que se seleccione ayuda,
            event_ayuda, values_ayuda = window_selectAyuda.Read()
            if event_ayuda is 'Aceptar':
                values['__ayudalistaPalabras__'] = values_ayuda[
                    '__ayudalistaPalabras__']
                values['__ayudaDefinicion__'] = values_ayuda[
                    '__ayudaDefinicion__']
            else:  #Si apreta X en la ventana de ayudas
                values['__ayuda__'] = 'No'
        #generar colores random si no se ingresan
        if values['__verbColorChooser__'] == '' or values[
                '__verbColorChooser__'] == 'None':  #Generar colores al azar si no son ingresados
            values['__verbColorChooser__'] = '#' + "%06x" % random.randint(
                0, 0xFFFFFF)
        if values['__adjColorChooser__'] == '' or values[
                '__adjColorChooser__'] == 'None':
            values['__adjColorChooser__'] = '#' + "%06x" % random.randint(
                0, 0xFFFFFF)
        if values['__sustColorChooser__'] == '' or values[
                '__sustColorChooser__'] == 'None':
            values['__sustColorChooser__'] = '#' + "%06x" % random.randint(
                0, 0xFFFFFF)

        #comprobar que la cantidad pedida de cada tipo no sobrepase la cantidad ingresada
        if values['__cantsustantivos__'] > len(
                dic_palabras['__sustantivos__']):
            values['__cantsustantivos__'] = len(
                dic_palabras['__sustantivos__'])
        if values['__cantverbos__'] > len(dic_palabras['__verbos__']):
            values['__cantverbos__'] = len(dic_palabras['__verbos__'])
        if values['__cantadjetivos__'] > len(dic_palabras['__adjetivos__']):
            values['__cantadjetivos__'] = len(dic_palabras['__adjetivos__'])

        # determino color de look and feel.
        if oficinas_temp[values['__oficinas__']] < 10:
            sg.ChangeLookAndFeel('BlueMono')
        elif (oficinas_temp[values['__oficinas__']] >=
              10) and (oficinas_temp[values['__oficinas__']] <= 25):
            sg.ChangeLookAndFeel('Purple')
        else:
            sg.ChangeLookAndFeel('Reds')

        # elimino los valores devueltos por el layout que no me sirven
        valoresInservibles = [
            '__input__', '__verbos__', '__adjetivos__', '__sustantivos__'
        ]
        for dato in valoresInservibles:
            if dato in values.keys():
                del values[dato]
    ventana_IngVen.Close()
    window_selectAyuda.Close()
    # print(values)
    return values
예제 #25
0
class Life_World(World):
    WHITE = '#ffffff'
    BLACK = '#000000'

    fg_color_chooser = sg.ColorChooserButton('foreground',
                                             button_color=(WHITE, WHITE),
                                             size=(10, 1))
    bg_color_chooser = sg.ColorChooserButton('background',
                                             button_color=(BLACK, BLACK),
                                             size=(10, 1))

    SELECT_FOREGROUND_TEXT = 'Select foreground color'
    SELECT_BACKGROUND_TEXT = 'Select background color'

    current_row_index = 0
    rule = None

    # The key is the state (L, M, R), and the value is the rule number (or index in a binary string)
    # Ex. Rule 110 is '01110110' in binary. If we take allstates[(0,0,0)], we can get 7, and use that index to get the on/off result.
    all_states = {
        (0, 0, 0): 7,
        (0, 0, 1): 6,
        (0, 1, 0): 5,
        (0, 1, 1): 4,
        (1, 0, 0): 3,
        (1, 0, 1): 2,
        (1, 1, 0): 1,
        (1, 1, 1): 0
    }

    def get_color_and_update_button(self,
                                    button,
                                    default_color_string,
                                    values=None):
        if not values:
            values = self.values
        key = button.get_text()
        color_string = values.get(key, '')
        if color_string in {'None', '', None}:
            color_string = default_color_string
        button.update(button_color=(color_string, color_string))
        color = Color(color_string)
        return color

    def get_colors(self):
        CA_Patch.bg_color = self.get_color_and_update_button(
            self.bg_color_chooser,
            default_color_string=rgb_to_hex(CA_Patch.bg_color))
        CA_Patch.fg_color = self.get_color_and_update_button(
            self.fg_color_chooser,
            default_color_string=rgb_to_hex(CA_Patch.fg_color))

    def handle_event_and_values(self):
        """
        This method handles the color chooser. It does it in a round-about way because
        the color chooser can't generate events. Consequently, the user is asked to click
        a button next to the color-chooser. In processing that button-click, we ".click()"
        the color-chooser button. The user selects a color, which we retrieve by reading
        the window. We then color the color-chooser button with that color.
        """
        foreground = self.event == Life_World.SELECT_FOREGROUND_TEXT
        # There are two color-choosers: foreground and background. Determine and select the
        # desired color chooser based on the label on the button the user clicked.
        color_chooser_button = Life_World.fg_color_chooser if foreground else Life_World.bg_color_chooser
        # Run it
        color_chooser_button.click()

        # Create a default color_string in case the user had cancelled color selection.
        # The default color string is the string of the current color.
        default_color_string = rgb_to_hex(
            CA_Patch.fg_color if foreground else CA_Patch.bg_color)
        # Retrieve the color choice by reading the window.
        (_event, values) = gui.WINDOW.read(timeout=10)

        color = self.get_color_and_update_button(color_chooser_button,
                                                 default_color_string, values)

        # Set the color to the new choice
        if foreground:
            CA_Patch.fg_color = color
        else:
            CA_Patch.bg_color = color

        # Update the patches.
        for patch in self.patches:
            patch.set_alive_or_dead(patch.is_alive)

    def mouse_click(self, xy: Tuple[int, int]):
        """ Toggle clicked patch's aliveness. """
        patch = self.pixel_tuple_to_patch(xy)
        patch.set_alive_or_dead(not patch.is_alive)

    def setup(self):
        self.get_colors()
        # Converts the gui value 'rule' into 8 bit binary
        self.rule = format(self.get_gui_value('rule'), '08b')
        density = self.get_gui_value('density')
        self.current_row_index = 0

        # iterate through the first row of patches and fill it in with the desired density
        for patch in self.patches[self.
                                  current_row_index:self.current_row_index +
                                  gui.PATCH_COLS]:
            is_alive = randint(0, 100) < density
            patch.set_alive_or_dead(is_alive)

    def step(self):

        # Currently works only if number of rows == number of cols
        # Since self.patches is just one long list, I can find out the first column of the last row
        # If our starting point is the first column of the last row, we move that last row to the top and empty the rest of the board.
        if self.current_row_index == gui.PATCH_COLS * (gui.PATCH_COLS - 1):
            patch_num = 0
            for patch in self.patches[self.current_row_index -
                                      gui.PATCH_COLS:self.current_row_index +
                                      gui.PATCH_COLS]:
                if patch.is_alive:
                    self.patches[patch_num].set_alive_or_dead(True)
                else:
                    self.patches[patch_num].set_alive_or_dead(False)
                patch_num += 1
            self.current_row_index = 0
            for patch in self.patches[self.current_row_index +
                                      gui.PATCH_COLS:]:
                patch.set_alive_or_dead(False)

        # Determine and set whether each patch is_alive in the next state.
        self.get_colors()

        # cur_index gives you the index of the next row, but same column.
        cur_index = self.current_row_index + gui.PATCH_COLS
        # Iterate through the patches in the current row
        for patch in self.patches[self.
                                  current_row_index:self.current_row_index +
                                  gui.PATCH_COLS]:

            # patch_state will return a tuple (L, M, R), ex.. (0, 1, 0)
            # (0, 1, 0) means the left is off, middle is on, and right is off.
            patch_state = patch.LMR_status()
            # Returns a 0 or 1 depending on the binary index given by the state
            dead_or_alive = self.rule[self.all_states[patch_state]]

            if dead_or_alive == '0':
                self.patches[cur_index].set_alive_or_dead(False)
            else:
                self.patches[cur_index].set_alive_or_dead(True)

            cur_index += 1

        self.current_row_index += gui.PATCH_COLS
예제 #26
0
 ],
 [
     sg.Text('This multiline input change submits'),
     sg.ML('', change_submits=True)
 ], [sg.Text('This input is normal'),
     sg.Input(),
     sg.FileBrowse()],
 [
     sg.Text('File Browse submits'),
     sg.Input(change_submits=True, key='-in1-'),
     sg.FileBrowse()
 ],
 [
     sg.Text('Color Chooser submits'),
     sg.Input(change_submits=True, key='-in2-'),
     sg.ColorChooserButton('Color...', target=(sg.ThisRow, -1))
 ],
 [
     sg.Text('Folder Browse submits'),
     sg.Input(change_submits=True, key='-in3-'),
     sg.FolderBrowse()
 ],
 [
     sg.Text('Calendar Chooser submits'),
     sg.Input(change_submits=True, key='-in4-'),
     sg.CalendarButton('Date...', target=(sg.ThisRow, -1))
 ],
 [
     sg.Text('Disabled input submits'),
     sg.Input(change_submits=True, disabled=True, key='_in5'),
     sg.FileBrowse()
                                  [
                                      sg.Text('3D Head WaveFront ',
                                              size=(20, 1)),
                                      sg.InputText(DEFAULT_OUTPUT,
                                                   size=(50, 1),
                                                   key='_OBJ_PATH_'),
                                      sg.FileBrowse()
                                  ], [sg.Button('Show 3D model')]]

    hair_color_frame_layout = [[
        sg.Text('Hair Color:'),
        sg.InputText("#000000", key="_hair_color_value_")
    ],
                               [
                                   sg.ColorChooserButton(
                                       "Choose",
                                       target="_hair_color_value_",
                                       key="_hair_color_chooser_")
                               ]]
    # Main Layout
    layout = [
        [sg.Menu(menu_bar_def)],
        [
            sg.Frame('Input',
                     input_frame_layout,
                     title_color='white',
                     key="_INPUT_FRAME_",
                     visible=True),
            sg.Frame('Input Preview',
                     input_preview_frame_layout,
                     title_color='white',
                     key="_IMG_PREVIEW_FRAME_",
예제 #28
0
def configuracion():
    with open('configuracion.json') as f:
        data = json.load(f)
    color = [
        "red", "blue", "green", "orange", "yellow", "gray", "purple", "pink",
        "brown"
    ]
    layout = [
        [
            sg.Text(" Configurar palabras ",
                    relief='raised',
                    text_color='black')
        ],
        [
            sg.Text("Ingrese una palabra", size=(20, 1), relief='groove'),
            sg.InputText(key='input', size=(20, 3))
        ],
        [sg.Listbox(values=(data["palabras"]), key="list", size=(50, 3))],
        [sg.Submit("Agregar"), sg.Submit("Quitar")],
        [sg.Text("Colores", relief='raised', text_color='black')],
        [
            sg.ColorChooserButton('Sustantivos',
                                  size=(11, 1),
                                  key='color_sust',
                                  button_color=('white', 'red')),
            sg.ColorChooserButton('Verbos',
                                  size=(10, 1),
                                  key='color_verb',
                                  button_color=('white', 'green')),
            sg.ColorChooserButton('Adjetivos',
                                  size=(10, 1),
                                  key='color_adj',
                                  button_color=('white', 'blue'))
        ],
        [sg.Text("Orientacion", relief='raised', text_color='black')],
        [
            sg.InputCombo(("Vertical", "Horizontal"),
                          size=(10, 1),
                          default_value=data["orientacion"],
                          key='vert_horiz')
        ],
        [sg.Text("Cantidad de palabras", relief='raised', text_color='black')],
        [
            sg.Text(
                "Sustantivos:",
                size=(12, 1),
            ),
            sg.InputText(size=(3, 1),
                         default_text=data["cantidad"]["Sustantivos"],
                         key='cant_sust'),
            sg.Text("Verbos:", size=(7, 1)),
            sg.InputText(size=(3, 1),
                         default_text=data["cantidad"]["Verbos"],
                         key='cant_verb'),
            sg.Text("Adjetivos:", size=(10, 1)),
            sg.InputText(size=(3, 1),
                         default_text=data["cantidad"]["Verbos"],
                         key='cant_adj')
        ],
        [
            sg.Text("Mayúsculas/Minúsculas",
                    relief='raised',
                    text_color='black')
        ],
        [
            sg.InputCombo(("Mayúsculas", "Minúsculas"),
                          size=(10, 1),
                          default_value=data["mayus"],
                          key='mayus')
        ],
        [
            sg.Text("Tipografías de títulos y texto para el reporte",
                    relief='raised',
                    text_color='black')
        ],
        [
            sg.Text("Tútulos", relief='groove'),
            sg.InputCombo((color),
                          size=(5, 1),
                          default_value=data["titulos"],
                          key='titulos')
        ],
        [
            sg.Text("Textos", relief='groove'),
            sg.InputCombo((color),
                          size=(5, 1),
                          default_value=data["textos"],
                          key='textos')
        ],
        [sg.Text("Estilo", relief='raised', text_color='black')],
        [
            sg.InputCombo(("Vertical", "Horizontal"),
                          size=(10, 1),
                          default_value=data["estilo"],
                          key='estilo')
        ],
        [sg.Text("Oficina", relief='raised', text_color='black')],
        [
            sg.InputCombo(("Vertical", "Horizontal"),
                          size=(10, 1),
                          default_value=data["oficina"],
                          key='oficina')
        ],
        [sg.Submit("Guardar cambios"),
         sg.Cancel("Volver")],
    ]

    window = sg.Window("Configuración", size=(570, 670),
                       font='Courier').Layout(layout)

    while True:
        button, values = window.Read()
        Lista = data["palabras"]

        if button == "Guardar cambios":
            datosConfig = {}
            datosConfig["palabras"] = sorted(Lista,
                                             key=lambda palabra: len(palabra),
                                             reverse=True)
            datosConfig["colores"] = {
                "Sustantivos": values['color_sust'],
                "Verbos": values['color_verb'],
                "Adjetivos": values['color_adj']
            }
            datosConfig["orientacion"] = values['vert_horiz']
            datosConfig["cantidad"] = {
                "Sustantivos": values['cant_sust'],
                "Verbos": values['cant_verb'],
                "Adjetivos": values['cant_adj']
            }
            datosConfig["mayus"] = values['mayus']
            datosConfig["titulos"] = values['titulos']
            datosConfig["textos"] = values['textos']
            datosConfig["estilo"] = values['estilo']
            datosConfig["oficina"] = values['oficina']
            with open("configuracion.json", "w") as j:
                json.dump(datosConfig, j)

        if button == "Volver" or values == None:
            break
        if button == "Agregar":
            Lista.append(values['input'])
            window.FindElement('list').Update(values=(Lista))
            window.FindElement('input').Update('')
            print(values['list'])
        if button == "Quitar":
            try:
                Lista.remove(values['list'][0])
            except (ValueError):
                sg.PopupError(
                    "No se puede quitar la palabra por que no existe en la lista"
                )
            window.FindElement('list').Update(values=(Lista))

    window.Close()
예제 #29
0
def configurar():
    dic_tipo1 = {'Sustantivo': [], 'Adjetivo': [], 'Verbo': []}
    lis_tipo2 = [
        ['NN', 'NNS', 'NNP', 'NNPS'],  #Sustantivo
        ['JJ', 'JJR', 'JJS'],  #Adjetivo
        ['VB', 'VBZ', 'VBP', 'VBD', 'VBN', 'VBG'],  #Verbo
    ]
    pedirPalabra = [[sg.InputText(key='palabra', do_not_clear=False)]]
    color_pal = [[
        sg.Text('Color Sustantivos: '),
        sg.Input(change_submits=True,
                 size=(10, 1),
                 do_not_clear=True,
                 key='ColorSus'),
        sg.ColorChooserButton('Elegir', target=(sg.ThisRow, -1))
    ],
                 [
                     sg.Text('Color Adjetivos:     '),
                     sg.Input(change_submits=True,
                              size=(10, 1),
                              do_not_clear=True,
                              key='ColorAdj'),
                     sg.ColorChooserButton('Elegir', target=(sg.ThisRow, -1))
                 ],
                 [
                     sg.Text('Color Verbos:        '),
                     sg.Input(change_submits=True,
                              size=(10, 1),
                              do_not_clear=True,
                              key='ColorVer'),
                     sg.ColorChooserButton('Elegir', target=(sg.ThisRow, -1))
                 ]]

    layout = [
        [
            sg.Text('Configuracion (Parte 1/2)',
                    size=(50, 1),
                    justification='center',
                    font=(
                        'arial',
                        16,
                    ))
        ],
        [
            sg.Frame(
                'Ingrese palabras (de a una) con los signos de correspondientes.	Nota: Se requiere conexion a internet.',
                pedirPalabra)
        ], [sg.Button('Agregar'), sg.Button('Eliminar')], [sg.Text('')],
        [sg.Frame('Color de los tipos de palabras', color_pal)],
        [sg.Checkbox('Habilitar boton de ayuda', key='ayuda')],
        [sg.Button('Siguiente Parte')]
    ]

    window = sg.Window('Ingreso de palabras.').Layout(layout)
    while True:
        boton, values = window.Read()
        if boton is None:
            break
        elif boton == 'Agregar':
            if (values['palabra'] == ""):
                sg.Popup('Ingresa una palabra')
            else:
                palabra1 = values['palabra']
                if not palabra1.isalpha():
                    sg.Popup(palabra1 + ' no es una palabra.')
                else:
                    dic_tipo1 = clasificar_palabra(palabra1, dic_tipo1,
                                                   lis_tipo2)

        elif boton == 'Eliminar':
            palabra1 = values['palabra']
            if (palabra1 == ""):
                sg.Popup('Ingresa una palabra')
            else:
                dic_tipo1 = eliminar_palabra(palabra1, dic_tipo1)
        elif boton == 'Siguiente Parte':
            dic_cant = cantidad_palabras(dic_tipo1)
            window.Hide()
            layout2 = [
                [
                    sg.Text('Configuracion (Parte 2/2)',
                            size=(50, 1),
                            justification='center',
                            font=('arial', 16))
                ],
                [
                    sg.Text(
                        'Elija para cada tipo de palabra la cantidad que desea que este en la sopa de letras'
                    )
                ],
                [
                    sg.Text('Cantidad de sustantivos', font=('arial', 12)),
                    sg.Slider(range=(0, dic_cant['Sustantivo']),
                              change_submits=True,
                              orientation='h',
                              size=(34, 20),
                              default_value=0,
                              key='cSus')
                ],
                [
                    sg.Text('Cantidad de adjetivos', font=('arial', 12)),
                    sg.Slider(range=(0, dic_cant['Adjetivo']),
                              change_submits=True,
                              orientation='h',
                              size=(34, 20),
                              default_value=0,
                              key='cAdj')
                ],
                [
                    sg.Text('Cantidad de verbos', font=('arial', 12)),
                    sg.Slider(range=(0, dic_cant['Verbo']),
                              change_submits=False,
                              orientation='h',
                              size=(34, 20),
                              default_value=0,
                              key='cVer')
                ], [sg.Button('Listo')]
            ]
            window2 = sg.Window('Elegir cantidad').Layout(layout2)
            while True:
                boton2, values2 = window2.Read()
                if boton2 is None:
                    break
                elif boton2 is 'Listo':
                    break
            Cpalabras_elegidas = {}
            Cpalabras_elegidas['Sustantivos'] = int(values2['cSus'])
            Cpalabras_elegidas['Adjetivos'] = int(values2['cAdj'])
            Cpalabras_elegidas['Verbos'] = int(values2['cVer'])
            break
    colores = {}
    colores['Sustantivo'] = values['ColorSus']
    colores['Adjetivo'] = values['ColorAdj']
    colores['Verbo'] = values['ColorVer']
    ayuda = values['ayuda']
    print(dic_tipo1)
    print(Cpalabras_elegidas)
    print(colores)
    print(ayuda)
    return (dic_tipo1, Cpalabras_elegidas, colores, ayuda)
예제 #30
0
def createLayout():
    layout = [
        [
            sg.Text('Исходный документ'),
            sg.InputText(key='-docfile-', size=(60, 1), pad=((3, 0), 0)),
            sg.FileBrowse("Выбрать..", key='-choicefile-', pad=((5, 0), 0))
        ],
        [
            sg.Frame(layout=[[
                sg.Text('Тип шрифта:'),
                sg.InputCombo(
                    ('Times New Roman', 'Calibri', 'Tahoma',
                     'Franklin Gothic Medium', 'Comic Sans', 'Segoe', 'Align'),
                    size=(23, 1),
                    key='-fontname-',
                    pad=((2, 0), 0)),
                sg.Text('Размер:', pad=((10, 0), 0)),
                sg.Spin([i for i in range(1, 72)],
                        initial_value=12,
                        key='-fontsize-',
                        size=(4, 1)),
                sg.ColorChooserButton("Выберите цвет",
                                      target='-fontcolor-',
                                      key='-color-',
                                      size=(15, 1),
                                      pad=((18, 0), 0)),
                sg.InputText(enable_events=True,
                             key='-fontcolor-',
                             size=(12, 1),
                             pad=((4, 0), 0),
                             justification='center')
            ],
                             [
                                 sg.Text('Выравнивание:'),
                                 sg.InputCombo(
                                     ('По левому краю', 'По центру',
                                      'По правому краю', 'По ширине'),
                                     size=(20, 1),
                                     key='-aligment-',
                                     pad=((6, 0), 0)),
                                 sg.Checkbox('Жирный',
                                             key='-bold-',
                                             font=('Segoe', 10, 'bold'),
                                             pad=((10, 0), 0)),
                                 sg.Checkbox('Курсив',
                                             key='-italic-',
                                             font=('Segoe', 10, 'italic'),
                                             pad=((37, 0), 0)),
                                 sg.Checkbox('Подчёркнутый',
                                             key='-underline-',
                                             font=('Segoe', 10, 'underline'),
                                             pad=((37, 0), 0))
                             ]],
                     title='Текст',
                     font=('Segoe', 12, 'bold'))
        ],
        [
            sg.Frame(layout=[[
                sg.Text('Междустрочный интервал:'),
                sg.InputCombo(('1.5', 'Двойной', 'Одинарный', 'Минимум'),
                              size=(11, 1),
                              key='-linespace-'),
                sg.Text('Интервал перед:', size=(13, 1), pad=((10, 0), 0)),
                sg.Spin([str(i) for i in frange(0, 72, 0.25)],
                        initial_value=0,
                        key='-before-',
                        size=(5, 1)),
                sg.Text('Интервал после:', size=(14, 1), pad=((5, 0), 0)),
                sg.Spin([str(i) for i in frange(0, 72, 0.25)],
                        initial_value=0,
                        key='-after-',
                        size=(5, 1))
            ],
                             [
                                 sg.Text('Начало абзаца:'),
                                 sg.Spin([str(i) for i in frange(0, 72, 0.25)],
                                         initial_value=1.25,
                                         key='-redline-',
                                         size=(5, 1),
                                         pad=((5, 0), 0)),
                                 sg.Text('Интервал cлева:',
                                         size=(13, 1),
                                         pad=((120, 0), 0)),
                                 sg.Spin([str(i) for i in frange(0, 72, 0.25)],
                                         initial_value=0,
                                         key='-intleft-',
                                         size=(5, 1)),
                                 sg.Text('Интервал cправа:',
                                         size=(14, 1),
                                         pad=((5, 0), 0)),
                                 sg.Spin([str(i) for i in frange(0, 72, 0.25)],
                                         initial_value=0,
                                         key='-intright-',
                                         size=(5, 1))
                             ]],
                     title='Абзац',
                     font=('Segoe', 12, 'bold'))
        ],
        [
            sg.Frame(layout=[[
                sg.Text('Верхнее:', size=(7, 1)),
                sg.Spin([str(i) for i in frange(0, 72, 0.25)],
                        initial_value=0,
                        key='-top-',
                        size=(5, 1)),
                sg.Text('Нижнее:', size=(6, 1), pad=((5, 2), 0)),
                sg.Spin([str(i) for i in frange(0, 72, 0.25)],
                        initial_value=0,
                        key='-bottom-',
                        size=(5, 1))
            ],
                             [
                                 sg.Text('Левое:', size=(7, 1)),
                                 sg.Spin([str(i) for i in frange(0, 72, 0.25)],
                                         initial_value=0,
                                         key='-left-',
                                         size=(5, 1)),
                                 sg.Text('Правое:',
                                         size=(6, 1),
                                         pad=((5, 2), 9)),
                                 sg.Spin([str(i) for i in frange(0, 72, 0.25)],
                                         initial_value=0,
                                         key='-right-',
                                         size=(5, 1))
                             ]],
                     title='Поля',
                     font=('Segoe', 12, 'bold')),
            sg.Frame(layout=[[
                sg.FileBrowse("Загрузить шаблон",
                              key='-template-',
                              size=(15, 0)),
                sg.InputText(enable_events=True,
                             key='-example-',
                             size=(31, 0),
                             pad=((3, 0), 0))
            ],
                             [
                                 sg.FileSaveAs("Сохранить шаблон",
                                               file_types=(('ALL Files',
                                                            '*.json'), ),
                                               target='-saved-',
                                               key='-save-',
                                               size=(15, 0),
                                               pad=((1, 1), 5)),
                                 sg.InputText(enable_events=True,
                                              key='-saved-',
                                              size=(31, 0),
                                              pad=((3, 0), 0))
                             ]],
                     title='Шаблоны',
                     font=('Segoe', 12, 'bold'),
                     pad=((5, 0), 0))
        ],
        [
            sg.Button("Применить", size=(14, 2), pad=((0, 5), 4)),
            sg.Button("Закрыть", size=(14, 2), pad=((5, 0), 4))
        ]
    ]
    return layout