如何在按 Enter 时跳过打印到终端的对话框

问题描述 投票:0回答:1

我有一个函数,可以以较慢的方式打印给它的字符串(每 0.05 秒一个字母):

def tobyTalks(sentence):
    skip = False
    for letter in sentence:
        print('\033[1;34m' + letter + '\033[0m', end='', flush=True)
        if skip:
            time.sleep(0.0001)  # smaller than 0.05s or 0
        else:
            time.sleep(0.05)

实际上它正在工作并且没有任何问题,但我想为键盘上的“Enter”键添加一个事件监听器,以将

skip
更改为
True

但听起来这种方式是完全错误的,应用程序甚至无法工作。

有人可以告诉我处理这个问题的方法吗?

python terminal keyboard
1个回答
0
投票

您可以使用 Pynput 来检测按下情况。
第一:

pip install pynput

然后:

from pynput import keyboard
skip = False
def on_enter_key_released(key):
    if key == keyboard.Key.enter:
        skip = not skip # toggles skip to True and False
def on_enter_key_pressed():
    pass
# toggling skip only on release as release is detected one time but press toggles multiple times if pressed for long time
listener = keyboard.Listener(
    on_press=on_enter_key_pressed,
    on_release=on_enter_key_released
)
listener.start() # Adds a event listener for detecting enter key pressed
def tobyTalks(sentence):
    global skip

    for letter in sentence:
        print('\033[1;34m' + letter + '\033[0m', end='', flush=True)

        if skip:
            time.sleep(0.0001)  # smaller than 0.05s or 0
        else:
            time.sleep(0.05)

© www.soinside.com 2019 - 2024. All rights reserved.