根据它的状态,是否可以在GtkButton中以不同的方式设置两个孩子?

问题描述:

GTK3:我有两个GtkLabel的小部件的GtkButton上(通过HBox中)是这样的:根据它的状态,是否可以在GtkButton中以不同的方式设置两个孩子?

[name_label (black) value_label (grey)] - button inactive (white background) 

[name_label (white) value_label (yellow)] - button active (black background) 

当按钮被触发我想要的背景变成黑色,在两个标记应该相应改变颜色。

是否可以使用CSS来做到这一点?

这是我曾尝试:

from gi.repository import Gtk, Gdk 

window = Gtk.Window() 
button = Gtk.Button() 
hbox = Gtk.HBox() 
name = Gtk.Label('Name') 
value = Gtk.Label('Value') 
value.set_name('value') 
hbox.set_spacing(10) 
hbox.pack_start(name, expand=False, fill=True, padding=0) 
hbox.pack_start(value, expand=False, fill=True, padding=0) 
button.add(hbox) 
window.add(button) 

window.connect('destroy', Gtk.main_quit) 
window.show_all() 

screen = Gdk.Screen.get_default() 
css_provider = Gtk.CssProvider() 
css_provider.load_from_path('style.css') 

context = Gtk.StyleContext() 
context.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) 

Gtk.main() 

的style.css:

.button { 
    background-color: white; 
    background-image: none; 
} 

.button #value { 
    color: grey; 
} 

.button:active { 
    background-color: black; 
    background-image: none; 
    color: white; 
} 

.button:active #value { 
    color: yellow; 
} 

值标签保持灰色当按钮被按下,所以最后一节不适用。这是预期的吗?

好的,所以我可以通过动态地向值标签添加一个类来得到这个工作。像这样,但原来的问题仍然存在:是否可以使用CSS来完成?

编辑:在新版本的GTK3,例如, 3.18.9(包含在Ubuntu Xenial中的),纯CSS解决方案按预期工作!

对于那些坚持使用旧的GTK版本的人,我会留下旧的解决方案。

from gi.repository import Gtk, Gdk 

window = Gtk.Window() 
button = Gtk.Button() 
hbox = Gtk.HBox() 
name = Gtk.Label('Name') 
value = Gtk.Label('Value') 
value.set_name('value') 
hbox.set_spacing(10) 
hbox.pack_start(name, expand=False, fill=True, padding=0) 
hbox.pack_start(value, expand=False, fill=True, padding=0) 
button.add(hbox) 
window.add(button) 

window.connect('destroy', Gtk.main_quit) 
window.show_all() 

screen = Gdk.Screen.get_default() 
css_provider = Gtk.CssProvider() 
css_provider.load_from_path('style.css') 

context = Gtk.StyleContext() 
context.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) 

ctx = value.get_style_context() 

def active(widget): 
    ctx.add_class('active_value') 

def inactive(widget): 
    ctx.remove_class('active_value') 

button.connect('pressed', active) 
button.connect('released', inactive) 
Gtk.main() 

以及相应的CSS:

.button { 
    background-color: white; 
    background-image: none; 
} 

.button #value { 
    color: gray; 
} 

.button #value.active_value { /* value label when the button is pressed */ 
    color:yellow; 
} 

.button:active { 
    background-color: black; 
    background-image: none; 
    color: white; 
}