Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to word-wrap text in Tkinter Text?
Word wrapping is an essential feature in text editors that automatically breaks long lines to fit within the available width. In Tkinter, the Text widget provides a wrap parameter to control how text wrapping behaves. This parameter accepts three values: WORD, CHAR, or NONE.
Wrap Options
The wrap parameter determines how text flows in the Text widget ?
-
WORD− Wraps text at word boundaries (default and most readable) -
CHAR− Wraps text at any character position -
NONE− No wrapping, text extends horizontally with scrollbar
Example 1: Word Wrapping
This example demonstrates wrapping text at word boundaries ?
import tkinter as tk
# Create the main window
window = tk.Tk()
window.geometry("400x200")
window.title("Word Wrap Example")
# Create Text widget with word wrapping
text_widget = tk.Text(window, wrap=tk.WORD, width=40, height=10)
text_widget.pack(padx=10, pady=10)
# Insert sample text
sample_text = "Python is an interpreted, high-level programming language. Its design philosophy emphasizes code readability with significant indentation. Python supports multiple programming paradigms including procedural, object-oriented, and functional programming."
text_widget.insert(tk.INSERT, sample_text)
window.mainloop()
Example 2: Character Wrapping
Here's how character-level wrapping works ?
import tkinter as tk
window = tk.Tk()
window.geometry("400x200")
window.title("Character Wrap Example")
# Text widget with character wrapping
text_widget = tk.Text(window, wrap=tk.CHAR, width=40, height=10)
text_widget.pack(padx=10, pady=10)
text_widget.insert(tk.INSERT, "This text will wrap at any character position, even breaking words in the middle if necessary.")
window.mainloop()
Example 3: No Wrapping
When wrapping is disabled, text extends horizontally ?
import tkinter as tk
window = tk.Tk()
window.geometry("400x200")
window.title("No Wrap Example")
# Text widget without wrapping
text_widget = tk.Text(window, wrap=tk.NONE, width=40, height=10)
text_widget.pack(padx=10, pady=10)
text_widget.insert(tk.INSERT, "This very long line will not wrap and will extend beyond the visible area requiring horizontal scrolling to view the complete text.")
window.mainloop()
Comparison
| Wrap Option | Behavior | Best For |
|---|---|---|
WORD |
Breaks at word boundaries | Readable text documents |
CHAR |
Breaks at any character | Code or data with long strings |
NONE |
No automatic wrapping | Preserving original line structure |
Conclusion
Use wrap=WORD for most text applications as it provides the best readability. Choose CHAR when you need to fit content within specific width constraints, and NONE when preserving original formatting is important.
