隔久点不用老是会忘,留个笔记。。
Python+PYGObject/PYGtk,加载 CSS 样式的演示代码
demo 运行的效果截图:
#!/usr/bin/env python3
import sys
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import GLib, Gtk, Gio
class MyApplication(Gtk.Application):
def __init__(self):
super().__init__(application_id="com.example.MyGtkApplication")
GLib.set_application_name('My Gtk Application')
def do_activate(self):
window = Gtk.ApplicationWindow(application=self, title="Hello World")
window.present()
button = Gtk.Button(label="Python+PyGObject+CSS修改背景色")
button.set_name("bricks-button")
button.set_halign(Gtk.Align.CENTER)
button.set_valign(Gtk.Align.CENTER)
button.set_size_request(250, 84)
window.add(button)
window.show_all()
strcss="""
#bricks-button {
color: #F55;
background-color: #eef;
background-image: -gtk-scaled(url('resource://css/brick.png'), url('resource://css/brick2.png'));
background-repeat: no-repeat;
background-position: center;
/* 测试 */
}
"""
strpath="./play.css"
fp = open(strpath, 'w')
fp.write(strcss)
fp.close()
provider = Gtk.CssProvider()
provider.connect("parsing-error", self.show_css_parsing_error)
# fname = Gio.file_new_for_path('play.css')
# provider.load_from_file(fname)
# https://docs.gtk.org/gtk4/method.CssProvider.load_from_file.html
# load_from_path, load_from_file, load_from_string
provider.load_from_path(strpath)
self.apply_css(window, provider)
def show_css_parsing_error(self, provider, section, error):
print(error.message)
def apply_css(self, widget, provider):
Gtk.StyleContext.add_provider(widget.get_style_context(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
if isinstance(widget, Gtk.Container):
widget.forall(self.apply_css, provider)
app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)
官方文档:CssProvider — GNOME Python API
Deprecated since version 4.12: Use load_from_string or load_from_bytes instead
Styling GTK3 in Python with CSS (Shallow Thoughts)
控件对应的CSS选择器名称(Built-in Class Names)
css = 'button { background-color: #f00; }'
CSS选择器名称可以改(User-set Class Names)
button_context = button.get_style_context()
button_context.add_class("whitebutton")
控件名称,映射为 HTML 标签的ID,在CSS中使用井号选择器
(Widget Names, like CSS ID)
label = gtk.Label() label.set_use_markup(True) label.set_line_wrap(True) label.set_name("red_label") mainbox.pack_start(label, False, False, 0) css = '#red_label { background-color: #f00; }' dflabel = gtk.Label()