如何使用 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()
中对此进行了解释。 .
关于Python xlib 更改光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41554701/