How to set the justification of the text to "Justify" in tkinter?

Question:

I am trying to justify the text from tkinter text. The other answers (How to set justification on Tkinter Text box)said that it is my answer. I am try to use this code (I am using tkinter 8.6 and Python 3):

import tkinter
root = tkinter.Tk()
text_widget = tkinter.Text()
text_widget.pack(fill='both', expand=True)
text_widget.tag_configure('tag-center', justify='justify')
text_widget.insert('end', 'text ' * 10, 'tag-center')

but then, if I run the code:

Traceback (most recent call last):
  File "C:/Users/moon/AppData/Local/Programs/Python/Python310/asking1.py", line 5, in <module>
    text_widget.tag_configure('tag-center', justify='justify')
  File "C:UsersmoonAppDataLocalProgramsPythonPython310libtkinter__init__.py", line 3888, in tag_configure
    return self._configure(('tag', 'configure', tagName), cnf, kw)
  File "C:UsersmoonAppDataLocalProgramsPythonPython310libtkinter__init__.py", line 1665, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: bad justification "justify": must be left, right, or center

It said "_tkinter.TclError: bad justification "justify": must be left, right, or center, but no justify. I saw it that both MS Word and LO Writer has Justify. How to do it? Thank you!

Please click this link: Word Justification

Asked By: Misinahaiya

||

Answers:

Sadly, the Tkinter Text has only three justify option: left, center and right aligns. But don’t be disappointed, you may try something called spacing2 and discover it by using tags and option configuration. Try it!

P.S. You may also try PyQt5. They may have justify option. wxPython is also a good choice.

Answered By: Jason CAI

em actually there’s NO justicfy function in tkinter. it has only "left" (tk.LEFT), "center" (tk.CENTER) or "right" (tk.RIGHT)

but dont be disappointed, like mr jason said pyqt5 has the following justify options:

import PyQt5.QtCore
# import PySide5.QtCore

PyQt5.QtCore.Qt.AlignLeft      # PySide6.QtCore.Qt.AlignLeft
PyQt5.QtCore.Qt.AlignHCenter   # PySide6.QtCore.Qt.AlignHCenter
PyQt5.QtCore.Qt.AlignRight     # PySide6.QtCore.Qt.AlignRight
PyQt5.QtCore.Qt.AlignJustify   # PySide6.QtCore.Qt.AlignJustify
PyQt5.QtCore.Qt.AlignTop       # PySide6.QtCore.Qt.AlignTop
PyQt5.QtCore.Qt.AlignBottom    # PySide6.QtCore.Qt.AlignBottom
PyQt5.QtCore.Qt.AlignVCenter   # PySide6.QtCore.Qt.AlignVCenter
PyQt5.QtCore.Qt.AlignBaseline  # PySide6.QtCore.Qt.AlignBaseline

so why not use pyqt5 for gui applications happily? 🙂

edit:

u can also use PyQt5.QtWidgets.QTextEdit.setAlignment([Justification]) to set the justification if u r using qtextedit

Answered By: Scott
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.