按 space 栏时如何中断 for 循环?

How to break a for loop when pressing space bar?

我想在按下 space 栏时打破无限循环。我不想使用 Pygame,因为它会产生 window.

我该怎么做?

使用 space 会很困难,因为每个系统映射它的方式不同。如果您对 enter 没问题,那么这段代码就可以解决问题:

import sys, select, os
i = 0
while True:
    os.system('cls' if os.name == 'nt' else 'clear')
    print ("I'm doing stuff. Press Enter to stop me!")
    print (i)
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
    line = input()
    break
i += 1

Source

我得到了答案。我们可以使用 msvcrt.kbhit() 来检测按键。这是我写的代码。

import msvcrt
while 1:
    print 'Testing..'
    if msvcrt.kbhit():
        if ord(msvcrt.getch()) == 32:
            break

32 是 space 的号码。 27 为 esc。像这样我们可以选择任何键。

重要提示:这在 IDLE 中不起作用。使用终端。

Python 有一个具有许多功能的 keyboard 模块。您可以在 ShellConsole 中使用它。 安装它,也许使用这个命令:

pip3 install keyboard

然后在代码中使用它:

import keyboard #Using module keyboard
while True:  #making a loop
    try:  #used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed(' '): #if key space is pressed.You can also use right,left,up,down and others like a,b,c,etc.
            print('You Pressed A Key!')
            break #finishing the loop
    except:
        pass

可以设置为多个Key Detection:

if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
    #then do this

您还可以执行以下操作:

if keyboard.is_pressed('up') and keyboard.is_pressed('down'): #if both keys are pressed at the same time.
    #then do this

希望对您有所帮助。
谢谢。