我正在尝试创建一个热键切换(f12),该热键切换将在按下一次时打开循环,然后在再次按下时关闭该循环。循环是打开时每 0.5 秒单击一次鼠标。我在 wxpython 网站上找到了热键的配方,我可以打开循环,但无法找到关闭它的方法。我尝试创建一个单独的 key 来将其关闭,但没有成功。 鼠标模块模拟 1 次鼠标左键单击。
这是我当前的代码:
导入wx、win32con、鼠标
从时间导休眠眠
框架类(wx.Frame):
def __init__(self, parent, title):
super(Frameclass, self).__init__(parent, title=title, size=(400, 200))
self.Centre()
self.Show()
self.regHotKey()
self.Bind(wx.EVT_HOTKEY, self.handleHotKey, id=self.hotKeyId)
self.regHotKey2()
self.Bind(wx.EVT_HOTKEY, self.handleHotKey2, id=self.hotKeyId2)
def regHotKey(self):
"""
This function registers the hotkey Alt+F12 with id=150
"""
self.hotKeyId = 150
self.RegisterHotKey(self.hotKeyId,win32con.MOD_ALT, win32con.VK_F12)#the key to watch for
def handleHotKey(self, evt):
loop=True
print('clicks on')
while loop==True:
#simulated left mouse click
mouse.click()
sleep(0.50)
x=self.regHotKey2()
print(x)
if x==False:
print('Did it work?')
break
else:
pass
---------------------第二个按键热键--------
def regHotKey2(self):
self.hotKeyId2 = 100
self.RegisterHotKey(self.hotKeyId2,win32con.MOD_ALT, win32con.VK_F11)
def handleHotKey2(self, evt):
return False
loop=False
print(loop)
如果名称=='主要':
showytitleapp=wx.App()
#gotta have one of these in every wxpython program apparently
Frameclass(None, title='Rapid Clicks')
showytitleapp.MainLoop()
#infinite manloop for catching all the program's stuff
最佳答案
您的loop
变量的局部作用域位于 handleHotKey
内。因为regHotKey2
绑定(bind)到handleHotKey2
,这是一个不同的监听器,它生成的事件永远不会影响handleHotKey
内的循环。 。除此之外,第一行 handleHotKey2
是一个返回值,在下面两行执行之前会退出函数。
出于好奇,输出是什么 x=self.regHotKey2(); print(x)
生产?
尝试在类级别而不是函数级别定义循环变量 -
def __init__(self, parent, title):
... your original stuff ...
self.clicker_loop = False
然后修改处理程序中的该循环 -
def handleHotKey(self, evt):
self.clicker_loop = True
while self.clicker_loop:
... do the thing ...
def handleHotKey2(self, evt):
self.clicker_loop = False
请尝试一下并告诉我这是否有效。
也许这会从同一个热键切换循环......
def handleHotKey(self, evt):
if self.clicker_loop:
self.clicker_loop = False
else:
self.clicker_loop = True
关于python - wxPython:全局热键循环切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7563396/