FlissieT FlissieT - 7 days ago 8
Python Question

How to add a new line in Gtk textview?

Here is my problem, I can't quite find the answer elsewhere. I want to show some text in a Gtk textview (python3), with a new line after each piece of text. When I use "\n", it shows "\n" rather than actually adding in a new line. Is there a way that I can fix this?

This should be a reproducible version of my problem and then my output... (ps. I'm not an experienced programmer)

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

records = ()
tv = Gtk.TextView()

records += ("a", "\n", "b", "\n", "c", "\n")
tb = tv.get_buffer()
tb.set_text(str(records))

sw = Gtk.ScrolledWindow()
sw.set_size_request(300,400)
sw.add(tv)

w = Gtk.Window()
w.add(sw)
w.show_all()

Gtk.main()


current output in Gtk window:

('a','\n','b', '\n', 'c')


desired output in Gtk window:

'a'
'b'
'c'

Answer

I have been shown a way to solve this problem by using %s string formatting. Here is a sample of the code I was actually working with:

tv = Gtk.TextView()
    for record in records:
        records_str += "Title: %s \nAuthors: %s \nSource: %s\n\n" %(record.get("TI"), ", ".join(record.get("AU")), record.get("SO"))

    tb = tv.get_buffer()
    tb.set_text("".join(records_str)) 

This prints "Title", "Author" and "Source" on separate lines.

Comments