简体   繁体   中英

How to get background of textview in pygobject “gtk3”?

I'd like to get the current background color of my textview to change it and restore it later.

here what I tried:

context = textview.get_style_context()
state = Gtk.StateFlags.NORMAL
color = context.get_background_color(state)

I tried all possible states, but none returns the correct background color (white in my case)

Any idea how to get it?

I'm not exactly sure what you specific problem is without seeing more code, but here is a quick example that overrides the background and then restores it on a button click:

from gi.repository import Gtk, Gdk
import sys


class MyWindow(Gtk.ApplicationWindow):
    def __init__(self, app):
        Gtk.Window.__init__(self, title="Textview example", application=app)
        self.set_default_size(250, 100)
        self.set_border_width(10)

        self.view = Gtk.TextView()
        self.style_context = self.view.get_style_context()
        self.default_bg_color = self.style_context.get_background_color(Gtk.StateFlags.NORMAL)
        self.view.override_background_color(Gtk.StateFlags.NORMAL,
                                            Gdk.RGBA(0, 0, 0, 1))

        self.btn = Gtk.Button(label="Click Here")
        self.btn.connect("clicked", self.on_btn_clicked)

        box = Gtk.VBox()
        box.pack_start(self.view, True, True, 0)
        box.pack_start(self.btn, False, False, 0)
        self.add(box)

    def on_btn_clicked(self, widget):
        current_bg = self.style_context.get_background_color(Gtk.StateFlags.NORMAL)
        if current_bg == self.default_bg_color:
            self.view.override_background_color(Gtk.StateFlags.NORMAL,
                                                Gdk.RGBA(0, 0, 0, 1))
        else:
            self.view.override_background_color(Gtk.StateFlags.NORMAL, 
                                                self.default_bg_color)


class MyApplication(Gtk.Application):
    def __init__(self):
        Gtk.Application.__init__(self)

    def do_activate(self):
        win = MyWindow(self)
        win.show_all()

    def do_startup(self):
        Gtk.Application.do_startup(self)

app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM