通过Python中的Xlib找出鼠标按钮状态

我可以通过以下方式确定当前鼠标指针的位置:

from Xlib.display import Display
display = Display()
qp = display.screen().root.query_pointer()
print(qp.root_x,qp.root_y)

我如何也可以通过Xlib获得当前鼠标按钮的状态,例如按下/释放左/右按钮? (或者,如果不可能,为什么不呢?)

最佳答案
您的X窗口必须支持XInput扩展. Real X可以使用,但是如果X服务器不支持VNC服务器等扩展名,则无法使用鼠标键.

如果X服务器支持它,则可以进入鼠标状态,如下所示:

from Xlib.display import Display
from Xlib.ext import xinput

display = Display()

import time

while True:
    buttons = []

    for device_info in display.xinput_query_device(xinput.AllDevices).devices:
        if not device_info.enabled:
            continue
        if xinput.ButtonClass not in [ device_class.type for device_class in device_info.classes ]:
            continue
        buttons.append(device_info)

    for button in buttons:
        for device_class in button.classes:
            if xinput.ButtonClass == device_class.type:
                if device_class.state[0]:
                    print('Device {name} - Primary button down'.format(name=button.name))
    time.sleep(1)

我不确定百分百找不到文档,但是我确定device_class.state [0]是主要的(左键),1是中间的,2是右键.

您可能会发现the button number assignment spec here

编辑:

为什么有两个for循环-首先,我在永远循环之外编写了“ buttons”部分.但是,“嘿,您可以随时插入鼠标.”

您会发现,有许多设备包括“虚拟”设备.在笔记本电脑上,触摸板也可以用作按钮,因此在您的应用中,如果您想了解真正的鼠标按钮,则可能必须从名称中选择设备.同样,没有好的文档,因此您可能必须解密设备类对象.您可以在/usr/lib/python3/dist-packages/Xlib/ext/xinput.py中找到xinput. (如果您使用的是Python2,请相应地进行调整.)祝您好运.

相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...