Sunday, February 18, 2007

Getting text from a TextView

It took some searching to see how to get the string contained in a TextView with a string (hint: there's no textview.get_text()), but here's the snippet I came up with:

notes_txt = self.widgets.get_widget('notesTxt').get_buffer()
startiter, enditer = notes_txt.get_bounds()
character = dbaccess.fetch_character(self.char_id)
notes_file = open(character['name'] + "-notes.txt", "w")
notes_file.write(notes_txt.get_text(startiter, enditer))
notes_file.close()

Basically, you have to find the start and end Iters to set the bounds of the text you want.

Populating is trivial:

try:
notes_file = open(character['name'] + "-notes.txt", "r")
text = self.widgets.get_widget('notesTxt').get_buffer()
text.set_text(notes_file.read())
notes_file.close()
except:
print "No notes file found: ", character['name'] + \
"-notes.txt"