Python 使用PySimpleGUI和pyhook在按下按钮的基础上锁定键和释放键
我创建了一个程序,用户只需按一下按钮退出程序,就可以访问系统键,如ctrl和alt。然而,当我运行程序时,它确实会卡在UI中,不允许我做任何事情。我错在哪里?提前谢谢Python 使用PySimpleGUI和pyhook在按下按钮的基础上锁定键和释放键,python,pysimplegui,pyhook,Python,Pysimplegui,Pyhook,我创建了一个程序,用户只需按一下按钮退出程序,就可以访问系统键,如ctrl和alt。然而,当我运行程序时,它确实会卡在UI中,不允许我做任何事情。我错在哪里?提前谢谢 import PySimpleGUI as sg import pyWinhook import pythoncom layout=[[sg.Button('Exit')]] def blockKeys(event): if event.Key.lower() in ['lwin', 'tab', 'l
import PySimpleGUI as sg
import pyWinhook
import pythoncom
layout=[[sg.Button('Exit')]]
def blockKeys(event):
if event.Key.lower() in ['lwin', 'tab', 'lmenu']:
return False # block these keys
else:
# return True to pass the event to other handlers
return True
def releaseKeys(event):
return True
window = sg.Window('Window Title', layout, no_titlebar=True, location=(0,0), size=(800,600), keep_on_top=True).Finalize()
window.Maximize()
hm = pyWinhook.HookManager()
hm.MouseAll = releaseKeys
hm.KeyAll = blockKeys
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()
while True:
event,values = window.read()
print(event,values)
if event =='Exit':
hm = pyWinhook.HookManager()
hm.MouseAll = releaseKeys
hm.KeyAll = releaseKeys
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()
break;
window.close()
pythoncom.PumpMessages()
只是处于空闲状态,等待Windows事件。这意味着它将继续在那里等待,什么也不做。您在PySimpleGUI
中使用while循环,因此不需要这样做
代码修订如下:
将PySimpleGUI导入为sg
导入pyWinhook
进口蟒蛇
布局=[[sg.按钮('Exit')]]
def区块键(事件):
如果['lwin','tab','lmenu']中的event.Key.lower():
返回False#阻止这些键
其他:
#返回True以将事件传递给其他处理程序
返回真值
def释放钥匙(事件):
返回真值
window=sg.window('windowtitle',layout,return\u keyboard\u events=True,finalize=True)
hm=pyWinhook.HookManager()
hm.MouseAll=释放键
hm.KeyAll=块键
嗯,钩鼠()
hm.键盘()
#pythoncom.PumpMessages()
尽管如此:
事件,值=window.read()
打印(事件、值)
如果事件==“退出”:
hm=pyWinhook.HookManager()
hm.MouseAll=释放键
hm.KeyAll=释放键
嗯,钩鼠()
hm.键盘()
#pythoncom.PumpMessages()
打破
window.close()
非常感谢您。这正是我想要的