How to set justification on Tkinter Text box?

The Text widget supports multiline user input from the user. We can configure the Text widget properties such as its font properties, text color, background, etc., by using the configure() method.

To set the justification of our text inside the Text widget, we can use tag_add() and tag_configure() methods. We will specify the value of "justify" as CENTER, LEFT, or RIGHT.

Basic Text Justification

Here's how to create a Text widget with center justification ?

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Create a text widget
text = Text(win, width=40, height=10)

# Justify the text alignment to the center
text.tag_configure("center", justify='center')
text.insert(INSERT, "Welcome to Tutorialspoint...")

# Add the tag from start to end text
text.tag_add("center", 1.0, "end")
text.pack()

win.mainloop()

Multiple Justification Options

You can set different justification styles using various values ?

from tkinter import *

win = Tk()
win.geometry("700x400")

text = Text(win, width=50, height=15)

# Configure different justification tags
text.tag_configure("left", justify='left')
text.tag_configure("center", justify='center') 
text.tag_configure("right", justify='right')

# Insert text with different justifications
text.insert("1.0", "Left aligned text\n")
text.tag_add("left", "1.0", "1.end")

text.insert("2.0", "Center aligned text\n")
text.tag_add("center", "2.0", "2.end")

text.insert("3.0", "Right aligned text\n")
text.tag_add("right", "3.0", "3.end")

text.pack()
win.mainloop()

Key Points

  • tag_configure() creates a style configuration with a name
  • tag_add() applies the tag to specific text ranges
  • Justification options are: 'left', 'center', and 'right'
  • Text positions use "line.column" format (e.g., "1.0" means line 1, column 0)

Output

When you run the above code, you will observe that the text in the Text widget displays with the specified justification. The center-aligned text appears in the middle of the widget, while left and right alignments position text accordingly.

Left aligned text Center aligned text Right aligned text Tkinter Text Widget with Different Justifications

Conclusion

Use tag_configure() and tag_add() to set text justification in Tkinter Text widgets. This allows you to control text alignment for different sections of your text content.

Updated on: 2026-03-26T00:17:21+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements