pythoncolorsgtk3gtktextview

GTK3+ TextView add lines of text with different colors per line


I'm slightly stumped right now, i use a TextView as a status log, new lines added whenever something happens, this is the function i use for that, probably not right but it does work however i can't make it add changing the color of the entire line.

def logtostatus(self, text):
    tvLog = self.tabs['Status'][1].get_children()[0].get_children()[0]
    buf = tvLog.get_buffer()
    start = buf.get_end_iter()
    buf.insert(start, text+"\n")
    end = buf.get_end_iter()

This does insert text, and i had various versions trying to use TextTag's but it refused to work so since i ran out of ideas, i'm asking you all out there, please help, this is driving me nuts.

Thank you


Solution

  • This works for me:

    from gi.repository import Gtk
    
    class MainWindow(Gtk.Window):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.connect("destroy", lambda x: Gtk.main_quit())
    
            tb = Gtk.TextBuffer()
            tv = Gtk.TextView(buffer = tb)
    
            for color in ("red", "yellow", "green", "blue", "white"):
                tb.insert_markup(
                    tb.get_end_iter(),
                    '<span color="{:s}">This is a test message</span>\n'.format(color),
                    -1)
    
            self.add(tv)
            self.show_all()
    
        def run(self):
            Gtk.main()
    
    
    def main(args):
        mainwdw = MainWindow()
        mainwdw.run()
    
        return 0
    
    if __name__ == '__main__':
        import sys
        sys.exit(main(sys.argv))
    

    It seems the easiest way to play with colors. This is the result:

    enter image description here