Пример #1
0
    def __init__(self, config):
        """

        Instantiate a new instance of MainWindow

        """

        # Gather the name of the icon set we should be using. We will use this to search the icon set packages
        icon_set_str = config['GUI_PREFS']['icon_set']
        self.icons = import_icon_set(icon_set_str)

        # Create an instance-flag that can be toggled to False or True when this window is active or not respectively
        self.win_active = False

        # Start an instance of the AdaSense class which will allow us to easily interface with the SenseHat
        self.ada_sense = AdaSense(config=config)

        # Create a log-name for this class
        self.log_name = f'{PROG}.GUI.MainWindow'
        log = getLogger(self.log_name)
        log.debug(f'Started logger for {self.log_name}')
        log.debug(f'Initializing AdaHub.GUI.MainWindow...')

        Qt.theme(config['GUI_PREFS']['theme'])

        self.window = Qt.Window('AdaHub Home',
                                layout=self.main_layout(),
                                no_titlebar=True,
                                alpha_channel=0.8,
                                grab_anywhere=True,
                                size=(500, 500))
Пример #2
0
    def category_to_layout(category_info):
        titles = []
        links = []
        frameworks = []
        col1 = []
        col2 = []
        count = 0
        for model in category_info['models']:
            if model.get('title'):
                titles.append(model['title'][0:60])
            else:
                titles.append('null')
            if model.get('link'):
                links.append(model['link'].replace('https://github.com/', ''))
            else:
                links.append('null')
            if model.get('framework'):
                frameworks.append(model['framework'])
            else:
                frameworks.append('null')
        for x in range(len(titles)):
            if (count % 2) != 0:
                col1.append([
                    g.Button(titles[x] + ' | ' + frameworks[x],
                             key='https://github.com/' + links[x])
                ])
            else:
                col2.append([
                    g.Button(titles[x] + ' | ' + frameworks[x],
                             key='https://github.com/' + links[x])
                ])
            count += 1

        return col1, col2
Пример #3
0
    def geolocale_frame():
        """
        This frame helps us group settings related to the geo-location together to present in the GUI for the end-user

        :return:
        """

        import PySimpleGUIQt as qt

        struct = [[
            qt.Text('Street Address:', justification="left"),
            qt.InputText('', key='input_st_address')
        ],
                  [
                      qt.Text('City:', justification='left'),
                      qt.InputText('', key='input_city')
                  ],
                  [
                      qt.Text('State:', justification='left'),
                      qt.InputText('', key='input_state')
                  ],
                  [
                      qt.Text('Lat:', justification='left'),
                      qt.InputText('', key='lat_input'),
                      qt.Text('Lon:', justification='center'),
                      qt.InputText('', key='lon_input'),
                  ]]

        return struct
Пример #4
0
    def rearrange_layout_of_tab(self) -> None:
        # Todo: Limit to Toplevel/Add another limit, otherwise the ui will
        # turn crowded
        self.check_boxes = []
        for id_el in self.all_ids:
            new_checkbox = sg.Checkbox(text=self.id_collecion_name_dict[id_el],
                                       key=f"-checkbox-{id_el}-",
                                       default=id_el in self.valid_ids)
            new_checkbox.any = {"collection_id": id_el}
            self.check_boxes.append(new_checkbox)

        self.rows = []

        checkbox_frame = sg.Frame(title="Active Collections:",
                                  layout=[self.check_boxes])

        self.rows.append([checkbox_frame])

        self.rows.append([
            sg.Text(f"Current Exercise: \n {self.current_human_id} ",
                    justification="center")
        ])
        if self.display_solution:
            self.rows.append([self.exercise_image, self.solution_image])
        else:
            self.rows.append([self.exercise_image])
        self.rows.append([self.btn_show_solution])
