在后台检测python中的按键 [英] Detecting a keypress in python while in the background

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

问题描述

我试图找到一种方法来检测按键,然后根据它是什么键运行一个方法.

I am trying to find a way to detect a keypress and then run a method depending on what key it is.

我已经可以用 Tkinter 做到这一点.但是我不能做的是在窗口处于后台时检测按键.我会在玩游戏时在后台运行这个程序.我需要它能够在我在游戏中时检测输入.

I can already do this with Tkinter. But what I can't do is detect the keypress while the window is in the background. I will be running this program in the background while I play a game. I need it to be able to detect inputs while I'm in the game.

有什么办法可以用 Tkinter 或其他东西来做到这一点吗?最好我不想下载任何外部内容,因为我想将其分发给其他人.

Is there any way I can do this with Tkinter or something else? Preferably I would like to not have to download anything external as I would like to distribute this to some other people.

推荐答案

pyHook 似乎可以很适合这个(由 furas 提到)

pyHook seems like it would work well for this (mentioned by furas)

from pyHook import HookManager
from win32gui import PumpMessages, PostQuitMessage

class Keystroke_Watcher(object):
    def __init__(self):
        self.hm = HookManager()
        self.hm.KeyDown = self.on_keyboard_event
        self.hm.HookKeyboard()


    def on_keyboard_event(self, event):
        try:
            if event.KeyID  == keycode_youre_looking_for:
                self.your_method()
        finally:
            return True

    def your_method(self):
        pass

    def shutdown(self):
        PostQuitMessage(0)
        self.hm.UnhookKeyboard()


watcher = Keystroke_Watcher()
PumpMessages()

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

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