Python xlib 更改光标

标签 python xlib mouse-cursor

如何使用 Xlib 在 Python 应用程序中设置根窗口(或任何其他窗口)的光标?

我有一个 displaywindow (根窗口)的实例。 使用 C 绑定(bind);我可以使用 XDefineCursor使用我用 XCreatePixmapCursor 创建的光标。如何对 python 绑定(bind)执行同样的操作?

我希望能够使用默认光标或自定义光标。

最佳答案

当您需要查找与任何 libX11 函数等效的 python-xlib 时,需要记住两件事:

  1. 与 libX11 不同,python-xlib 是面向对象的;在本例中,XCreatePixmapCursor() 转换为 pixmap.create_cursor()
  2. 大多数 python-xlib 方法直接映射到 X11 消息,即。大多数辅助函数没有实现;如果找不到匹配的 python-xlib 方法,您通常会想查看 libX11 source code弄清楚该函数是否只是一个在幕后调用其他函数的助手。在这种情况下,如果您查看 source code of XDefineCursor() ,您会看到它实际上正在调用 XChangeWindowAttributes(),这意味着您需要在 python-xlib 中使用 win.change_attributes()

如果您想使用 XCreateFontCursor() 使用光标字体中的光标,则第二条准则再次适用:它在底层调用 XCreateGlyphCursor(),这对应于font.create_glyph_cursor()

将所有这些放在一起,您将得到以下结果:

# Create font cursor
font = display.open_font('cursor')
cursor = font.create_glyph_cursor(font, Xlib.Xcursorfont.crosshair, Xlib.Xcursorfont.crosshair+1, (65535, 65535, 65535), (0, 0, 0))


# Use PIL to load a cursor image and ensure that it's 1-bit as required
im = Image.open('cursor.png').convert('1')
w, h = im.size

# Create pixmap cursor
mask = win.create_pixmap(w, h, 1)
gc = mask.create_gc(foreground=0, background=1)
mask.put_pil_image(gc, 0, 0, im)
cursor = mask.create_cursor(mask, (0, 0, 0), (65535, 65535, 65535), 0, 0)


# Change cursors for given windows
win.change_attributes(cursor=cursor)

如果您想知道调用 font.create_glyph_cursor()+1 的重要性,source code of XCreateFontCursor() 中对此进行了解释。 .

关于Python xlib 更改光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41554701/

相关文章:

python - 为什么 __slots__ 不是 Python 中的默认值?

python - Numpy:在各种索引的矩阵行中插入任意数量的零

css - 使用 GWT、CSS 管理和自定义游标

vb.net - 让鼠标光标移动到一个位置?

python - 使用 Python 修复 HTML 字符串中的开括号问题

python - pyyaml 的漂亮输出

error-handling - 如何使Xlib打印错误消息,但不退出?

c - 奇怪的 XLib 错误; XDrawString 仅在 sleep 后有效

python - 监听键盘事件而不捕获它们?

html - 如何使光标在CSS的边距区域保持不变