2016-05-14 64 views
0

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; 
} 

值標籤保持灰色當按鈕被按下,所以最後一節不適用。這是預期的嗎?

回答

0

好的,所以我可以通過動態地向值標籤添加一個類來得到這個工作。像這樣,但原來的問題仍然存在:是否可以使用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; 
} 
相關問題