The Wayback Machine - https://web.archive.org/web/20240903074451/https://www.geeksforgeeks.org/python-tkinter-text-widget/
Open In App

Python Tkinter – Text Widget

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: 
 

Python3
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 
 

python-tkinter-text


Example 2: Saving Text and performing operations
 

Python3
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

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 Text class 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 Text or Entry widget, allows users to input one line (Entry) or multiple lines (Text) of text. The Text widget is suitable for larger amounts of text and provides more formatting options compared to Entry.

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 Text widget), 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



Previous Article
Next Article

Similar Reads

How to Set Text of Tkinter Text Widget With a Button?
Prerequisite: Python GUI – tkinter Text Widget is used where a user wants to insert multi-line text fields. In this article, we are going to learn the approaches to set the text inside the text fields of the text widget with the help of a button. Approach: Using insert and delete methodImport the Tkinter module.Create a GUI window.Create our text w
2 min read
Python Tkinter – How to display a table editor in a text widget?
In this article, we will discuss how to display a table editor in a text widget. Before moving ahead let's create a simple text widget first with the help of Tkinter. For the link to the Excel file used in the code click here. Text Widget The Text widget is used to show the text editor in the Tkinter window. A user can modify the text in the text e
3 min read
Hide Python Tkinter Text widget border
Tkinter is a standard GUI library for Python, providing tools to create graphical user interfaces easily. When designing interfaces, developers often encounter the need to customize widget appearances, including removing widget borders. Borders can sometimes clash with the desired aesthetic or layout of the application. This article explores what w
3 min read
Tkinter | Adding style to the input text using ttk.Entry widget
Tkinter is a GUI (Graphical User Interface) module which is widely used to create GUI applications. It comes along with the Python itself. Entry widgets are used to get the entry from the user. It can be created as follows- entry = ttk.Entry(master, option = value, ...) Code #1: Creating Entry widget and taking input from user (taking only String d
2 min read
Create Find and Replace features in Tkinter Text Widget
Prerequisites: Python GUI – tkinterFirstly we need to find all the words or letters that we want to replace in our below text for that we will use the find function in which we will determine all the starting and the ending indexes from the editor of the same word after that we will apply the replace functionality in which we will delete that part
4 min read
Change the color of certain words in the tkinter text widget
Python has various options for Graphical User Interface (GUI) development. One of the options is Tkinter. Tkinter and Python together provide a faster way for GUI development. The Tk GUI toolkit provides an object-oriented interface. For creating GUI applications using Tkinter we have to follow a few steps – Import Tkinter module.Create the main wi
3 min read
How to Set the Default Text of Tkinter Entry Widget?
The Tkinter Entry widget does not have any text attribute that can be used to set the default text. Therefore, default text must be added to any text field in Tkinter using the following methods: Insert methodstringvar method Method 1: Using the insert method The tkinter module is imported. The root widget is created and this must be done before cr
2 min read
How to set the tab size in Text widget in Tkinter?
Prerequisite: Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tki
2 min read
How to stop copy, paste, and backspace in text widget in tkinter?
In this article, we will see how to stop backspacing, copying, and pasting in the text widget in Tkinter. In order to disable copying, pasting, and backspacing in Tkinter a Text widget, you’ve to bind the event with an event handler, binding helps us to create complex GUI applications that bind some specific key to functions, which execute when tha
2 min read
How To Make The Tkinter Text Widget Read Only?
The Tkinter library in Python provides a powerful and flexible way to create GUI applications. One of the widgets available in Tkinter is the Text widget, which is used for displaying and editing multi-line text. However, there might be situations where you want the Text widget to be read-only, preventing users from modifying its content. This arti
3 min read
Underline Text In Tkinter Label Widget
Tkinter is a module in Python which is used to create GUI applications. It has many useful widgets such as Label, Button, Radiobutton, Checkbutton, Listbox, and more. In this article, we will learn about changing the color of a Tkinter label widget in Python. By default, the text of a Label in Tkinter is not underlined. To have an underline in a te
3 min read
Difference Between The Widgets Of Tkinter And Tkinter.Ttk In Python
Python offers a variety of GUI (Graphical User Interface) frameworks to develop desktop applications. Among these, Tkinter is the standard Python interface to the Tk GUI toolkit. Tkinter also includes the 'ttk' module, which enhances the visual appeal and functionality of the applications. In this article, we will cover the differences, providing a
4 min read
How to wrap text within Tkinter Text Box?
In this article, we will see that how can we wrap the text in the TKinter Text-Box using the Tkinter module Called textWrap Module. The textwrap module can be used for wrapping and formatting plain text. This module provides formatting of the text by adjusting the line breaks in the input paragraph. Example 1: Firstly We will import the Tkinter Lib
2 min read
Python | Menu widget in Tkinter
Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the most commonly used package for GUI applications which comes with the Python itself. Menus are the important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipu
2 min read
Progressbar widget in Tkinter | Python
The purpose of this widget is to reassure the user that something is happening. It can operate in one of two modes - In determinate mode, the widget shows an indicator that moves from beginning to end under program control. In indeterminate mode, the widget is animated so the user will believe that something is in progress. In this mode, the indica
2 min read
Python | PanedWindow Widget in Tkinter
Tkinter supports a variety of widgets to make GUI more and more attractive and functional. The PanedWindow widget is a geometry manager widget, which can contain one or more child widgets panes. The child widgets can be resized by the user, by moving separator lines sashes using the mouse. Syntax: PanedWindow(master, **options) Parameters: master:
3 min read
Python Tkinter - Toplevel 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 Toplevel widget A Toplevel widget is used to create a window on top of all other w
3 min read
Combobox Widget in tkinter | Python
Python provides a variety of GUI (Graphic User Interface) types such as PyQT, Tkinter, Kivy, WxPython, and PySide. Among them, tkinter is the most commonly used GUI module in Python since it is simple and easy to understand. The word Tkinter comes from the Tk interface. The tkinter module is available in Python standard library which has to be impo
3 min read
Python Tkinter - ListBox 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 ListBox widget The ListBox widget is used to display different types of items. The
2 min read
Python Tkinter - Scale 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 Scale widget The Scale widget is used whenever we want to select a specific value
2 min read
Python Tkinter - Canvas 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 Canvas widget The Canvas widget lets us display various graphics on the application
3 min read
Python Tkinter - MessageBox Widget
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy ta
2 min read
Python Tkinter - Menubutton Widget
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy ta
4 min read
Creating Tabbed Widget With Python-Tkinter
Python offers a range of GUI frameworks that can be used to develop GUI based applications in Python. The most widely used Python interface is Tk interface or tkinter( as renamed in Python 3.x) . The Tkinter module offers a wide range of widgets that can be used to develop GUI applications much faster and easier compared to the other interfaces off
5 min read
Python Tkinter - Validating Entry Widget
Python offers a variety of frameworks to work with GUI applications. Tkinter or Tk interface is one of the most widely used Python interface to build GUI based applications. There are applications that require validation of text fields to prevent invalid input from the user before the form is submitted. Python allows input validation by allowing va
5 min read
Python Tkinter - ScrolledText Widget
Tkinter is a built-in standard python library. With the help of Tkinter, many GUI applications can be created easily. There are various types of widgets available in Tkinter such as button, frame, label, menu, scrolledtext, canvas and many more. A widget is an element that provides various controls. ScrolledText widget is a text widget with a scrol
3 min read
Python Tkinter - Frame Widget
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
3 min read
Python Tkinter - Checkbutton Widget
The Checkbutton widget is a standard Tkinter widget that is used to implement on/off selections. Checkbuttons can contain text or images. When the button is pressed, Tkinter calls that function or method. Note: For more reference, you can read our article, What is WidgetsPython Tkinter OverviewPython Tkinter TutorialTkinter Checkbutton Widget Synta
5 min read
Validating Entry Widget In Python Tkinter
When developing graphical user interfaces (GUIs) in Python, Tkinter is a powerful and widely-used toolkit that simplifies the process. One of the common tasks in GUI applications is obtaining user input through form fields. Tkinter's Entry widget is designed for this purpose, allowing users to input text. However, ensuring the correctness of the en
7 min read
Access the Actual Tab Widget of ttk.Notebook in Python Tkinter
Tab widgets of ttk.Notebook are essential components in a Tkinter GUI for organizing content into multiple tabs. Accessing these tab widgets allows for customization and manipulation of their properties. In this article, we will explore two different approaches to accessing the actual tab widget of ttk.Notebook. Access the actual tab widget of ttk.
2 min read
Practice Tags :