Клавиатурный модуль Python - подавить ввод при записи в окно - PullRequest
0 голосов
/ 08 апреля 2020


Привет,
Я занимаюсь разработкой приложения, которое отслеживает и корректирует вводимые пользователем данные на основе некоторых правил.
Я читаю события с клавиатуры с помощью модуля python клавиатуры.
Я столкнулся с некоторой проблемой, когда пользователь печатает очень быстро, в отношении некоторых наложений текста. Под этим я подразумеваю, что когда мое приложение пишет правильный ввод, пользователь продолжает писать и может писать до того, как корректор наберет целое слово.
Я обнаружил, что могу запустить перехват клавиатуры с подавленным выводом на экран и попытался реализовать решение.
В приведенном выше коде я попытался воссоздать проблему и попытался дать общее представление.

import keyboard
from collections import deque

string : str = ""
counter : int = 0
is_suppressed: bool = False # this indicates if letters are shown in the window or not
suppressed_string: str = ""
q = deque() # this is used as a buffer, and stores the words that are entered when the
# program is correcting


def keyboard_module_write_to_screen(is_suppressed, string):
        for i in range(len(string) + 1):
            print("--Pressing backspace--")
            keyboard.press_and_release('backspace')
        for i, char in enumerate (string): # simulating a calculation 
            final_char_to_be_written = char.upper()
            print("---WRITING THE CHAR -> {} ---".format(final_char_to_be_written))
            keyboard.write(final_char_to_be_written)
        for i in range(30):
            keyboard.write('*')
        keyboard.write(' ')

def monitoring(event):
        global counter, string, is_suppressed, suppressed_string

        if (event.event_type == keyboard.KEY_DOWN): # and event.name != 'backspace'):
            print("-String entered : {}".format(event.name))

            if (event.name == 'space'):
                # if space is button a new word is entered
                if (is_suppressed is True):
                    # if program occupied writing to the screen save the word to the buffer
                    q.appendleft(suppressed_string)
                    suppressed_string = ""

                elif (is_suppressed is False):
                        # check and write first from the deque,
                        # write the word(s) that were stored in the buffer before writing current
                        # input string
                        # haven't find a way to do the above alongside the others
                        keyboard.unhook_all()
                        keyboard.hook(monitoring, suppress = True)

                        is_suppressed = True

                        keyboard_module_write_to_screen(is_suppressed, string)

                        keyboard.unhook_all()
                        keyboard.hook(monitoring, suppress = False)
                        is_suppressed = False
                        counter = 0
                        string = ""

            elif (event.name in "abcdefghijklmnopqrstuvwxyz") :
                if (is_suppressed is True):
                    suppressed_string = ''.join([suppressed_string, event.name])
                    print("########## SUPPRESSED_STRING = {} #########".format(suppressed_string))

                counter = counter + 1
                print("-- COUNTER is : {}".format(counter))
                string = ''.join([string, event.name])
            elif (event.name == "]"):
                    print(q)
            elif (event.name == 'backspace'):
                pass

keyboard.hook(monitoring, suppress = False)

Мне не удалось заставить его работать и дать желаемый результат.
Любой совет, как заставить его работать, был бы полезен.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...