How do I center the text in a Tkinter Text widget?

Tkinter's Text widget is a multiline text input widget used for inserting, deleting, and adding textual data. To center-align text in a Text widget, you need to use tags with the justify='center' property.

Basic Text Centering

Use tag_configure() to create a tag with center justification, then apply it to your text ?

from tkinter import *

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

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

text = Text(win)

# Configure the alignment of the text
text.tag_configure("center", justify='center')

# Insert a Demo Text
text.insert("1.0", "How do I center align the text in a Tkinter Text widget?")

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

win.mainloop()

How It Works

The centering process involves three steps:

  1. tag_configure("center", justify='center') creates a text tag with center justification
  2. text.insert("1.0", "text") inserts text at position 1.0 (line 1, character 0)
  3. tag_add("center", "1.0", "end") applies the center tag to the specified text range

Centering Multiple Lines

You can center multiple lines of text by applying the tag to the entire text range ?

from tkinter import *

win = Tk()
win.geometry("600x300")

text = Text(win, font=("Arial", 12))
text.tag_configure("center", justify='center')

# Insert multiple lines
text.insert("1.0", "Line 1: Centered Text\nLine 2: Also Centered\nLine 3: All Lines Centered")

# Apply center tag to all text
text.tag_add("center", "1.0", "end")
text.pack(padx=20, pady=20)

win.mainloop()

Centering Specific Text Portions

You can center only specific portions of text by specifying exact line and character positions ?

from tkinter import *

win = Tk()
win.geometry("600x300")

text = Text(win, font=("Arial", 11))
text.tag_configure("center", justify='center')
text.tag_configure("left", justify='left')

# Insert text with mixed alignment
text.insert("1.0", "This line is left-aligned\n")
text.insert("2.0", "This line is centered\n")
text.insert("3.0", "This line is also left-aligned")

# Apply different tags to different lines
text.tag_add("left", "1.0", "1.end")
text.tag_add("center", "2.0", "2.end")
text.tag_add("left", "3.0", "3.end")

text.pack(padx=20, pady=20)
win.mainloop()

Key Points

  • Use tag_configure() to create styling tags
  • Position format is "line.character" (e.g., "1.0" = line 1, character 0)
  • Use "end" to refer to the end of all text
  • Tags can be applied to specific text ranges for mixed alignment

Conclusion

Center text in Tkinter's Text widget using tag_configure("tag_name", justify='center') followed by tag_add(). This method allows flexible text alignment control for different portions of your text content.

Updated on: 2026-03-25T23:35:13+05:30

21K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements