示例#1
0
 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()
示例#2
0
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 selectComPort(window: sg.Window):
    setStatus(window, "Select COM Port")
    while (True):
        event, values = window.read()
        if event == 'COMPORT':
            portName = values['COMPORT']
            ser = openComPort(portName)
            if ser is not None:
                setStatus(window, "%s open" % portName)
                return ser
            else:
                setStatus(window, "UNABLE to open %s" % portName)
        elif event in (None, 'Exit'):
            return None
示例#4
0
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)
示例#5
0
def run(window: Window):
    while True:
        event, values = window.read()

        if event in [WIN_CLOSED, 'Exit']:
            break
        elif event == team_clear_one.Key:
            team_choice_one.Update('')
        elif event == team_clear_two.Key:
            team_choice_two.Update('')
        elif event == event_clear.Key:
            event_choice.Update('')
        elif event == h2h_submit.Key:
            run_head_to_head(values)
        elif event == team_analysis_submit.Key:
            run_team_analysis(values)
        elif event == performance_analysis_submit.Key:
            run_performance_analysis(values)
        elif event in [
                aggregated_sequences_submit.Key, season_sequences_submit.Key
        ]:
            run_sequences(values, event)
        elif event == heatmap_submit.Key:
            run_heatmap_analysis(values)
        elif event == event_matrix_submit.Key:
            run_event_matrix_analysis(values)
        elif event == league_analysis_submit.Key:
            run_league_analysis(values)
        elif event in [performance_individual.Key, performance_average.Key]:
            performance_positions_choice.update(disabled=True)
            performance_relative_choice.update(disabled=True)
        elif event == performance_positions.Key:
            performance_positions_choice.update(disabled=False)
            performance_relative_choice.update(disabled=True)
        elif event == performance_relative.Key:
            performance_positions_choice.update(disabled=True)
            performance_relative_choice.update(disabled=False)
        elif event == team_analysis_summary.Key:
            team_analysis_game_states.update(disabled=False)
        elif event in [
                team_analysis_form.Key, team_analysis_margins.Key,
                team_analysis_goals.Key
        ]:
            team_analysis_game_states.update(disabled=True)
        elif event == expression.Key:
            run_expression_evaluation(values)
def evaluateUI(window: sg.Window, ser: Serial):
    event, values = window.read(1000)
    print(event, values)
    if event in (None, 'Exit'):
        return -1, CMD_ID.cmd_none
    elif event == 'COMPORT':
        return 2, CMD_ID.cmd_none
    elif event == 'RED' or event == 'GREEN' or event == 'BLUE':
        # if there was a slider event, make sure to update and
        # return the necessary command (blinking or steady)
        if window['CMD_STEADY'].Get() is True:
            return 1, CMD_ID.cmd_steady
        else:
            return 1, CMD_ID.cmd_blink
    elif event == 'CMD_STEADY':
        return 1, CMD_ID.cmd_steady
    elif event == 'CMD_BLINK':
        return 1, CMD_ID.cmd_blink
    elif event == 'CMD_ALL_ON':
        # update state of the radio buttons and sliders
        window['CMD_STEADY'].Update(True)
        window['RED'].Update(255)
        window['GREEN'].Update(255)
        window['BLUE'].Update(255)
        window.Refresh()
        return 1, CMD_ID.cmd_all_on
    elif event == 'CMD_ALL_OFF':
        # update state of the radio buttons and sliders
        window['CMD_STEADY'].Update(True)
        window['RED'].Update(0)
        window['GREEN'].Update(0)
        window['BLUE'].Update(0)
        window.Refresh()
        return 1, CMD_ID.cmd_all_off
    else:
        return 0, CMD_ID.cmd_none
示例#7
0
def camera_mode(
    window: sg.Window,
    q: Queue,
    q2: Queue,
    lock2: threading.Lock,
    event: str,
    values: Union[Dict[Any, Any]],
):
    """A new GUI loop for camera mode, wait for Enter and Escape buttons"""
    QT_ENTER_KEY1 = "special 16777220"
    QT_ENTER_KEY2 = "special 16777221"
    while True:
        event, values = window.read(timeout=20)
        if event in (sg.WIN_CLOSED, "Exit"):
            break
        if event == "-SHOW CAMERA-":
            window["camera_image"].update(data=values[event][0])
            nm_faces = values[event][1]
        if (event in values and isinstance(values[event], list)
                and isinstance(values[event][0], bool) and values[event][0]):
            window[values[event][1]].update(values[event][2],
                                            text_color=values[event][3])
        elif (event in ("Return:36", "\r", QT_ENTER_KEY1,
                        QT_ENTER_KEY2)) and nm_faces > 1:
            window["text_instruction"].update(
                "Multiple faces detected. Press [Enter] to try again",
                text_color="white")
            # q.put("Pause")
            # try_again(window)
            # q.put("Continue")
        elif (event in ("Return:36", "\r", QT_ENTER_KEY1,
                        QT_ENTER_KEY2)) and nm_faces < 1:
            window["text_instruction"].update(
                "No faces detected. Press [Enter] to try again",
                text_color="white")
        elif (event in ("Return:36", "\r", QT_ENTER_KEY1,
                        QT_ENTER_KEY2)) and nm_faces == 1:
            window["text_instruction"].update(
                "Press [Enter] to accept image, [Escape] to try again",
                text_color="white")
            exit_outer_loop = False
            wait_for_signal = False
            while True:
                # The order of this if clause is important!
                if not wait_for_signal and lock2.acquire(False):
                    if accept_deny(window):
                        q.put("Done")
                        wait_for_signal = True
                        lock2.release()
                    else:
                        window["text_instruction"].update(
                            "Press [Enter] to capture image",
                            text_color="white")
                        lock2.release()
                        break
                elif wait_for_signal and not q2.empty():
                    q2.get()
                    return
                event, values = window.read(timeout=20)
                if event in (sg.WIN_CLOSED, "Exit"):
                    exit_outer_loop = True
                    break
                if event == "-SHOW CAMERA-":
                    window["camera_image"].update(data=values[event][0])
                    nm_faces = values[event][1]

            if exit_outer_loop:
                break
    window.close()
    exit(0)
示例#8
0
def handle_events(window: sg.Window):
    while True:
        event, values = window.read()
        window["-PROGRESS-"].Update(0, 0, False)
        status = ''
        if event == "Exit" or event == sg.WIN_CLOSED:
            break

        try:
            # Folder name was filled in, make a list of files in the folder
            if event == "-FOLDER-":
                change_buttons_disabled_state(window, True)

                folder = values["-FOLDER-"]
                if not folder:
                    continue

                # Get list of files in folder
                logging.info('Folder selected:' + folder)
                folder = Path(folder)
                window["-FILE LIST-"].update([f.name for f in get_img_file_in_folder(folder)], disabled=False)
                window["-TNEW_DATE-"].update(disabled=False)
                window["-BEDIT_DATE-"].update(disabled=False)
                window["-BUPDATE_ALL_DIR-"].update(disabled=False)

            elif event == '-BUPDATE-' or event == '-BUPDATE_SEL_NEXT-':
                new_date = values["-TNEW_DATE-"]
                new_date = guess_date_from_string(new_date, values['-DATE_PATTERN-'])
                selected_files = values["-FILE LIST-"]
                if len(selected_files) != 1:
                    raise LookupError("select one file")

                filepath = Path(values["-FOLDER-"]) / selected_files[0]
                write_new_date(filepath, new_date)
                status = 'Success'

                if event == '-BUPDATE_SEL_NEXT-':
                    files: sg.Listbox = window["-FILE LIST-"]
                    next_idx = files.GetIndexes()[0]
                    next_idx = next_idx + 1
                    if next_idx >= len(files.GetListValues()):
                        next_idx = 0
                    logging.info('select next list element:' + str(next_idx))
                    files.Update(set_to_index=next_idx)

            elif event == '-BUPDATE_ALL_DIR-':
                new_date = values["-TNEW_DATE-"]
                new_date = guess_date_from_string(new_date, values['-DATE_PATTERN-'])

                files = get_img_file_in_folder(Path(values["-FOLDER-"]))
                progress_bar: sg.ProgressBar = window["-PROGRESS-"]
                curr_progress = 0
                progress_bar.Update(curr_progress, len(files), True)
                for filepath in files:
                    write_new_date(filepath, new_date)
                    curr_progress = curr_progress + 1
                    progress_bar.UpdateBar(curr_progress)
                status = 'Success'

            elif event == '-BUPDATE_ALL_SELECTED-':
                new_date = values["-TNEW_DATE-"]
                new_date = guess_date_from_string(new_date, values['-DATE_PATTERN-'])

                files = [Path(values["-FOLDER-"]) / f for f in values["-FILE LIST-"]]
                progress_bar: sg.ProgressBar = window["-PROGRESS-"]
                curr_progress = 0
                progress_bar.Update(curr_progress, len(files), True)
                for filepath in files:
                    write_new_date(filepath, new_date)
                    curr_progress = curr_progress + 1
                    progress_bar.UpdateBar(curr_progress)
                status = 'Success'

            if (event == "-FILE LIST-" or event.startswith('-BUPDATE')) and window["-FILE LIST-"].GetIndexes():
                change_buttons_disabled_state(window, False)
                files: sg.Listbox = window["-FILE LIST-"]
                filepath = Path(values["-FOLDER-"]) / files.GetListValues()[files.GetIndexes()[0]]
                logging.info('File selected: ' + str(filepath))
                window["-TFILEPATH-"].update(filepath.name)

                try:
                    guess_date = guess_date_from_string(filepath.stem, values['-DATE_PATTERN-'])
                    window["-TNEW_DATE-"].update(guess_date)
                except ValueError:
                    pass

                exif_date = 'No exif date'
                exif_date_original = exif_date
                exif_date_digitalized = exif_date
                try:
                    with open(filepath, 'rb') as image_file:
                        my_image = Image(image_file)

                        if my_image.has_exif:
                            exif_date = datetime.strptime(my_image['datetime'], DATETIME_STR_FORMAT)
                            exif_date_original = datetime.strptime(my_image['datetime_original'], DATETIME_STR_FORMAT)
                            exif_date_digitalized = datetime.strptime(my_image['datetime_digitized'], DATETIME_STR_FORMAT)
                except AttributeError as e:
                    logging.warning(str(e))
                finally:
                    window["-TEXIF_DATE-"].update(exif_date)
                    window["-TEXIF_DATE_ORIGINAL-"].update(exif_date_original)
                    window["-TEXIF_DATE_DIGITALIZED-"].update(exif_date_digitalized)

        except Exception as e:
            tb_init = e.__traceback__
            tb = tb_init.tb_next
            tb_lineno = tb_init.tb_lineno
            while tb is not None and tb.tb_frame.f_code.co_filename == tb_init.tb_frame.f_code.co_filename:  # as long as we are in this file
                tb_lineno = tb.tb_lineno
                tb = tb.tb_next
            msg = str(tb_lineno) + ': ' + str(type(e)) + ' ' + str(e)
            logging.warning('Got Exception: ' + msg)
            window["-STATUS-"].update('Error ' + msg)
        else:
            window["-STATUS-"].update(status)
示例#9
0
    )
]])

layout = [main_title_col, [col1, col2], [col3, col4]]

# Create the Window
main_window = Window(' Bloom Filter & Password Strength Checker', layout)

redundency_count = 0
false_positive = 0

# set default values of the bfilters.

# Event Loop to process "events"
while True:
    event, values = main_window.read()
    if event == sg.WIN_CLOSED:
        break
    elif event == 'Enter':
        Array_size = int(values['-K-'])
        sizeofhashs = int(values['-N-'])
        if Array_size > 0 and sizeofhashs > 0:
            bloomf = BloomFilter(Array_size, sizeofhashs)
            confirm = sg.PopupOKCancel(
                "Are you sure you want to change\Add filter parameters?\nThis operation resets the filters and dictionaries",
                title='Confirm')
            sg.PopupOKCancel("Update successfully")
            if confirm == 'OK':
                redundency_count = 0
                false_positive = 0
            else:
示例#10
0

def evolve(population, iterations):
    for i in range(iterations):
        best_creature, best_score = get_best_from_pop(population)
        # print(best_creature, best_score)
        population = [mutate(best_creature)
                      for i in range(9)] + [best_creature]

    foo(best_creature[0], best_creature[1], best_creature[2], best_creature[3],
        best_creature[4], best_creature[5])
    print('%.2E' % Decimal(str(best_score)))


