def tela_atualizacao(informacao_antiga): """ Tela para atualizar informações de um emprestimo já cadastrado. :param informacao_antiga: um dicionário contento todas as antigas informações do emprestimo. :return: uma lista de valores, contento o conteúdo dos InputText. """ layout = [ [Text("Atualizar emprestimo")], [ Text("Nome", size=(15, 1)), InputText(default_text=informacao_antiga['nome'], do_not_clear=True) ], [ Text("Telefone Fixo", size=(15, 1)), InputText(default_text=informacao_antiga['telefone'], do_not_clear=True) ], [ Text("Celular", size=(15, 1)), InputText(default_text=informacao_antiga['celular'], do_not_clear=True) ], [ Text("E-mail", size=(15, 1)), InputText(default_text=informacao_antiga['email'], do_not_clear=True) ], [ Text("De onde conhece", size=(15, 1)), InputText(default_text=informacao_antiga['vivencia'], do_not_clear=True) ], [ Text("Data", size=(15, 1)), InputText( default_text=informacao_antiga['data'].strftime("%d/%m/%Y"), do_not_clear=True) ], [ Text("Item", size=(15, 1)), InputText(default_text=informacao_antiga['item'], do_not_clear=True) ], [ Button("Atualizar", button_color=('white', 'springgreen4')), Cancel(button_text="Cancelar", button_color=('white', 'firebrick3')) ] ] janela = Window( "Cadastro", icon=('C:\\Loans-management\\Icon\\icon-logo.ico')).Layout(layout) botao, valores = janela.Read() print(valores) if botao == "Atualizar": janela.Close() return valores elif botao == 'Cancelar': janela.Close()
def tela_excluir(): """ Tela para confirmação da exclusão de um emprestimo. :return: um valor booleano, para confirmação ou negação da ação. """ layout = [[Text('Tem certeza que deseja excluir?')], [ Button("Sim", size=(8, 1), button_color=('white', 'springgreen4'), pad=(20, 1)), Button("Não", size=(8, 1), button_color=('white', 'firebrick3')) ]] janela = Window( 'Excluir', icon=('C:\\Loans-management\\Icon\\icon-logo.ico')).Layout(layout) botao, evento = janela.Read() if botao == 'Sim': janela.Close() return True else: janela.Close() return False
class DetalhesDoFuncionario(AbstractTela): def __init__(self, func): self.__validator = validator self.window = Window('Detalhes do funcionário') layout = [ [Text('Funcionário:')], ] veics = [] for veic in func.veiculos_cadastrados: veics.append([ Text( f' Placa: {veic.placa} - Marca: {veic.marca} - Modelo: {veic.modelo} ' ) ]) fields_out_of_validator = [ [Text((f'Bloqueado : {func.bloqueado}'))], [Text('Veiculos :')], ] + veics for k in self.__validator.keys(): repres = k.title( ) if k != 'data_nascimento' else 'Data de nascimento' layout.append([Text(f'{repres} : {getattr(func, k)}')]) layout += fields_out_of_validator layout.append([Button('Voltar')]) self.window.layout(layout)
def tela_escolha_busca(): """ Tela na qual o usuário escolhera qual o método de busca. :return: retorna uma string, sendo a escolha do usuário. """ layout_busca = [[T("Deseja buscar por:", size=(30, 1))], [ Button("Nome", button_color=('white', 'springgreen4'), size=(8, 1)), Button("Item", button_color=('white', 'springgreen4'), size=(8, 1)), Button("Ano", button_color=('white', 'springgreen4'), size=(8, 1)), Button("Mes + Ano", button_color=('white', 'springgreen4'), size=(10, 1)) ], [ Button("Cancelar", button_color=('white', 'firebrick3'), size=(8, 1), pad=(150, 0)) ]] janela_busca = Window( "Buscas", size=(400, 100), text_justification=('center'), icon=( 'C:\\Loans-management\\Icon\\icon-logo.ico')).Layout(layout_busca) botao_busca, valores_busca = janela_busca.Read() janela_busca.Close() return botao_busca
def CPU_thread(window: sg.Window): while True: cpu_percent = psutil.cpu_percent(interval=g_interval) procs = psutil.process_iter() window.write_event_value('-CPU UPDATE FROM THREAD-', (cpu_percent, procs))
def tela_cadastro(): """ Tela para cadastro de novo emprestimo. :return: uma lista contento as informações inputadas. """ layout = [[Text("Cadastrar emprestimo")], [Text("Nome", size=(15, 1)), InputText()], [Text("Telefone Fixo", size=(15, 1)), InputText()], [Text("Celular", size=(15, 1)), InputText()], [Text("E-mail", size=(15, 1)), InputText()], [Text("De onde conhece", size=(15, 1)), InputText()], [ Text("Data", size=(15, 1)), InputText("ex: dia/mês/ano", do_not_clear=False) ], [Text("Item", size=(15, 1)), InputText()], [ Button("Cadastrar", button_color=('white', 'springgreen4')), Cancel(button_text="Cancelar", button_color=('white', 'firebrick3')) ]] janela = Window( "Cadastro", disable_close=True, icon=('C:\\Loans-management\\Icon\\icon-logo.ico')).Layout(layout) botao, valores = janela.Read() if botao == "Cadastrar": janela.Close() return valores elif botao == 'Cancelar' or botao is None: janela.Close()
def __init__(self, field, value): self.__validator = validator self.window = Window('Atualiza funcionário') layout = [[ Text(f'Informe o/a {field} do funcionário:'), Input(key=field, default_text=value) ], [Button('Ok!'), Button('Manter')]] self.window.layout(layout)
def __init__(self, field): self.__validator = validator self.window = Window('Adiciona funcionário') layout = [[ Text(f'Informe o/a {field} do funcionário:'), Input(key=field) ], [Button('Ok!')]] self.window.layout(layout)
def run(self, constants: Constants, settings: {}, window: sg.Window, progress: sg.ProgressBar): thread = Thread(target=self.execute, args=(constants, settings, progress)) thread.start() while thread.is_alive(): window.read(1) thread.join()
def __init__(self, funcs): self.window = Window('Funcionários') layout = [ [Text('Funcionários:')], ] for func in funcs: layout.append([Text(f'{func.matricula} - {func.nome}')]) layout.append([Button('Voltar')]) self.window.layout(layout)
def update_bar_message(message: str, counter: int, window: sg.Window): """ Updates progress bar and output message, returns counter +1 """ msg = window["-MESSAGE-"] bar = window["-BAR-"] counter += 1 bar.update_bar(counter) msg.update(message) window.refresh() return counter
def the_thread(window: sg.Window): """ The thread that communicates with the application through the window's events. Because the figure creation time is greater than the GUI drawing time, it's safe to send a non-regulated stream of events without fear of overrunning the communication queue """ while True: fig = your_matplotlib_code() buf = draw_figure(fig) window.write_event_value( '-THREAD-', buf) # Data sent is a tuple of thread name and counter
def try_again(window: sg.Window): """Press [Enter] to try again""" QT_ENTER_KEY1 = "special 16777220" QT_ENTER_KEY2 = "special 16777221" while True: event, _ = window.read(timeout=20) if event in (sg.WIN_CLOSED, "Exit"): break elif event in ("Return:36", "\r", QT_ENTER_KEY1, QT_ENTER_KEY2): return window.close() exit(0)
def show_result(window: sg.Window, result: bool) -> None: """ Show the result as a file. """ if result: window.write_event_value( "-COMPARE RESULT-", [True, "text_face_compare_status", "SUCCESS", "green"], ) else: window.write_event_value( "-COMPARE RESULT-", [False, "text_face_compare_status", "FAILED", "red"], )
def add_packages_to_window(window: sg.Window): packages = sg.user_settings_get_entry('-packages-', []) for i, package in enumerate(packages): in_elem = window.find_element(('-ID-', i), silent_on_error=True) if isinstance(in_elem, sg.ErrorElement): window.metadata += 1 window.extend_layout(window['-TRACKING SECTION-'], [package_row(window.metadata)]) in_elem = window.find_element(('-ID-', window.metadata), silent_on_error=True) in_elem.update(package[0]) else: in_elem.update(package[0]) desc_elem = window.find_element(('-DESC-', i), silent_on_error=True) if not isinstance(desc_elem, sg.ErrorElement): desc_elem.update(package[1])
def __init__(self, user): self.window = Window('Alterar senha').layout( [[Text(f'Senha atual: '), Input(key='old_password')], [Text('Nova senha: '), Input(key='password')], [Button('Voltar'), Button('Confirmar')]])
def process_click(type: int, coord: tuple, env_process: EnvProcess, window: Window): x, y = coord ant: Agent x_offset = min(env_process.borders[1][0], env_process.borders[0][0]) y_offset = min(env_process.borders[1][1], env_process.borders[0][1]) for i, ant in enumerate(env_process.ants): size = distance(ant.triangle.center, ant.triangle.top) ax, ay = ant.xy ax += x_offset ay += y_offset if (ax - (size / 2)) <= x <= (ax + (size / 2)) and ( ay - (size / 2)) <= y <= (ay + (size / 2)): window["agent-column"].metadata = i return if (x_offset < x < max(env_process.borders[1][0], env_process.borders[0][0]) and y_offset < y < max(env_process.borders[1][1], env_process.borders[0][1])): if window["GRAPH-BOX"].metadata == "activated": if type is 2: env_process.boxes.append( Box((x - x_offset, y - y_offset), len(env_process.boxes))) elif window["GRAPH-WALL"].metadata == "activated": if type == 1: window.metadata["tempPos"] = (x - x_offset, y - y_offset) else: env_process.walls.append( Wall(window.metadata["tempPos"], (x - x_offset, y - y_offset), len(env_process.walls))) else: env_process.pheromones.append( Pheromone(x - x_offset, y - y_offset, 5, b"0x12"))
def accept_deny(window: sg.Window) -> bool: """Press [Enter] to accept image, [Escape] to try again""" QT_ENTER_KEY1 = "special 16777220" QT_ENTER_KEY2 = "special 16777221" while True: event, _ = window.read(timeout=20) if event in (sg.WIN_CLOSED, "Exit"): break elif event in ("Return:36", "\r", QT_ENTER_KEY1, QT_ENTER_KEY2): window["text_instruction"].update("", text_color="white") return True elif event.startswith("Escape"): return False window.close() exit(0)
def w_total_event(self, window: sg.Window, new: int): w = self.quest['wave'] old, w['total'] = w['total'], new if old > new: # fewer for N in map(str, range(new + 1, old + 1)): window[f'{self.__prefix_key}_wave{N}_auto_'].hide_row() del w[N], window.AllKeysDict[f'{self.__prefix_key}_wave{N}_auto_'] del window.AllKeysDict[f'{self.__prefix_key}_wave{N}_sp_weight_enable_'] for p in pos: del window.AllKeysDict[f'{self.__prefix_key}_wave{N}_character_{p}_skill_priority_'], del window.AllKeysDict[f'{self.__prefix_key}_wave{N}_character_{p}_sp_weight_'] elif old < new: uData.padding_wave(w) for N in map(str, range(old + 1, new + 1)): window.extend_layout(window[f'{self.__prefix_key}_wave_frame_'], self.__a_wave_row(w, N))
def __init__(self, _list): layout = [] for item in _list.items.values(): layout += [ [Button(f'{item.title}')], ] self.window = Window('Selecione um item').layout(layout + [[Button('Voltar')]])
def __init__(self, user): self.window = Window('Minha conta').layout( [[Text(f'Usuário: {user.username}')], [Text(f'Senha: {user.password}')], [Text(f'Data inserção: {user.date}')], [Button('Alterar senha')], [Button('Voltar'), Button('Trocar Conta'), Button('Excluir')]])
def Signup(self): signup_active = True layout = [ [T("Signup for Xpnsit", **heading_format), ], [T("First Name:"), Input(size=(15, 1), key="f_name"), T( " "), T("Last Name:"), Input(size=(15, 1), key="l_name")], [T("Username:"******"user")], [T("Password:"******"pass", password_char="*")], [], [T(' '*40), Submit()] ] signup_win = Window("Xpnsit - Signup", layout=layout) while signup_active: # <------------ Event Loop -----------------> # event, values = signup_win.Read() if event in (None, 'Exit'): signup_active = False login_active = True if event == 'Submit': self.vals = [values["user"], values["pass"], values["mail"], values["f_name"], values["l_name"]] if not username_used(self.vals[0]): create_account(*self.vals) # <------------------- Confirmation of Insertion ------------------> # success = check_login_info(values["user"], values["pass"]) if success == True: print("Signup Successful.") Popup( "Signup Successful!", "Exit this popup to return to the login page" ) signup_win.close() signup_active = False login_active = True else: PopupError("ERROR: Username already in usage", title="Username already taken")
def __init__(self): layout = [ [Text('O que você quer fazer?')], [Text('Gerenciar funcionários'), Button('0')], [Text('Gerenciar veículos'), Button('1')], [Text('Gerenciar movimentações'), Button('2')], [Button('Sair')] ] self.window = Window('Claviculário Eletrônico').Layout(layout)
def run(self, window: Window, fields: list) -> map: """ This method control the logic of load records selection window Args: window: the window contains the table fields: the fields that need to be get Returns: a map that contains selected record data """ "" info = window.Element('_OR_TABLE_').get()[self.values["_OR_TABLE_"][0]] window.close() i = 0 for each in fields: self.record[each] = info[i] i += 1 return self.record
def the_thread(window:sg.Window, seconds): """ The thread that communicates with the application through the window's events. Wakes every X seconds that are provided by user in the main GUI: Sends an event to the main thread Goes back to sleep """ i = 0 while True: time.sleep(seconds) # send a message to the main GUI. It will be read using window.read() # the "Value" send is a tuple that contains all the things to show in the popup window.write_event_value('-POPUP-', ('Hello this is the thread...', f'My counter is {i}', f'Will send another message in {seconds} seconds')) i += 1
def firstTest(temperature : int, m : SimpleNamespace, w : sg.Window): assert(temperature == 25 or temperature == 45) attenuation = ATTENUATION m.ardq.put( ArduinoMessage.TEMPERATURE({ 25: temp_bassa, 45: temp_alta }[temperature])) while attenuation >= 0: if attenuation in m.collected_data.diretta[temperature].keys(): attenuation -= 1 continue else: break # I dati sono gia' stati raccolti if attenuation < 0: return True if not sendCommand( WorkMessage.SEND("Set_ATT,{:.2f}".format(attenuation)), m, w): w[Id.STATUS].Update("Errore di comunicazione!") return False if not sg.Popup( "Verifica carico 500HM correttamente inserito e temperatura impostata {:.2f} C" .format(temperature), keep_on_top=True, title="Attenzione!"): w[Id.STATUS].Update("Procedura interrotta!") return False while attenuation >= 0: if readings := readParameters(temperature, m, w): _, values = w.Read(timeout=0) k = float(values[Id.K]) adjusted = .5 * ((readings[0] * k) / .5) adjusted = adjustPopup(adjusted) m.collected_data.diretta[temperature][attenuation] = [ readings[1], readings[3], adjusted ] else: return False if attenuation <= 0: break attenuation -= 1 if not sendCommand( WorkMessage.SEND("Set_ATT,{:.2f}".format(attenuation)), m, w): w[Id.STATUS].Update("Errore di comunicazione!") return False
def __init__(self, genres): self.window = Window('Criar meta').layout( [[Text('Prazo: '), Input(key='prazo'), Text(' dias')], [Text('Objetivo: '), Input(key='objetivo'), Text(' obras')], [Text('Genero: '), Combo(genres, key='genre')], [Button('Voltar'), Button('Criar meta')]])
def w_skill_priority_event(self, window: sg.Window, key: str, value: str): N = key[5] current_list = list(filter(lambda e: e != '', value.split(' > '))) available_list = [sk for sk in sk_list if sk not in current_list] current_list = priority_GUI('skill', key.replace('_', ' ').strip(), current_list, available_list, sk_list, window.mouse_location()).open() if current_list is not None: p = key[17:key.index('_', 17)] self.quest['wave'][N][f'character_{p}']['skill_priority'] = current_list if current_list != ['Same as Wave1'] else self.quest['wave']['1'][f'character_{p}']['skill_priority'] # noqa: E501 window[f'{self.__prefix_key}{key}'].Update(' > '.join(self.quest['wave'][N][f'character_{p}']['skill_priority']))
def ah_read(ah: ArtsHandler, event: str, values: ValuesType, serialized: ValuesType, ls: LoopSlicerGui, load_values: bool, window: sg.Window) -> ty.Tuple[ArtsHandler, sg.Window]: ah_read_ret = ah.read(event, values) if isinstance(ah_read_ret, tuple) and isinstance(ah_read_ret[0], ty.List): ah = ArtsHandler(tabs_layout=ah_read_ret[0], arts_instances=ah_read_ret[1]) ls = LoopSlicerGui() if serialized is not None: rpr.Project().set_ext_state(GUI_SECTION, GUI_KEY, serialized, pickled=True) wind1 = _make_window(ls, ah, load_values) window.close() window = wind1 else: check_for_exception(ah_read_ret) # type:ignore return ah, window
def settings(window: sg.Window): layout = [ [sg.T(f'Screen size = {sg.Window.get_screen_size()}')], [ sg. T(f'Your launcher is currently located at {window.current_location()}' ) ], [ sg. T('Enable autosave and position your window where you want it to appear next time you run.' ) ], [ sg.T('Your Screen Background Color'), sg.In(sg.user_settings_get_entry('-screen color-', DEFAULT_SCREEN_BACKGROUND_COLOR), s=15, k='-SCREEN COLOR-') ], [ sg.CBox('Autosave Location on Exit', default=sg.user_settings_get_entry('-auto save location-', True), k='-AUTO SAVE LOCATION-') ], [ sg.CBox('Keep launcher on top', default=sg.user_settings_get_entry('-keep on top-', True), k='-KEEP ON TOP-') ], [sg.OK(), sg.Cancel()] ] event, values = sg.Window('Settings', layout).read(close=True) if event == 'OK': sg.user_settings_set_entry('-auto save location-', values['-AUTO SAVE LOCATION-']) sg.user_settings_set_entry('-keep on top-', values['-KEEP ON TOP-']) sg.user_settings_set_entry('-screen color-', values['-SCREEN COLOR-']) if values['-KEEP ON TOP-']: window.keep_on_top_set() else: window.keep_on_top_clear()