Пример #5
0
    def load_exercise_solution(self) -> None:
        session: Session
        with BackendSession.begin() as session:
            if self.current_ex_sol_pair_id:
                current_pair: ExerciseSolutionPair = session.query(
                    ExerciseSolutionPair).filter_by(
                        internal_id=self.current_ex_sol_pair_id).one()
                current_pair.attempt_counter += 1

            next_pair = determine_next_exercise_solution_pair(
                session, self.valid_ids)
            self.current_ex_sol_pair_id = next_pair.internal_id
            self.current_human_id = next_pair.human_id
            exercise_file_path = retrieve_file(BaseConfig.exercise_path,
                                               next_pair.human_id)
            solution_file_path = retrieve_file(BaseConfig.solution_path,
                                               next_pair.human_id)

        image_bytes_exercise = convert_to_bytes(str(exercise_file_path),
                                                resize=(700, 700))
        image_bytes_solution = convert_to_bytes(str(solution_file_path),
                                                resize=(700, 700))

        self.exercise_image = sg.Image(data=image_bytes_exercise,
                                       size=(100, 100))
        self.solution_image = sg.Image(data=image_bytes_solution,
                                       size=(100, 100))
Пример #6
0
def autocomplete_popup_show(text_list):
    autocomplete_popup_layout = [[
        sg.Listbox(values=text_list,
                   size=(100, 20 * len(text_list)) if QT else
                   (15, len(text_list)),
                   change_submits=True,
                   bind_return_key=True,
                   auto_size_text=True,
                   key='_FLOATING_LISTBOX_',
                   enable_events=True)
    ]]

    autocomplete_popup = sg.Window("Borderless Window",
                                   default_element_size=(12, 1),
                                   auto_size_text=False,
                                   auto_size_buttons=False,
                                   no_titlebar=True,
                                   grab_anywhere=True,
                                   return_keyboard_events=True,
                                   keep_on_top=True,
                                   background_color='black',
                                   location=(1320, 622),
                                   default_button_element_size=(12, 1))

    window = autocomplete_popup.Layout(autocomplete_popup_layout).Finalize()
    return window
def main_loop(window: sg.Window):
    """
    Função que executa o loop principal da janela da aplicação.

    Arguments:
        window (sg.Window): objeto de janela do PySimpleGUI
    """
    while True:
        event, values = window.read()

        if event == 'Gerar planilha':
            input_file = values['_FILE_INPUT_']
            output_file = values['_FILE_OUTPUT_']

            try:
                if output_file[-5:] != '.xlsx':
                    output_file += '.xlsx'

                generate_worksheet(input_file, output_file, window=window)
                print()
                window.refresh()

            except Exception as exc:
                sg.Popup(str(exc), title='Erro ao tentar executar')
                sg.Popup('Garanta que você tenha selecionado uma planilha no formato\ncorreto e tenha selecionado um local adequado para salvar a\nplanilha que será gerada.', title='Dica')

        
        if (event == sg.WINDOW_CLOSED) or (event == 'Quit'):
            break

        window.refresh()
    def redraw_visible_ui(self) -> List:
        self.rearrange_layout_of_tab()

        default_frame: sg.Frame = sg.Frame(title="", layout=self.rows, element_justification="center",
                                           size=(200, 200), key=f"-framekey-f{self.title}")
        visible_tab = sg.Tab(title=self.title, layout=[[default_frame]])
        return [visible_tab]
Пример #9
0
 def show_clip_list_window(self, clips):
     """ Show all received clips in a Windows with a Listview and allow
         user select and copy an entry
     """
     # TODO: Show Only preview of Clip to reduce length
     layout = [
         [
             sg.Listbox(
                 values=clips,
                 size=(60, 6),
                 select_mode="LISTBOX_SELECT_MODE_SINGLE",
                 key="sel_clip",
             )
         ],
         [sg.Button("Copy to clipboard", size=(20, 1)), sg.Cancel(size=(20, 1))],
     ]
     window = sg.Window(
         title=f"{Config.APP_NAME} - Your Clips",
         layout=layout,
         size=(600, 300),
         icon=Config.ICON_B64,
     )
     event, values = window.read()
     if event in (sg.WIN_CLOSED, "Cancel"):
         log.debug("List Clips selection canceled")
         pass
     elif event == "Copy to clipboard":
         Api.paste(values.get("sel_clip")[0])
     window.close()
Пример #10
0
    def check_cred(self, window):
        """ Given credentials input check if we can perform action of
            login or registration on server

        Args:
            window (PySimpleGUIQt.Window): GUI-Window asking for creds

        Returns:
            bool: True if credentials are valid, else False
        """
        event, values = window.read()
        log.debug(f"{event} - {values}\n\n")
        if event in (sg.WIN_CLOSED, "Cancel"):
            log.debug("Credentials entry canceled")
            return True
        else:
            self.set_config_ignore_ssl_cert(values.get("ignore_cert"))
            if self.is_cred_input_valid(values):
                server, user, pw = self.is_cred_input_valid(values)
                if event == "Login":
                    if self.check_cred_login_and_save(server, user, pw):
                        sg.popup(
                            f"Credentials saved to config file: {Config.PATH_CONFIG_FILE}",
                            title=f"{Config.APP_NAME}",
                        )
                        return True
                elif event == "Register":
                    if self.check_cred_register_and_save(server, user, pw):
                        sg.popup(
                            f"Credentials saved to config file: {Config.PATH_CONFIG_FILE}",
                            title=f"{Config.APP_NAME}",
                        )
                    return True
        return False
Пример #11
0
def SendTC(file_name, instrument_type, note):

    flights = [
        'FLOATS_51', 'FLOATS_52', 'FLOATS_53', 'RACHuTS_51', 'RACHuTS_52',
        'RACHuTS_53', 'LPC_51', 'LPC_52', 'LPC_53'
    ]

    flight_layout = [[
        sg.Listbox(values=flights,
                   key='_param_',
                   tooltip='Select balloon/instrument to send TC to',
                   size=(20, 6),
                   font=Font)
    ]]
    layout_config_TC = [
        [sg.Frame('Select Instrument/Flight: ', flight_layout, font=Font)],
        #[sg.Frame('Input new value: ', value_layout, font = Font)],
        [
            sg.Submit(font=Font, pad=(10, 10)),
            sg.Cancel(font=Font, pad=(10, 10))
        ]
    ]
    param_window = sg.Window('Select Flight', layout_config_TC)
    event, values = param_window.Read()
    param_window.Close()
    instrument = values['_param_'][0]
    print(instrument)
    print(event)

    if event == 'Submit':
        curl_cmnd(instrument, file_name, note)
Пример #12
0
def continue_anyway(issue):

    # Set-up the logger
    log = getLogger(f'{PROG}.{__name__}')
    log.debug('Received request to produce a "continue?" popup window.')

    # Provide a layout for our window
    logo_frame = [[Qt.Image('/home/taylor/Pictures/logo.png', key='img_elm')]]

    button_frame = [
            [Qt.Button('Yes')]
            ]

    main_layout = [
            [Qt.Frame('', layout=logo_frame, element_justification='center', size=(40, 40))],
            []
            ]

    window = Qt.Window('Continue Anyway?', layout=main_layout)


    while True:
        event, vals = window.read(timeout=100)



        if event is None or vals == 'exit':
            log.debug('User leaving window by click')
Пример #13
0
def _layout_(config):
    import PySimpleGUIQt as qt
    struct = [[qt.Menu(_top_menu_())], [qt.Text('Welcome to Test API!')],
              [qt.Combo(['Living Room', 'Playroom'])],
              [qt.Frame('', _sense_frame_(config))],
              [qt.Frame('', list(_button_frame_()))]]

    return struct
Пример #14
0
 def _bd_status_kw(self, index, height):
     return {
         "key": f"_STATUS_{index}_",
         "size": (self.width, height),
         "font": self.def_font,
         "text_color": sg.theme_element_text_color(),
         "background_color": sg.theme_element_background_color(),
     }
Пример #15
0
def load_parser(config_file):
    parser = ConfigParser()
    parser.optionxform = str
    try:
        parser.read(config_file)
    except Exception as e:
        sg.popup(f'Exception {e}', 'No config file found... will create one for you', keep_on_top=True, background_color='red', text_color='white')
    return parser
Пример #16
0
 def __init__(self):
     self.result = ""
     self.layout = [
         [sg.Text("Enter the linear equation"),
          sg.In(key="lneq")],
         [sg.Button("Evaluate", enable_events=True, key="eval")],
         [sg.Text("Result:"),
          sg.Text(text="", key="result")],
     ]
