如何在python程序中检测“空间”?

时间:2018-10-27 16:02:02

标签: python python-3.x keyboard keypress

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

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)

3 个答案:

答案 0 :(得分:0)

空格的Python表示形式为u"\u0020",称为here

并通过以下测试:

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

答案 1 :(得分:0)

您可以使用getch模块。

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

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

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

答案 2 :(得分:0)

我建议您使用keyboard

这是检测空间的示例代码,还请注意,该代码将等待按下空格键。

import keyboard

#.....

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

#....