while True:
    event, values = window.read()
    d.value = 8
    if event == "Evolve":
        # genetic algo part

        current_creatures = [[
            values[2], values[3], values[4], values[5], values[6], values[7]
        ]] * 20
        evolve(current_creatures, 1000)
    else:
        # os.system("cd ~/Desktop;python3 untitled2.py 20")
        print('%.2E' % Decimal(
            str(
                foo(values[2], values[3], values[4], values[5], values[6],
                    values[7]))))
    img.update('foo.png')
示例#11
0
     Column(top_bar_layout, visible=False, key='-TOP_BAR-'),
     Column(my_profile_layout, visible=False, key='-MY_PROFILE-'),
     Column(feed_layout, visible=False, key='-FEED-')]
]

window = Window('CaliGoals', layout)

# ----- events -----#
#
# start_time = time_as_int()
# current_time, paused_time, paused = 0, 0, False

f_window_active = False
click_friend = False
while True:
    event, values = window.read(timeout=100)

    if event == sg.WIN_CLOSED:
        break

    elif event == 'Friends':
        print("clicked on friends")

    # if statements for switching pages
    elif event == 'Enter':
        user = values['-USERNAME-']
        password = values['-PASSWORD-']

        try:
            user_id = back.login((user, password))
            window['-PFP-'].update(image_filename=back.getProfilePicture(user_id))
def getSliderValues(window: sg.Window):
    event, values = window.read(0)
    return values['RED'], values['GREEN'], values['BLUE']
