在python中检测按键?

问题描述 投票:42回答:9

我在python中制作秒表类型程序,我想知道如何检测是否按下了一个键(例如p表示暂停,s表示停止),我不希望它像raw_input那样等待用户在继续执行之前的输入。任何人都知道如何在while循环中执行此操作?

另外,我想制作这个跨平台,但如果不可能,那么我的主要开发目标是linux

python python-2.7 keypress detect
9个回答
35
投票

Python有一个keyboard模块,具有许多功能。安装它,也许使用此命令:

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('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
        else:
            pass
    except:
        break  # if user pressed a key other than the given key the loop will break

0
投票
key = cv2.waitKey(1)

这是来自openCV包。它无需等待即可检测到按键。


17
投票

OP提到raw_input - 这意味着他想要cli解决方案。 Linux:curses就是你想要的(windows PDCurses)。 Curses,是一个用于cli软件的图形API,您可以实现的不仅仅是检测关键事件。

此代码将检测键,直到按下新行。

import curses
import os

def main(win):
    win.nodelay(True)
    key=""
    win.clear()                
    win.addstr("Detected key:")
    while 1:          
        try:                 
           key = win.getkey()         
           win.clear()                
           win.addstr("Detected key:")
           win.addstr(str(key)) 
           if key == os.linesep:
              break           
        except Exception as e:
           # No input   
           pass         

curses.wrapper(main)

16
投票

对于那些在窗户上并且正在努力寻找工作答案的人来说,这是我的:pynput

from pynput.keyboard import Key, Listener

def on_press(key):
    print('{0} pressed'.format(
        key))

def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

上面的功能将打印您按下的任何键,并在释放'esc'键时启动操作。键盘文档是here,用于更多变化的用法。


9
投票

对于Windows,您可以像这样使用msvcrt

   import msvcrt
   while True:
       if msvcrt.kbhit():
           key = msvcrt.getch()
           print(key)   # just to show the result

6
投票

使用PyGame创建一个窗口,然后就可以获得关键事件。

对于字母p

import pygame, sys
import pygame.locals

pygame.init()
BLACK = (0,0,0)
WIDTH = 1280
HEIGHT = 1024
windowSurface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)

windowSurface.fill(BLACK)

while True:
    for event in pygame.event.get():
        if event.key == pygame.K_p: # replace the 'p' to whatever key you wanted to be pressed
             pass #Do what you want to here
        if event.type == pygame.locals.QUIT:
             pygame.quit()
             sys.exit()

5
投票

使用此代码查找按下的键

from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

3
投票

使用keyboard模块可以完成更多的事情。

以下是一些方法:


Method #1:

使用函数read_key()

import keyboard

while True:
    if keyboard.read_key() == "p":
        print("You pressed p")
        break

当按下键p时,这将打破循环。


Method #2:

使用函数wait

import keyboard

keyboard.wait("p")
print("You pressed p")

它将等待您按下p并在按下时继续执行代码。


Method #3:

使用函数on_press_key

import keyboard

keyboard.on_press_key("p", lambda _:print("You pressed p"))

它需要一个回调函数。我使用了_,因为键盘函数将键盘事件返回给该函数。

一旦执行,它将在按下键时运行该功能。您可以通过运行此行来停止所有挂钩:

keyboard.unhook_all()

Method #4:

用户8167727已经回答了这种方法,但我不同意他们制作的代码。它将使用is_pressed函数,但以另一种方式:

import keyboard

while True:
    if keyboard.is_pressed("p"):
        print("You pressed p")
        break

当按下p时它会打破循环。


笔记:

  • keyboard将从整个操作系统中读取按键。
  • keyboard需要linux上的root

1
投票

我建议你使用PyGame并添加一个事件句柄。

http://www.pygame.org/docs/ref/event.html


1
投票

所以我根据这篇文章(使用msvcr库和Python 3.7)制作了这个游戏。

以下是游戏的“主要功能”,即检测按下的按键:

# Requiered libraries - - - -
import msvcrt
# - - - - - - - - - - - - - -


def _secret_key(self):
    # Get the key pressed by the user and check if he/she wins.

    bk = chr(10) + "-"*25 + chr(10)

    while True:

        print(bk + "Press any key(s)" + bk)
        #asks the user to type any key(s)

        kp = str(msvcrt.getch()).replace("b'", "").replace("'", "")
        # Store key's value.

        if r'\xe0' in kp:
            kp += str(msvcrt.getch()).replace("b'", "").replace("'", "")
            # Refactor the variable in case of multi press.

        if kp == r'\xe0\x8a':
            # If user pressed the secret key, the game ends.
            # \x8a is CTRL+F12, that's the secret key.

            print(bk + "CONGRATULATIONS YOU PRESSED THE SECRET KEYS!\a" + bk)
            print("Press any key to exit the game")
            msvcrt.getch()
            break
        else:
            print("    You pressed:'", kp + "', that's not the secret key(s)\n")
            if self.select_continue() == "n":
                if self.secondary_options():
                    self._main_menu()
                break

如果你想要程序的完整源代码,你可以看到它或从这里下载它:

The Secret Key Game (GitHub)

(注意:秘密按键是:Ctrl + F12)

我希望你可以作为一个例子,帮助那些前来咨询这些信息的人。

© www.soinside.com 2019 - 2024. All rights reserved.