Пример #17
0
 def form_frame():
     _layout = [[
         qt.Text('Look & Feel: '),
         qt.Combo(qt.theme_list(),
                  enable_events=True,
                  key='look_and_feel_combo')
     ]]
     _frame = qt.Frame('Settings', _layout)
     return _frame
Пример #18
0
def rcloneoutputwindow(contents: []):
    output = ""
    for item in contents:
        output += item.name + "\n"
    layout = [[sg.Text("Here are the contents:")],
              [sg.MultilineOutput(output)], [sg.OK()]]
    window = sg.Window("Results", layout)
    window.Read()
    window.Close()
Пример #19
0
def sortoutputwindow(contents: [str]):
    output = ""
    for item in contents:
        output += item + "\n"
    layout = [[sg.Text("I have sorted these files:")],
              [sg.MultilineOutput(output)], [sg.OK()]]
    window = sg.Window("Results", layout)
    window.Read()
    window.Close()
Пример #20
0
    def render(self):
        sg.theme('dark')
        menu_def = [['File', [PREFERENCES_MENU]]]
        layout = [[sg.Menu(menu_def, background_color='white')],
                  [sg.Text(WELCOME_TEXT)],
                  [self.start_stop_button]]

        window = sg.Window("Captionizer", layout, element_padding=(16, 16))
        self._event_loop(window)
        window.close()
Пример #21
0
def start_dialog():
    left_frame = [[sg.Image(filename='', key='_IMAGE_')]]
    right_frame = [[sg.Image(filename='', key='_PERSON_')],
                   [sg.Text("Who is it?")], [sg.Input()],
                   [sg.Button('Capture')], [sg.Button('Quit')]]

    layout = [[sg.Frame("", left_frame), sg.Frame("", right_frame)]]

    window = sg.Window('Face recognition training centre', layout)

    cap = cv2.VideoCapture(0)
    ret, frame = cap.read()
    mirror = flipHorizontal = cv2.flip(frame, 1)
    while True:
        event, values = window.Read(timeout=20, timeout_key='timeout')
        if event is None or event == 'Quit':
            break
        if event == 'Capture':
            person_name = values[0]
            if person_name is not None and person_name != "":
                process_image(person_name, frame)

        ret, frame = cap.read()
        mirror = flipHorizontal = cv2.flip(frame, 1)

        imgbytes = cv2.imencode('.png', mirror)[1].tobytes()
        window.FindElement('_IMAGE_').Update(data=imgbytes)
        person_img = get_first_face(mirror, 200, 200)
        if person_img is not None:
            imgbytes = cv2.imencode('.png', person_img)[1].tobytes()
            window.FindElement('_PERSON_').Update(data=imgbytes)

    window.close()
    cap.release()
Пример #22
0
def gui_select_tracks(tracks: List[dict], start_time: int, config: dict) -> dict:
    chataigne_path_cfg = config.get("chataigneProjectPath")
    if not chataigne_path_cfg: chataigne_path_cfg = ""

    start_time_cfg = config.get("startTime")
    if not start_time_cfg: start_time_cfg = start_time

    tracks_cfg = config.get("tracks")
    if tracks_cfg is None: tracks_cfg = {}

    layout = [[sg.Text('Chataigne base project:')],
              [sg.Input(chataigne_path_cfg, key='-CH_PATH-'), sg.FileBrowse()],
              [sg.Text('Start time'), sg.Input(default_text=start_time_cfg, key='-START_TIME-')],
              [sg.Text('Select tracks, DMX channel')]]

    for i, track in enumerate(tracks):
        track_cfg = tracks_cfg.get(track["name"])

        if track_cfg is None:
            include = False
            dmx = None
        else:
            include = track_cfg["include"]
            dmx = track_cfg["dmx"]

        if dmx is None:
            dmx = ""

        layout.append(
            [sg.Checkbox(track["name"], default=include, key=f"-TRACK_{i}-"), sg.Input(dmx, key=f"-DMX_{i}-")])

    layout.append([sg.Submit("Convert selected tracks!", bind_return_key=True)])

    window = sg.Window('Select DMX tracks', layout)

    event, values = window.read()
    window.close()

    if event == None: exit()

    start_time_cfg = re.sub('[^0-9]', '', values["-START_TIME-"])
    start_time_cfg = int(start_time_cfg) if start_time_cfg else start_time

    config = {"chataigneProjectPath": values["-CH_PATH-"],
              "startTime": start_time_cfg,
              "tracks": {}}

    for i, track in enumerate(tracks):
        checked = values[f'-TRACK_{i}-']
        dmx = re.sub('[^0-9]', '', values[f'-DMX_{i}-'])
        dmx = int(dmx) if dmx else None
        config["tracks"][track["name"]] = {"include": checked, "dmx": dmx}

    return config
