GTK3:我在GtkButton(通过HBox)中有两个GtkLabel小部件,如下所示:
[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 :(得分: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;
}