简体   繁体   English

Python如何添加热键?

[英]How to add hotkey in Python?

I'm making a bot for a game and I want to call the function when I press hotkey.我正在为游戏制作一个机器人,我想在按下热键时调用 function。 I already tried some solutions but it is not good.我已经尝试了一些解决方案,但效果并不好。 Here is my code:这是我的代码:

def start():
    while True:
        if keyboard.is_pressed('alt+s'):
            break
        ...

def main():
    while True:
        if keyboard.is_pressed('alt+p'):
            start()

This way is stable but it causes a lag, it is hard for me to type something.这种方式很稳定,但会导致延迟,我很难打字。

def main():
    keyboard.add_hotkey('alt+p', start, args=(), suppress=True, trigger_on_release=True)
    while True:
        # waiting for the user to press hotkey
        continue

As I know keyboard.add_hotkey only returns output so I can't stop the loop in the start function.据我所知,keyboard.add_hotkey 只返回 output,所以我无法在开始时停止循环 function。

Is there any better solution?有没有更好的解决办法?

although this may be late for you, it may help others if they find this...虽然这对你来说可能会迟到,但如果他们发现这个可能会帮助其他人......

exit = false


def start():
    exit = true


def main():
    keyboard.add_hotkey('alt+p', start, suppress=True, trigger_on_release=True)
    while not exit:
        # put something here, you can't have an empty loop
    keyboard.remove_hotkey('alt+p')

When main is called this will add a hotkey that, when triggered, will run the function start.当调用 main 时,这将添加一个热键,当触发时,将运行 function 启动。 It will then go into the while loop.然后它将 go 放入 while 循环。 (note that, unless your are using subprocessing,+ this will stop everything else from going on until you leave the loop) The while loop will run until exit = false . (请注意,除非您正在使用子处理,否则这将阻止其他一切继续进行,直到您离开循环)while 循环将运行直到exit = false It would probably be a good idea to remove the hotkey, although you may have a reason not too.删除热键可能是个好主意,尽管您可能也有理由不这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM