如何在GTK和Python中获取小部件的背景色? [英] How to get the background color of a widget in GTK and Python?

查看:100
本文介绍了如何在GTK和Python中获取小部件的背景色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得小部件的正常背景色(在本例中为GtkHeaderBar).我目前正在使用

I want to get the normal background color of a widget (a GtkHeaderBar, in this case). I'm currently using

style = self.get_titlebar().get_style_context()

获取样式,然后

color = style.get_property("background-color", Gtk.StateFlags.NORMAL)

获取与该样式相关的背景颜色.

to get the background color associated to that style.

但是它返回具有以下属性的Gkd.RGBA对象:

However it returns a Gkd.RGBA object with the following properties:

Gdk.RGBA(red=0.000000, green=0.000000, blue=0.000000, alpha=0.000000)

但是,如果我打开GTK Inspector,选择HeaderBar,然后转到样式属性,它将显示

But if I open GTK Inspector, select the HeaderBar, and goes to the style properties, it shows

background-color | rgb(57,63,63) | gtk-contained-dark.css:1568.29

我该怎么做才能获得这些相同的值?

What do I have to do to get these same values?

我正在尝试GtkStyleContext.render_background(),但没有成功:

I am experimenting with the GtkStyleContext.render_background(), but I'm having no success:

surfc = Cairo.ImageSurface (Cairo.FORMAT_ARGB32, 10, 10)
contx = Cairo.Context(surfc)
style = self.get_titlebar().get_style_context()
backg = Gtk.render_background(style, contx, 10, 10, 10, 10)
surfc.write_to_png("test.png")

生成的文件test.pngrgba(0, 0, 0, 0)图像.

推荐答案

您应该看看如何使用CSS修改背景颜色.它有一个非常好的文档.可以和python一起使用

You should have a look at modifying the background-color with css. There is a very good documentation of it. It can be used with python with

css_provider = Gtk.CssProvider()
css_provider.load_from_path('application.css')
Gtk.StyleContext.add_provider_for_screen(
    Gdk.Screen.get_default(),
    css_provider,
    Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
)

和一个css文件,例如:

and a css file like:

GtkHeaderbar {
    background-color:@theme_bg_color;
}

编辑:正如您评论的那样,您不想修改背景颜色,而是获取背景值.您可以执行widget.get_style_context().get_background_color(),它将返回类似Gdk.RGBA(red=0.913725, green=0.913725, blue=0.913725, alpha=1.000000)的内容.

As you commented you do not want to modify the background color but retrieve the value of it. You can do widget.get_style_context().get_background_color() and it will return something like Gdk.RGBA(red=0.913725, green=0.913725, blue=0.913725, alpha=1.000000).

但是,您应该注意,由于没有一个背景色,因此已弃用get_background_color().一些小部件使用渐变作为背景,因此使用此方法不是最佳解决方案.请参阅文档以供参考

However, you should note that get_background_color() is deprecated since there is not one background color. Some widget use a gradient as a background so it is not the best solution to use this method. See the documentation for reference.

这篇关于如何在GTK和Python中获取小部件的背景色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