【问题标题】:How to interupt typing text in terminal?如何中断在终端中输入文本?
【发布时间】:2019-09-22 19:28:08
【问题描述】:

我正在尝试制作一个小型 RPG 游戏,我想出了以下想法:

这个想法很简单:

1. Class Typing 会像在屏幕上键入一样打印文本。

(函数会更容易写,但问题是一样的)

import sys
import os
import time


class Typing:
    def __init__(self, text, speed):
        self.text = text
        self.speed = speed

        for l in text:
            sys.stdout.write(l)
            sys.stdout.flush()
            time.sleep(speed)
        sys.stdout.write('\n')
        sys.stdout.flush()


text = '''
                         _____ __             __  
                        / ___// /_____ ______/ /__
                        \__ \/ __/ __ `/ ___/ //_/
                       ___/ / /_/ /_/ / /__/ ,<   
   ____               /____/\__/\__,_/\___/_/|_|  
  / __ \_   _____  _____/ ____/ ____ _      __    
 / / / | | / / _ \/ ___/ /_  / / __ | | /| / /    
/ /_/ /| |/ /  __/ /  / __/ / / /_/ | |/ |/ /     
\____/ |___/\___/_/  /_/   /_/\____/|__/|__/      

'''
Typing(text, 0.005)


2.按下键盘键'space',for循环将停止,全文将显示在屏幕上。

        for l in text:

            # Keyboard would listen for the key 'space'

            # if 'space' key is detected:
            #     os.system('clear)
            #     print(text)

            # Keyboard would stop listing for the key 'space'
            #     break

            sys.stdout.write(l)
            sys.stdout.flush()
            time.sleep(speed)
        sys.stdout.write('\n')
        sys.stdout.flush()

我的问题:

这在 Python 中是否可行?如果有,怎么做?

【问题讨论】:

    标签: python-3.x for-loop printing keyboard pynput


    【解决方案1】:

    有可能,Python 中有一个keyboard module。添加if keyboard.is_pressed('space'):。在满足条件后,您可能希望包含少量延迟,否则似乎一个按键将被读取为多个。

    【讨论】:

    • 谢谢维尼修斯。这正是我想要的。
    猜你喜欢
    • 2021-03-27
    • 2017-11-20
    • 2017-06-18
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多