示例#13
0
class Xpnsit:
    
    def __init__(self):
        self.app_state: bool = True
    # <------------------- Misc. Functions (Layouts and Updaters and stuff) --------------------> #

    def Add_Trans(self, particulars: str, _type: str, amount: float, date: str):
        cursor = conn.cursor()

        try:
            cursor.execute(f"""
            INSERT INTO transactions (
                user_id,
                username,
                particulars,
                exp_type,
                amount,
                exp_date
            )
            VALUES (
                {self.user.user_id},
                '{self.user.uname}',
                '{particulars}',
                '{_type}',
                {amount},
                "{date}"
                );
            """)

            conn.commit()

            Popup("Transaction successfully added.")
            self.win.Refresh()

        except SQLErrors.ProgrammingError:
            PopupError("ERROR: Invalid details.\nRectify and try again.")

        cursor.close()

    def Create_Add_Trans_Layout(self):
        layout = [
            [T("New Transaction", font=("Helvetica", 18))],
            [T("NOTE:", font=("Helvetica", 20)), T(
                "All fields are required to be filled.")],
            [T("Particulars:"), Multiline("Enter details of transaction",
                                          autoscroll=True, key="Particulars")],
            [T("Transaction type:"), Combo(["Select", "Credit", "Debit"],
                                           "Select", readonly=True, key="new_type")],
            [T("Amount:"), Input(enable_events=True, key="amount")],
            [T("Date Of Transaction:"), Input("YYYY-MM-DD or use the button on the right",
                                              key="date"), CalendarButton("Select Date", target="date", format="%Y-%m-%d")],
            [Submit()]
        ]

        return layout

    def History(self):
        history_values, table, no_of_records = get_transactions(
            self.user.uname)

        self.slider = sg.Slider(
            range=(0, no_of_records),
            default_value=no_of_records,
            orientation='h',
            enable_events=True,
            key='slider'
        )

        layout = [
            [T("Transaction History", font=("Helvetica", 18))],
            [T("All your transactions, in one place. Right click any one to delete or edit it.")],
            [T('Number of records to be shown:'), self.slider],
            [T("Show records from "),
             Input(f"{year}-{month}-1", key="start_date", size=(10, 1)),
             CalendarButton("Start date", target="start_date", default_date_m_d_y=(
                 month, 1, year), button_color=("white", "green"), format="%Y-%m-%d"),
             T("to"),
             Input(f"{year}-{month}-{day}", key="end_date", size=(10, 1)),
             CalendarButton("End date", target="end_date", default_date_m_d_y=(
                 month, day, year), button_color=("white", "red"), format="%Y-%m-%d")
             ],
            [T("Type:"), Combo(["All", "Credit", "Debit"],
                               default_value="All", key="used_type", readonly=True)],
            [T("Sort by:"), Combo(["Name", "Amount", "Date of Transaction"],
                                  default_value="Name", key="sort_by", readonly=True), Combo(["Ascending", "Descending"], default_value="Ascending", key="asc_or_desc", readonly=True)],
            [table, Button("Refresh", button_color=(
                "white", "orange"), bind_return_key=True, key="refresh")],


        ]
        self.history_active = True

        return layout

    def update_table(self):
        start, end = self.values['start_date'], self.values["end_date"]
        aod = 'ASC' if self.values["asc_or_desc"] == "Ascending" else "DESC"
        sort = "particulars" if self.values["sort_by"] == "Name" else "amount" if self.values["sort_by"] == "Amount" else "exp_date"
        n = self.values["slider"] if self.event == 'slider' else 10000
        new_trans, new_table, new_number_of_trans = get_transactions(
            self.user.user_id,
            int(n),
            start,
            end,
            aod,  # a(scending)o(r)d(escending)
            sort
        )
        print(new_trans, new_table, new_number_of_trans)

        self.win["table"].Update(new_trans)  # Updates table

        # Updates max number of records to be possibly displayed
        self.win["slider"].Update(range=(0, new_number_of_trans+1))

        # Updates the default value of the slider to be the max
        self.slider.Update(value=new_number_of_trans)

        self.win.Refresh()

    def create_graph(self):

        fig, w, h = get_graph_values(
            self.values['a_start_date'],
            self.values['a_end_date'],
            self.values["a_type"],
        )
        self.figure_agg = draw_figure(
            self.win['canvas'].TKCanvas, fig)
    # <------------------ Main Screens --------------------> #

    def Login(self):
        login_active = True
        layout = [
            [T("Xpnsit", **heading_format)],
            [T("Username:"******"user")],
            [T("Password:"******"pass", password_char='*')],
            [Button("Login", bind_return_key=True), Button("Signup")]
        ]

        win = Window("Xpnsit", layout=layout)

        while login_active:  # <------------ Event Loop -----------------> #
            event, values = win.Read()

            if event is None:
                print("Exiting event loop")
                login_active = False
                self.app_state = False
                win.close()
                del win
                break

            if event == "Login":
                success = check_login_info(values["user"], values["pass"])

                if success == True:
                    print("Login Successful.")

                    self.user_details = get_user_details(values["user"])
                    self.user = NewUser(*self.user_details)

                    win.close()

                    self.Interface()
                    login_active = False
                else:
                    PopupError(
                        "ERROR: Username or password incorrect.\nPlease try again.")

            if event == "Signup":
                self.Signup()

    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 Dashboard(self):
        income, expenses = get_income_and_expense(self.user.uname)

        if (income, expenses) == (None, None):
            dash_layout = [
                [T(f"Welcome {self.user.first_name}")],
                [T("Looks like you have no transactions!\nGo add one in the Transactions tab.",
                   justification="center")],
                [T("-"*60, text_color="gray")],
            ]
        else:
            dash_layout = [
                [T(f"Welcome {self.user.first_name}")],
                [T(f"Your expenses for {month_name}-{year} are:"),
                 T(str(expenses), font=("Arial", 20))],
                [T(f"Your income for {month_name}-{year} is:"),
                 T(str(income), font=("Arial", 20))],
                [T("-"*80, text_color="gray")],
                [T("Net Profit/Loss:", font=("Segoe", 18)),
                 T(str(income-expenses), font=("Arial", 24))]
            ]

        dash_active = True

        return dash_layout

    def Transactions(self):
        transaction_layout = [
            [T("Transactions", font=("Helvetica", 18))],
            [TabGroup(
                [
                    [Tab("New Transaction", self.Create_Add_Trans_Layout())],
                    [Tab("History", self.History())]
                ]
            )]
        ]

        return transaction_layout

    def Analytics(self):
        fig, w, h = get_graph_values()


        analysis_layout = [
            [T("Analytics", font=("Helvetica", 18))],
            [T("Here you can find and generate graphs for your desired timeframe\nand observe trends in your balance.")],
            [T("Generate for records from "),
             Input(f"{year}-{month}-1", key="a_start_date", size=(10, 1)),
             CalendarButton("Start date", target="a_start_date", default_date_m_d_y=(
                 month, 1, year), button_color=("white", "green"), format="%Y-%m-%d"),
             T("to"),
             Input(f"{year}-{month}-{day}", key="a_end_date", size=(10, 1)),
             CalendarButton("End date", target="a_end_date", default_date_m_d_y=(
                 month, day, year), button_color=("white", "red"), format="%Y-%m-%d")
             ],
            [T("Type:"), Combo(["All", "Credit", "Debit"],
                               default_value="All", key="a_type", readonly=True)],
            [Button("Generate", button_color=("white", "orange"))],
            [Canvas(size=(w, h), key="canvas")]
        ]

        return analysis_layout

    def Interface(self):
        global graph_active


        layout = [
            [T("Xpnsit", **heading_format), T(" "*50), Button("Settings"),
             Button("Log Out", button_color=("black", "yellow"))],
            [TabGroup([
                [
                    Tab("Dashboard", self.Dashboard(
                    ), tooltip="See an overview of your account", font=("Arial", 12)),
                    Tab("Transactions", self.Transactions(
                    ), tooltip="View,add and delete transactions", font=("Arial", 12), key="transactions"),
                    Tab("Analytics", self.Analytics(
                    ), tooltip="Get a graphical insight to your spendings.", font=("Arial", 12))
                ]
            ],)]
        ]

        self.win = Window("Xpnsit v1.0", layout=layout, size = (590,640),resizable=True)
        while True:
            self.event, self.values = self.win.Read()
            self.figure_agg = self.create_graph()

            if self.event == "Log Out":
                logout = PopupYesNo("Are you sure you want to log out?")

                if logout == 'Yes':
                    sg.popup_quick_message(
                        "Okay, closing. Bye", auto_close_duration=10)
                    self.win.close()
                    # self.app_state = False
                    del self.win
                    break
            elif self.event is None:
                self.win.close()
                self.app_state = False
                del self.win
                break

            if self.event != sg.TIMEOUT_KEY:
                print(f"Event = {self.event}\nValues = {self.values}\n")


            if self.event == "Submit":
                _type = "CR" if self.values["new_type"] in (
                    "Credit", "Select") else "DR"
                self.Add_Trans(
                    self.values["Particulars"],
                    _type,
                    self.values["amount"],
                    self.values["date"])

            if self.event in ("slider", "refresh"):

                self.update_table()
                self.win.refresh()

            if self.event == "Generate":
                # self.create_graph()
                delete_figure_agg(self.figure_agg)
                self.create_graph()
                self.win.read()
                self.win.refresh()