Пример #23
0
Файл: ip.py Проект: sg-ja/IP-GUI
def init_tray():
    global tray

    menu = ["BLANK", [
        "&Open",
        "---",
        "&Close",
    ]]
    try:
        tray = sg.SystemTray(menu=menu, tooltip="IP", data="favicon.png")
    except TypeError:
        tray = sg.SystemTray(menu=menu, tooltip="IP", filename="favicon.png")
Пример #24
0
    def window(self):
        if self.config is None:
            qt.theme('Dark2')
        else:
            qt.theme(self.config['GUI']['theme'])

        window = qt.Window('Settings - CoViD 19 Tracker',
                           layout=self.layout(),
                           icon=c_icon,
                           force_toplevel=True)

        return window
Пример #25
0
 def GraphColumn(name, key):
     col = sg.Column([[
         Txt(name, key=key + '_TXT_'),
     ],
                      [
                          sg.Graph((GRAPH_WIDTH, GRAPH_HEIGHT), (0, 0),
                                   (GRAPH_WIDTH, 100),
                                   background_color='black',
                                   key=key + '_GRAPH_')
                      ]],
                     pad=(2, 2))
     return col
Пример #26
0
def getInputOutputWindow(titletext="Select File"):
    layout = [[sg.Text('Input File')],
              [sg.Input(), sg.FileBrowse(initial_folder=home)],
              [sg.Text('Output File')],
              [sg.Input(), sg.FileSaveAs(initial_folder=home)],
              [sg.OK(), sg.Cancel()]]
    window = sg.Window(titletext, layout)
    event, values = window.Read()
    return event, values
Пример #27
0
def _button_frame_():
    """
    Create a frame for our buttons at the bottom of the window

    :returns: Button frame object
    :rtype:
    """
    import PySimpleGUIQt as qt
    b_frame = [[
        qt.Button('Make Another', key='dupe'),
        qt.Button('Exit', key='top_win_exit')
    ]]
    return b_frame
Пример #28
0
 def gui_setup(self):
     sg.change_look_and_feel('Black')  # emulate the hardware
     # All the stuff inside your window.
     layout = [
         [sg.Text('[ %s ]' % col, size=BTN_SIZE) for col in range(1, 9)],
         [self.round_button(col, 0) for col in range(8)],
     ]
     for rowid, row in enumerate(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']):
         layout += [
             [self.square_button(col, rowid+1) for col in range(8)] + [self.round_button(8, rowid+1)] + [sg.Text('[%s]' % row)]
         ]
     window = sg.Window('Launchpad Emulator', layout, finalize=True)
     return window
Пример #29
0
def save_config(config_file,parser,values):
    if values:
        for k,v in conf_keys.items():
            try:
                if parser.has_section(v[0]):
                    if parser.has_option(v[0], k):
                        parser.set(v[0],k,values[v[2]])
            except Exception as e:
                print(f'Problem updating config from window values. Key = {k}')

    with open(config_file, 'w') as conf_file:
        parser.write(conf_file)
    
    sg.popup('Configuration saved!')
Пример #30
0
    def on_eval_clicked(self, values):
        eval_path = values[self.cfg.uie.eval_key]
        if not eval_path:
            psg.popup(self.cfg.error.eval_missing.format("Eval Path (string)"))
            return None

        gt_path = values[self.cfg.uie.gt_key]
        if not gt_path:
            psg.popup(
                self.cfg.error.eval_missing.format(
                    "Ground Truth Path (string)"))
            return None

        return eval_path, gt_path