Python Tkinter – Text Widget
Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is the most commonly used and the most basic GUI framework available in python. Tkinter uses an object-oriented approach to make GUIs.
Note: For more information, refer to Python GUI – tkinter
Text Widget
Text Widget is used where a user wants to insert multiline text fields. This widget can be used for a variety of applications where the multiline text is required such as messaging, sending information or displaying information and many other tasks. We can insert media files such as images and links also in the Textwidget.
Syntax:
T = Text(root, bg, fg, bd, height, width, font, ..)
Optional parameters
- root – root window.
- bg – background colour
- fg – foreground colour
- bd – border of widget.
- height – height of the widget.
- width – width of the widget.
- font – Font type of the text.
- cursor – The type of the cursor to be used.
- insetofftime – The time in milliseconds for which the cursor blink is off.
- insertontime – the time in milliseconds for which the cursor blink is on.
- padx – horizontal padding.
- pady – vertical padding.
- state – defines if the widget will be responsive to mouse or keyboards movements.
- highlightthickness – defines the thickness of the focus highlight.
- insertionwidth – defines the width of insertion character.
- relief – type of the border which can be SUNKEN, RAISED, GROOVE and RIDGE.
- yscrollcommand – to make the widget vertically scrollable.
- xscrollcommand – to make the widget horizontally scrollable.
Some Common methods
- index(index) – To get the specified index.
- insert(index) – To insert a string at a specified index.
- see(index) – Checks if a string is visible or not at a given index.
- get(startindex, endindex) – to get characters within a given range.
- delete(startindex, endindex) – deletes characters within specified range.
Tag handling methods
- tag_delete(tagname) – To delete a given tag.
- tag_add(tagname, startindex, endindex) – to tag the string in the specified range
- tag_remove(tagname, startindex, endindex) – to remove a tag from specified range
Mark handling methods
- mark_names() – to get all the marks in the given range.
- index(mark) – to get index of a mark.
- mark_gravity() – to get the gravity of a given mark.
Example 1:
import tkinter as tk
root = Tk()
# specify size of window.
root.geometry("250x170")
# Create text widget and specify size.
T = Text(root, height = 5, width = 52)
# Create label
l = Label(root, text = "Fact of the Day")
l.config(font =("Courier", 14))
Fact = """A man can be arrested in
Italy for wearing a skirt in public."""
# Create button for next text.
b1 = Button(root, text = "Next", )
# Create an Exit button.
b2 = Button(root, text = "Exit",
command = root.destroy)
l.pack()
T.pack()
b1.pack()
b2.pack()
# Insert The Fact.
T.insert(tk.END, Fact)
tk.mainloop()
Output

Example 2: Saving Text and performing operations
from tkinter import *
root = Tk()
root.geometry("300x300")
root.title(" Q&A ")
def Take_input():
INPUT = inputtxt.get("1.0", "end-1c")
print(INPUT)
if(INPUT == "120"):
Output.insert(END, 'Correct')
else:
Output.insert(END, "Wrong answer")
l = Label(text = "What is 24 * 5 ? ")
inputtxt = Text(root, height = 10,
width = 25,
bg = "light yellow")
Output = Text(root, height = 5,
width = 25,
bg = "light cyan")
Display = Button(root, height = 2,
width = 20,
text ="Show",
command = lambda:Take_input())
l.pack()
inputtxt.pack()
Display.pack()
Output.pack()
mainloop()
Output

Python Tkinter – Text Widget – FAQs
How Do I Add a Text Widget in Tkinter?
In Tkinter, a text widget is used to display multi-line text fields where users can enter or display text. Here’s how to add a text widget:
Example:
import tkinter as tk
root = tk.Tk()
# Create a Text widget
text_widget = tk.Text(root, height=10, width=50)
text_widget.pack()
root.mainloop()
How to Display a Text File in Python Tkinter?
To display the contents of a text file in a Tkinter application, you can read the file and insert the contents into a Text widget:
Example:
import tkinter as tk
def load_text():
with open('file.txt', 'r') as file:
data = file.read()
text_widget.insert(tk.END, data)
root = tk.Tk()
text_widget = tk.Text(root, height=10, width=50)
text_widget.pack()
load_text()
root.mainloop()
How Do I Create a Custom Text Widget?
Creating a custom text widget involves subclassing the
Textclass from Tkinter and adding your custom behavior or appearance modifications:Example:
import tkinter as tk
class CustomText(tk.Text):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.config(foreground='blue', background='lightgray') # Custom styles
root = tk.Tk()
custom_text_widget = CustomText(root, height=10, width=50)
custom_text_widget.pack()
root.mainloop()
What is a Text Box Widget in Python?
A text box widget in Python, typically created using Tkinter’s
TextorEntrywidget, allows users to input one line (Entry) or multiple lines (Text) of text. TheTextwidget is suitable for larger amounts of text and provides more formatting options compared toEntry.Example:
import tkinter as tk
root = tk.Tk()
# Creating a Text Box for multi-line text input
text_box = tk.Text(root, height=5, width=30)
text_box.pack()
root.mainloop()
How to Set Default Text in Textbox Tkinter?
To set default text in a Tkinter textbox (using the
Textwidget), you can insert text into it at the start:Example:
import tkinter as tk
root = tk.Tk()
text_box = tk.Text(root, height=5, width=30)
text_box.pack()
# Inserting default text
text_box.insert(tk.END, "Type your text here...")
root.mainloop()This setup allows you to create and customize text widgets effectively in a Tkinter-based GUI, suitable for various applications that require text input or display

