如何在Linux下的python中跟踪光标图像

问题描述

我想做的是跟踪显示在屏幕上的光标图像,特别是当由于我移入和移出活动区域而发生变化时。有很多模块可以跟踪光标的位置,但是有关光标图像的信息却很吓人。

我发现有一篇文章提到使用win32gui的Windows: The way to detect the current mouse cursor type from bash or python

但是还有一种方法可以使用Xlib在Linux下获得它吗?我进一步发现, XFixes 显然具有一种称为 XFixesGetCursorImage 的方法,它没有直接暴露给python,但是它已经使用了几年。有人知道这是否已更改,或者我如何在python中使用C库以利用该功能(到目前为止,尚无有关此操作的经验)?

解决方法

我能为您提供的最好的是我的Xwintrack项目中的以下代码。 Fixes下的Xlib模块仅提供show_cursorhide_cursor,这使我们只能更改现有属性。

这也意味着,由于您无法识别现有的光标或其来源,因此,如果您更改光标,则必须求助于标准X光标或创建自己的光标,例如使用PIL从图像中删除。另外,当然,没有回头路了。您将无法还原到上一个光标,必须从X库中提供一个猜测。

如果您开始研究并研究光标和主题(已实施),您将发现它是一个曲折的雷区。它似乎是一个由分散的零件组成的系统,只有松散的结合在一起,并带有蜘蛛网和唾液。

以下内容取决于:

from Xlib import X,display,Xcursorfont
LEFT_PTR = Xcursorfont.left_ptr
SELECT = Xcursorfont.dotbox

def xcursorselect():
    ''' Change the cursor to a green dotbox to indicate a selection is required
        Beware - there is no way back to the original themed cursor - see xcursornormal()
    '''
    disp = display.Display()
    root = disp.screen().root
    font = disp.open_font('cursor')
    cursor = font.create_glyph_cursor(font,SELECT,SELECT+1,(0,65535,0),0)) #green with black edges
    root.change_attributes(cursor=cursor)
    disp.flush()

def xcursornormal():
    ''' Change the cursor back to White left_ptr to indicate selection finished
        Sadly under python there appears to be no way to identify the existing
        cursor image,so we're left with returning to a standard X cursor,rather
        than the Themed one
    '''
    disp = display.Display()
    root = disp.screen().root
    font = disp.open_font('cursor')
    cursor = font.create_glyph_cursor(font,LEFT_PTR,LEFT_PTR+1,(65535,65355),0)) #white with black edges
    root.change_attributes(cursor=cursor)
    disp.flush()

如果您确实提出了解决方案,请务必在此处发布。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...