首页 > 解决方案 > 在 python 中使用系统范围的热键运行函数

问题描述

假设有这个代码

import time

function():
 print("abcd")
 time.sleep(1)
 print("efgh")

function()

function()每当我从电脑上的任何地方按下组合键时,我都希望它运行。就像,假设我在 chrome 上观看 youtube 视频,我按下假设 shift+alt+b 然后function()应该开始运行并打印这些东西。

我猜我在 Windows 10 上使用 python 3.8。

标签: pythonfunction

解决方案


哦,我自己想通了它比这容易得多pynput

您需要使用该keyboard模块

这是代码:

import keyboard 
import time

function():
   print("abcd")
   time.sleep(1)
   print("efgh")

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('shift'): 
            if keyboard.is_pressed('alt'):
                if keyboard.is_pressed('b'):
                    function()
    except:
        pass  

它比其他解决方案简单


推荐阅读