gpt4 book ai didi

css - 是否可以根据其状态在 GtkButton 中为两个 child 设置不同的样式?

转载 作者:行者123 更新时间:2023-11-28 05:52:56 27 4
gpt4 key购买 nike

GTK3:我在 GtkButton 中有两个 GtkLabel 小部件(通过 HBox),如下所示:

[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()

样式.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;
}

关于css - 是否可以根据其状态在 GtkButton 中为两个 child 设置不同的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37228407/

27 4 0
文章推荐: javascript - 按下提交按钮后淡化
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com