如何检测按键? [英] How to detect key presses?

查看:30
本文介绍了如何检测按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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, which waits for the user's input before continuing execution.

有人知道如何在 while 循环中执行此操作吗?

Anyone know how to do this in a while loop?

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

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

推荐答案

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

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

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

这篇关于如何检测按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