如何检测按键?

2024-05-15 22:24:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python制作一个秒表类型的程序,我想知道如何检测是否按下了一个键(例如,p表示暂停,s表示停止),我不希望它像raw_input一样,在继续执行之前等待用户的输入

有人知道如何在一段时间内做到这一点吗

我希望实现这个跨平台,但是,如果不可能,那么我的主要开发目标是Linux


Tags: 用户程序类型目标inputrawlinux跨平台
3条回答

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

对于那些在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()

上述功能将打印您正在按下的任何键,并在释放“esc”键时启动操作。键盘文档是here,以便更灵活地使用

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

使用keyboard模块可以做更多的事情。 您可以使用pip install keyboard安装此模块 以下是一些方法:


Method#1:

使用函数^{}

import keyboard

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

这将在按下键p时中断循环


Method#2:

使用函数^{}

import keyboard

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

它将等待您按p,然后继续按代码


Method#3:

使用函数^{}

import keyboard

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

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

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

keyboard.unhook_all()

Method#4:

这个方法已经被用户8167727回答过了,但我不同意他们编写的代码。它将使用函数^{},但以另一种方式:

import keyboard

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

当按下p时,它将中断循环


Method#5:

您也可以使用^{}。它记录所有按下和释放的键,直到您按下escape键或在untilarg中定义的键,并返回^{}元素列表

import keyboard

keyboard.record(until="p")
print("You pressed p")

注意事项:

  • keyboard将从整个操作系统读取按键
  • keyboard在linux上需要root用户

相关问题 更多 >