Python xlib更改光标
如何使用Xlib在python应用程序中为根窗口(或任何其他窗口)设置光标?
How can I set the cursor for the root window (or any other window) in a python application using Xlib?
我有一个display
和window
(根窗口)的实例.
使用C绑定;我可以将 XDefineCursor 与我用 XCreatePixmapCursor .我该如何使用python绑定做同样的事情?
I have an instance of display
and window
(the root window).
Using the C bindings; I could use XDefineCursor with a cursor I have created with XCreatePixmapCursor. How do I do the same with the python bindings?
我希望能够使用默认光标或自定义光标.
I want to be able to use a default cursor, or a custom cursor.
当您需要找到与任何libX11函数等效的python-xlib时,要记住两点:
There are two things you want to keep in mind when you need to find the python-xlib equivalent of any libX11 function:
- 与libX11不同,python-xlib是面向对象的.在这种情况下,
XCreatePixmapCursor()
会转换为pixmap.create_cursor()
. - 大多数python-xlib方法直接映射到X11消息,即.大多数辅助功能未实现;如果找不到匹配的python-xlib方法,则通常需要查看 libX11源代码确定该函数是否只是在后台调用其他函数的助手.在这种情况下,如果您查看
XDefineCursor()
,您会看到它实际上是在调用XChangeWindowAttributes()
,这意味着您将要在python-xlib中使用win.change_attributes()
.
- Unlike libX11, python-xlib is object-oriented; In this case,
XCreatePixmapCursor()
translates topixmap.create_cursor()
. - Most python-xlib methods map directly to X11 messages, ie. most helper functions aren't implemented; If you can't find a matching python-xlib method, you'll often want to look at the libX11 source code to figure out if the function is just a helper that calls some other function under the hood. In this case, if you look at the source code of
XDefineCursor()
, you'll see it's actually callingXChangeWindowAttributes()
, meaning you'll want to usewin.change_attributes()
in python-xlib.
如果要使用XCreateFontCursor()
来使用光标字体中的光标,则第二条准则再次适用:它在幕后调用XCreateGlyphCursor()
,与font.create_glyph_cursor()
相对应.
If you want to use XCreateFontCursor()
to use a cursor from the cursor font, the second guideline again applies: It's calling XCreateGlyphCursor()
under the hood, which corresponds to font.create_glyph_cursor()
.
将所有内容放在一起,您将获得以下内容:
Putting all of that together, here's what you'll get:
# 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)
如果您想知道+1
在调用font.create_glyph_cursor()
中的重要性,请在
If you're wondering about the significance of the +1
in the call to font.create_glyph_cursor()
, that's explained in the source code of XCreateFontCursor()
.