[英]Detecting both mouse buttons held down
我是 python 的新手,我發現了一個在按住並釋放鼠標按鈕時檢測鼠標按鈕的代碼,但我希望在按住兩個按鈕時“x”變為 True,我該怎么做
# This function will be called when any key of mouse is pressed
def on_click(*args):
# see what argument is passed.
print(args)
if args[-1]:
# Do something when the mouse key is pressed.
print('The "{}" mouse key has held down'.format(args[-2].name))
elif not args[-1]:
# Do something when the mouse key is released.
print('The "{}" mouse key is released'.format(args[-2].name))
# Open Listener for mouse key presses
with Listener(on_click=on_click) as listener:
# Listen to the mouse key presses
listener.join()
要檢測兩個按鈕是否同時按下,需要三個變量(在程序開始時初始化這些,在 on_click 函數之外):
global leftPressed, rightPressed, bothPressed
leftPressed = False
rightPressed = False
bothPressed = False
*注意這里的變量是全局的,因為多個版本的 on_click 將訪問和修改變量
然后,在第一個 if 語句中(按下鼠標按鈕時):
if args[-2].name == "left":
leftPressed = True
elif args[-2].name == "right":
rightPressed = True
if leftPressed and rightPressed:
# if both left and right are pressed
bothPressed = True
在第二個 if 語句中(釋放鼠標按鈕時)
if args[-2].name == "left":
leftPressed = False
elif args[-2].name == "right":
rightPressed = False
# as one key has been released, both are no longer pressed
bothPressed = False
print(bothPressed)
最后,要從 function on_click 中訪問全局變量,請將此行放在 function 的開頭:
global leftPressed, rightPressed, bothPressed
在此處查看完整版本的代碼:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.