1

I have written a function like this:

def alignRight(canvas,project):
    curPos = text.index(INSERT)
    startPos = text.index("%s.0" % (curPos[0]))
    endPos = text.index("%s.end" % (curPos[0]))
    text.tag_configure("right", justify='right')
    text.tag_add("right", startPos, endPos)
    project.file = text.get(1.0,'end-1c')

This is working fine. But when I try to save project.file into a .txt file. It loses the align-to-right style that I gave to it. (text is a Text widget)

Is there a way to work around this issue? Thank you!

Also, if it is about .txt files that they cannot inherent the styles, is it possible to save content in a text widget into a .docx file? Or is that something really difficult to do?

Hongrun Zhou
  • 75
  • 2
  • 10
  • Text files don't contain formatting information. Saving to a .docx file would be fairly difficult. – Bryan Oakley Nov 28 '17 at 12:48
  • As @Bryan Oakley pointed, it's fairly difficult task and also involves external dependencies and cumbersome solutions. If you trying to achieve something not-so-complex and if you ok with ancient technologies, you can [`dump`](https://www.tcl.tk/man/tcl8.4/TkCmd/text.htm#M82) structured content of the `text` widget and generate a [rtf](https://en.wikipedia.org/wiki/Rich_Text_Format)-formatted string fromt it by yourself. Difficulty is relative to demands ([link1](https://www.askingbox.com/info/rtf-align-text-left-right-centered-and-justified), [link2](http://www.pindari.com/rtf1.html)). – CommonSense Nov 28 '17 at 13:54
  • Okay. Thanks guys! – Hongrun Zhou Nov 28 '17 at 15:23

1 Answers1

1

text.get gets the sequence of characters (unicode codepoints, actually) in the widget. Tags and Text widget attributes are stored separately and are ignored by get. There are methods to get the current tags and their start and end positions. So it would be possible to write out a text, followed by tag specifications.

I have no idea how possible or easy it would be to convert tags to docx styles and positions, or any other formats.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
  • @Hongrun Zhou, I think that you should accept this answer. There's things that can be contributed to this answer (for e.g. an obvious notice that `.txt` is a [plain text](https://stackoverflow.com/questions/14492138/mime-type-for-txt-files) and a notice about [`dump`](http://effbot.org/tkinterbook/text.htm#Tkinter.Text.dump-method) method, which produces a sequence (a list) of tuples, which contains tag/text information and which can be potentially converted to format with code syntax or markup language (rtf, html, xml) without any dependency. But as is it's already an answer, so.. – CommonSense Nov 28 '17 at 16:07
  • @CommonSense Yeah, thanks for the reminder... I totally forgot to accept an answer haha. And thank you for the information too I am looking into it! :) – Hongrun Zhou Nov 29 '17 at 01:03