How to Text Justify in Python?
Asked Answered
K

0

1

I wrote a program to create a note pad. It has buttons toset text alignment.

def setAlignments(side):
    try:
        t1.tag_configure(side, justify=side)
        # Clipboard clearing and new selection append to the clipboard.
        copy_text()
        t1.delete('sel.first', 'sel.last')

        # Text_Widget.insert(Cursor_Position, Selection, Side)
        t1.insert(t1.index(INSERT), t1.clipboard_get(), side)
    except Exception as e:
        print("Error : ", e)
        pass

def leftAlign():
    setAlignments('left')

def centerAlign():
    setAlignments('center')

def rightAlign():
    setAlignments('right')

Here 't1' is my Text widget.

But I couldn't write a program to justify button. I tried with following coding part:

def justify():

    content = t1.get("1.0", "end-1c")
    lines = content.split('\n')

    max_line_width = t1.winfo_width() - t1.winfo_pixels("1i")

    justified_lines = []
    for line in lines:
        words = line.split()
        total_word_length = sum(len(word) for word in words)
        space_needed = max_line_width - total_word_length
        space_count = len(words) - 1

        if space_count > 0:
            space_between_words = space_needed // space_count
            extra_space = space_needed % space_count
            space_string = " " * space_between_words
            justified_line = words[0]
            for i, word in enumerate(words[1:], start=1):
                justified_line += space_string
                if i <= extra_space:
                    justified_line += " "
                justified_line += word
            justified_lines.append(justified_line)
        else:
            justified_lines.append(line)

    justified_text = '\n'.join(justified_lines)
    t1.delete("1.0", "end")
    t1.insert("1.0", justified_text)

But It had not my expecting result.

this result get same space between every two words. I think it should depend on each sentences. Here the program get multiple line for one sentence too. Can you help me to solve this problem ?

Knp answered 13/8, 2023 at 11:40 Comment(3)
It's not clear what you expect the justify function to do, since you can justify and wrap text with tags. Is justify actually trying to wrap the lines to a certain line length?Pomeranian
Need to align text to both left and right margins with adding extra spaces between words as necessary. I am using Text widget to do this.Knp
You might want to look at the textwrap module. It might have functions to do what you want.Pomeranian

© 2022 - 2024 — McMap. All rights reserved.