示例#14
0
def gui_main_loop(log: my_logger.LogWrapper, sender_profiles,
                  window: sg.Window, state: types.SimpleNamespace,
                  user_settings_file, log_output_filter,
                  send_desktop_notification, name_to_license: dict):
    args: Args = None

    # printer = OnlyPrintOnDiff()
    # _print = lambda *args, **kwargs: printer.print(*args, **kwargs)
    # _print = lambda *args, **kwargs: None

    status_text_format_ok = {"background_color": "green"}
    status_text_format_warning = {"background_color": "red"}
    old_scoredata = state.scoredata

    log.debug("Starting main gui loop")
    window["general_error_message"].update(visible=False)

    # Set True during development to show the warnings in the status bar
    test_show = False
    if test_show:
        window["general_error_message"].update(visible=True)

    state.timer.start("loop")
    while not state.done:
        event, values = window.read(10)

        state.timer.start("handle events")
        handle_events(log, user_settings_file, state, event, window, values,
                      name_to_license)
        state.timer.stop("handle events")

        if state.done:
            log.debug("state.done is True, breaking from main loop")
            break

        # Not sure on order of update_settings and handle_events
        # Update the state.settings dict
        update_settings(state.settings, values, log_output_filter)

        # Set a bool toggling whether desktop error notifications are enabled
        state.desktop_error_notifications = values[
            "desktop_error_notifications"]

        # Toggle logs folder gui input elements based on the toggle
        window["logs_folder_selected"].update(
            visible=state.settings["logs_folder_toggle"])
        window["logs_folder_selector"].update(
            visible=state.settings["logs_folder_toggle"])

        # https://github.com/PySimpleGUI/PySimpleGUI/issues/1964
        # Make it so that the FolderBrowse initial folder is set correctly
        # This is a class level variable, so be careful if add in another folder selector
        window["logs_folder_selector"].InitialFolder = state.settings[
            "logs_folder"]
        window["spreadsheet_selector"].InitialFolder = \
            os.path.dirname(state.settings["spreadsheet_path"])

        state.timer.start("running")
        if state.do_run:
            log.info("Program restarting backend")
            stop_running(state)
            if args is not None:
                args.close()
            args = setup_args(log, sender_profiles, state)
            log.info("Trying to run program")
            state.do_run = False
            window["log_tab"].select()
            # state.running will have been set True or False by setup_args
            # depending on whether it was successful
            if state.running:
                log.info("Successfully running")
            else:
                log.info("Failed to run program (see log)")
        state.timer.stop("running")

        # If running, read the score from Excel
        state.timer.start("reader")
        if state.running and state.reader_timer.just_expired():
            state.reader_timer.reset()
            assert args is not None, "If state.running, args should not be None"
            try:
                state.scoredata = args.score_reader.read_score()
            except Exception as e:
                log.error(f"Error reading score from Excel spreadsheet: {e}. "
                          "(Once fixed click \"Run\" to restart the program)")
                state.consecutive_reader_errors += 1
                # TODO: add notification if this happen a lot, probably means
                # excel has closed or something like that
            else:
                state.consecutive_reader_errors = 0

            # Log if the score has changed
            if old_scoredata != state.scoredata:
                score_str, err = state.scoredata.score_as_str(
                ), state.scoredata.error_msg
                old_score_str = old_scoredata.score_as_str()
                err_msg = f", error: {err}" if err else ""
                log.info(
                    f"Score read from Excel changed to: {score_str}{err_msg}, "
                    f"was {old_score_str}")
                old_scoredata = state.scoredata
        state.timer.stop("reader")

        # Show/hide error message about consecutive score reads failing. A
        # common possible cause is if Excel has been closed
        if state.consecutive_reader_errors > 10 or test_show:
            window["status_error_message"].update(
                "Multiple attempts to read score values from Microsoft Excel have failed",
                visible=True,
                **status_text_format_warning)
        else:
            window["status_error_message"].update(visible=False)

        # Update the connection with the latest score data, and service the network
        state.timer.start("network poll")
        if state.running:
            state.sender_connection.poll(state.scoredata.score)
        state.timer.stop("network poll")

        just_lost_connection = False
        if state.running and state.sender_connection.is_connected():
            if not state.connected:
                log.info("Connected!")
            state.connected = True
            window["is_connected"].update("Connected    ",
                                          **status_text_format_ok)
        else:
            window["is_connected"].update("Not connected",
                                          **status_text_format_warning)
            if state.connected:
                just_lost_connection = True
                state.connected = False
            if just_lost_connection and not state.lost_connection_notifications:
                state.lost_connection_notifications = True
                state.lost_connection_timer.reset()

        state.timer.start("desktop notify disconnect")
        send_notify = False
        if just_lost_connection:
            log.info("Disconnected!")
            send_notify = True
        elif state.lost_connection_notifications and state.lost_connection_timer.just_expired(
        ):
            log.debug("Lost connection notification timeout")
            state.lost_connection_timer.reset()
            send_notify = True

        if send_notify:
            log.debug("Sending desktop notification about lost connection")
            send_desktop_notification("cricket_scorer lost_connection",
                                      "cricket_scorer has lost connection")
        window["stop_disconnect_notifications"].update(
            visible=state.lost_connection_notifications)
        state.timer.stop("desktop notify disconnect")

        if state.running:
            window["is_running"].update("Running    ", **status_text_format_ok)
        else:
            window["is_running"].update("Not running",
                                        **status_text_format_warning)

        if test_show or state.running and settings_changed(
                state.settings, state.running_settings):
            window["settings_changed"].update(visible=True)
        else:
            window["settings_changed"].update(visible=False)

        # Spinner to show we haven't frozen
        spinning_chars = ["|", "/", "-", "\\"]
        if state.spinning_char_timer.just_expired():
            state.spinning_char_timer.reset()
            state.spinning_char_index += 1
            state.spinning_char_index %= len(spinning_chars)
            window["spinning_char"].update(
                spinning_chars[state.spinning_char_index])

        if state.general_error_flag_timer.just_expired():
            state.general_error_flag = False
            state.general_error_flag_timer.reset()
            if not test_show:
                window["general_error_message"].update(visible=False)

        # printer.print_contents_if_diff()

    log.info("Exiting main loop, program should terminate in a moment")

    state.timer.stop("loop")
    state.running_settings.clear()
    # printer.print_contents_if_diff()
    return args
