如何使用PyGTK和PyCairo在窗口中获得透明背景?

6

我一直在努力使用PyGTK创建一个没有装饰和透明背景的窗口。然后,我将使用Cairo来绘制窗口的内容。但是我无法使其正常工作。

我尝试了许多不同的方法,它们都失败了,这是其中之一:

#!/usr/bin/env python

import pygtk
pygtk.require('2.0')
import gtk, sys, cairo

win = None

def expose (widget, event):
    cr = widget.window.cairo_create()

    #Start drawing
    cr.set_operator(cairo.OPERATOR_CLEAR)
    cr.set_source_rgba(0.5,1.0,0.0,0.5)
    cr.rectangle(0, 0, 0.9, 0.8)
    cr.fill()

def main (argc):
    global win

    win = gtk.Window()

    win.set_decorated(False)

    win.connect('delete_event', gtk.main_quit)
    win.connect('expose-event', expose)

    win.set_app_paintable(True)

    win.show()

    gtk.main()

if __name__ == '__main__':
    sys.exit(main(sys.argv))

那么,最简单的方法是什么?
2个回答

9

实际上,我自己找到了解决方法。

这是一个可行的示例。我已经加了注释来说明相关部分,以防其他人对如何做这件事感兴趣。

#!/usr/bin/env python

import pygtk
pygtk.require('2.0')
import gtk, sys, cairo
from math import pi

def expose (widget, event):
    cr = widget.window.cairo_create()

    # Sets the operator to clear which deletes everything below where an object is drawn
    cr.set_operator(cairo.OPERATOR_CLEAR)
    # Makes the mask fill the entire window
    cr.rectangle(0.0, 0.0, *widget.get_size())
    # Deletes everything in the window (since the compositing operator is clear and mask fills the entire window
    cr.fill()
    # Set the compositing operator back to the default
    cr.set_operator(cairo.OPERATOR_OVER)

    # Draw a fancy little circle for demonstration purpose
    cr.set_source_rgba(0.5,1.0,0.0,1)
    cr.arc(widget.get_size()[0]/2,widget.get_size()[1]/2,
           widget.get_size()[0]/2,0,pi*2)
    cr.fill()

def main (argc):

    win = gtk.Window()

    win.set_decorated(False)

    # Makes the window paintable, so we can draw directly on it
    win.set_app_paintable(True)
    win.set_size_request(100, 100)

    # This sets the windows colormap, so it supports transparency.
    # This will only work if the wm support alpha channel
    screen = win.get_screen()
    rgba = screen.get_rgba_colormap()
    win.set_colormap(rgba)

    win.connect('expose-event', expose)

    win.show()

0

这个问题已经在一个论坛中得到了解决。但是它是用C++编写的。请尝试理解。

按照以下步骤: Linux Questions

查看phorgan1发布的评论。 希望这可以帮助你...


那段代码看起来很像我上面的代码。我根据那个C++代码修改了我的代码,但它还是不起作用。 - paldepind

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接