在python中检测按键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24072790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:55:00  来源:igfitidea点击:

detect key press in python?

pythonpython-2.7keypressdetect

提问by lobuo

I am making a stopwatch type program in python and I would like to know how to detect if a key is pressed (such as p for pause and s for stop), and I would not like it to be something like raw_input that waits for the user's input before continuing execution. Anyone know how to do this in a while loop?

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

Also, I would like to make this cross-platform, but if that is not possible, then my main development target is linux

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

回答by Madison Courto

I would suggest you use PyGame and add an event handle.

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

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

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

回答by A.J. Uppal

Use PyGame to have a window and then you can get the key events.

使用 PyGame 有一个窗口,然后您可以获取关键事件。

For the letter p:

对于这封信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()

回答by Abc Xyz

As OP mention about raw_input - that means he want cli solution. Linux: cursesis what you want (windows PDCurses). Curses, is an graphical API for cli software, you can achieve more than just detect key events.

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

This code will detect keys until new line is pressed.

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

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)

回答by Benjie

For Windowsyou could use msvcrtlike this:

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

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

回答by Benjie

Python has a keyboardmodule with many features. Install it, perhaps with this command:

Python 有一个具有许多功能的键盘模块。安装它,也许使用以下命令:

pip3 install keyboard

Then use it in code like:

然后在代码中使用它,如:

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
    except:
        break  # if user pressed a key other than the given key the loop will break

回答by Mitrek

For those who are on windows and were struggling to find an working answer here's mine: pynput

对于那些在 Windows 上并且正在努力寻找工作答案的人,这是我的: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()

The function above will print whichever key you are pressing plus start an action as you release the 'esc' key. The keyboard documentation is herefor a more variated usage.

上面的函数将打印您按下的任何键,并在您松开“esc”键时开始操作。键盘文档在这里提供了更多不同的用法。

Markus von Broadyhighlighted a potential issue that is: This answer doesn't require you being in the current window to this script be activated, a solution to windows would be:

Markus von Broady强调了一个潜在的问题,即:此答案不需要您在当前窗口中激活此脚本,Windows 的解决方案是:

from win32gui import GetWindowText, GetForegroundWindow
current_window = (GetWindowText(GetForegroundWindow()))
desired_window_name = "Stopwatch" #Whatever the name of your window should be

#Infinite loops are dangerous.
while True: #Don't rely on this line of code too much and make sure to adapt this to your project.
    if current_window == desired_window_name:

        with Listener(
            on_press=on_press,
            on_release=on_release) as listener:
            listener.join()

回答by Ferd

So I made this ..kind of game.. based on this post (using msvcr library and Python 3.7).

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

The following is the "main function" of the game, that is detecting the keys pressed:

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

# 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

If you want the full source code of the porgram you can see it or download it from here:

如果您想要该 porgram 的完整源代码,您可以从这里查看或下载:

The Secret Key Game (GitHub)

秘钥游戏 (GitHub)

(note: the secret keypress is: Ctrl+F12)

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

I hope you can serve as an example and help for those who come to consult this information.

希望您能以身作则,为前来咨询本资料的人士提供帮助。

回答by Manivannan Murugavel

Use this code for find the which key pressed

使用此代码查找按下的哪个键

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()

回答by Manivannan Murugavel

key = cv2.waitKey(1)

This is from the openCV package. It detects a keypress without waiting.

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

回答by Black Thunder

There are more things which can be done with keyboardmodule.

keyboard模块可以做的事情还有很多。

Here are some of the methods:

以下是一些方法:



Method #1:

方法#1:

Using the function read_key():

使用功能read_key()

import keyboard

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

This is gonna break the loop as the key pis pressed.

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



Method #2:

方法#2:

Using function wait:

使用功能wait

import keyboard

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

It will wait for you to press pand continue the code as it is pressed.

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



Method #3:

方法#3:

Using the function on_press_key:

使用功能on_press_key

import keyboard

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

It needs a callback function. I used _because the keyboard function returns the keyboard event to that function.

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

Once executed, it will run the function when the key is pressed. You can stop all hooks by running this line:

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

keyboard.unhook_all()


Method #4:

方法#4:

This method is sort of already answered by user8167727but I disagree with the code they made. It will be using the function is_pressedbut in an other way:

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

import keyboard

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

It will break the loop as pis pressed.

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



Notes:

笔记:

  • keyboardwill read keypresses from the whole OS.
  • keyboardrequires root on linux
  • keyboard将从整个操作系统读取按键。
  • keyboard在 linux 上需要 root