示例#15
0
    sg.Input(size=(18, 1), pad=(0, 0)),
    sg.Input(size=(14, 1), pad=(0, 0)),
    sg.Input(size=(15, 1), pad=(0, 0))
] for row in range(10)]
tab4_layout = header + input_rows
col3 = [[
    sg.TabGroup([[sg.Tab('Home', tab1_layout)],
                 [sg.Tab('Communication', tab2_layout)],
                 [sg.Tab('Transaction history', tab3_layout)],
                 [sg.Tab('Billing', tab4_layout)]])
]]
layout = [[sg.Column(col3, scrollable=True)]]
window = Window(value, layout, resizable=True, size=(600, 1000))

while True:
    event, values = window.read(timeout=900)
    # del x
    # del inBoard, outBoard, requestBoard, availabilityBoard, startBoard, stopBoard, startAckBoard, stopAckBoard
    inBoard = reply.lrange('IN_BOARD', 0, -1)
    outBoard = reply.lrange('OUT_BOARD', 0, -1)
    iB = []
    oB = []
    for i in inBoard:
        p = i.decode('utf-8')
        iB.append(p)
        iB.append("                                      ")
    for i in outBoard:
        p = i.decode('utf-8')
        oB.append(p)
        oB.append("                                      ")
    if set(iB) != set(iBi):
