【问题标题】:While loop doesn`t detect msvcrt.getch() keypress虽然循环没有检测到 msvcrt.getch() 按键
【发布时间】:2018-12-07 00:31:26
【问题描述】:
import msvcrt
x: int = 0
while not msvcrt.getch() == ' ':
    if x <= 10000:
        print(x)
        x += x
    else:
        print("space")

按下“空格”时循环不会停止。

【问题讨论】:

    标签: python python-3.x windows keypress msvcrt


    【解决方案1】:

    msvcrt.getch() 返回一个字节串而不是一个字符串,因此当您按空格键时,它将返回b' ',而不是' '

    因此改变:

    while not msvcrt.getch() == ' ':
    

    收件人:

    while not msvcrt.getch() == b' ':
    

    【讨论】:

    • 没有改变它只是飞过 0 甚至没有计算或关心空格键。
    • x: int = 0 更改为x = 0x+=x 更改为x+=1
    • 是的,它应该是 x += 1 我的错,但空间仍然无法正常工作。也许它无法赶上它 idk
    • 更改后,您的脚本对我来说很好。它会在任何按钮按下时增加 x,除了空格,它会停止。
    • 导入 msvcrt x = 0 而不是 msvcrt.getch() == b' ': if x
    【解决方案2】:
    import msvcrt
    x = 0
    while not msvcrt.getch() == b' ':
        if x <= 10000:
            print(x)
            x += 1
        else:
            print("space")
    

    感谢您的关注

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 2021-12-14
      • 2015-03-02
      • 2014-01-25
      • 2020-08-05
      相关资源
      最近更新 更多