【问题标题】:How do I detect 'space' in a python program?如何在 python 程序中检测“空格”?
【发布时间】:2019-04-01 02:26:54
【问题描述】:

我正在创建一个基于文本的游戏,为了加快过去的对话,我希望用户能够点击“空格”并跳过它。

import time
import sys

text_speed = .05

def slow_type(line, speed): #You input the dialogue and speed(smaller = faster)
    for l in line:
        sys.stdout.write(l)
        sys.stdout.flush()
        time.sleep(speed)
    time.sleep(.5)

if <'Space'> pressed:
    text_speed = 0

NL1 = "Huh, I see you finally came. "

slow_type(NL1, text_speed)

【问题讨论】:

    标签: python python-3.x keyboard keypress


    【解决方案1】:

    空间的 Python 表示是u"\u0020",引用here

    并通过以下方式测试:

    if input('enter:') == u"\u0020":
        print('pass')
    else:
        print('fail')
    

    【讨论】:

      【解决方案2】:

      您可以使用getch 模块。

      import getch
      while getch.getch() != ' ':
          pass
      

      或者在 Windows 上,你可以使用msvcr.getch:

      import msvcrt
      while msvcrt.getch() != ' ':
          pass
      

      【讨论】:

        【解决方案3】:

        我建议你使用keyboard

        这里是一个检测空格的示例代码,还要注意代码会等待空格键被按下。

        import keyboard
        
        #.....
        
        if keyboard.is_pressed("space"):
            text_speed = 0
        
        #....
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-04-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-26
          • 2018-11-26
          相关资源
          最近更新 更多