示例#16
0
def main_event_loop(args: argparse.Namespace, window: sg.Window):
    """
    Main GUI event loop
    """
    run = True

    db = TinyDB("db/db.json")

    while True:
        event, values = window.read(timeout=20)
        if event == sg.WIN_CLOSED:
            return

        elif event == "-SHOW WARNING-":
            if args.insert:
                if (
                    sg.popup_yes_no(
                        "Be aware that no security checks are made\n"
                        "This card MRZ will be added to the database if it does not already exist\n"
                        "Run the main program with this card before making sure that it is safe to add\n"
                        "Are you sure you want to add this card?"
                    )
                    == "Yes"
                ):
                    database_obj = Query()
                    if db.search(database_obj.mrz == values[event]) == []:
                        db.insert({"mrz": values[event]})
                        print("[+] Card is added to the database")
                    else:
                        print("[i] Card is already in the database")
                else:
                    print("[-] Card is NOT added to the database")
            else:
                if (
                    sg.popup_yes_no(
                        "Card is going to be removed from the database.\n" "Are you sure?"
                    )
                    == "Yes"
                ):
                    database_obj = Query()
                    if db.search(database_obj.mrz == values[event]) == []:
                        print("[-] Card is not in the database")
                    else:
                        db.remove(database_obj.mrz == values[event])
                        print("[+] Card is removed from the database")
                else:
                    print("[-] Card is NOT removed from the database")
            run = True
            print("[i] Restarting...")

        elif event == "-PROBLEM IN EITHER READ OR DOCUMENT-":
            sg.popup_ok(
                "Problem in either the MRZ scan or the document files\n"
                "Check the logs! Restarting..."
            )
            run = True

        elif event == "-SHOW MRZ-":
            window["camera_image"].update(data=values[event][0])

        elif event == "-HIDE MRZ-":
            window["camera_image"].update(filename="", size=(320, 240))

        elif event == "-RAISED EXCEPTION-":
            print("[!] Problem occured! Restarting...")
            run = True

        elif event == "-PRINT-":
            window["output_window"].print(values[event])

        if run:
            threading.Thread(target=database_builder_loop, args=(window,), daemon=True).start()
            run = False