如何使用 Xlib 在 python 应用程序中为根窗口(或任何其他窗口)设置光标?
我有一个 display 和 window 的实例(根窗口)。 使用 C 绑定(bind);我可以使用 XDefineCursor使用我用 XCreatePixmapCursor 创建的光标.我如何对 python 绑定(bind)执行相同的操作?
我希望能够使用默认光标或自定义光标。
请您参考如下方法:
当您需要查找与任何 libX11 函数等效的 python-xlib 时,您需要记住两件事:
- 与 libX11 不同,python-xlib 是面向对象的;在这种情况下,
XCreatePixmapCursor()转换为pixmap.create_cursor()。 - 大多数 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() 中对此进行了解释.
