How to Create a Text Box in Python Tkinter?

In this tutorial, I will explain how to create a text box in Python using the Tkinter library. I recently faced a challenge while developing a desktop application where I needed to capture user input and display it in a formatted manner. After thorough research and experimentation, I discovered the versatility of the Tkinter Text widget, and I’m excited to share my findings with you.

Tkinter Text Widget in Python

The Tkinter Text widget is a flexible and customizable component that enables developers to create text boxes in their Python applications. It provides a wide range of functionalities, such as:

  • Accepting single or multiple lines of user input
  • Displaying formatted text with various styles and colors
  • Enabling text editing, selection, and manipulation
  • Supporting scrolling for long text content

To create a text box using the Tkinter Text widget, import the library and instantiate a Text object within your application window.

Read How to Create Labels in Python with Tkinter?

Create a Text Box in Python Tkinter

Let’s get into a practical example to understand how to create a basic text box in Python Tkinter. Suppose you’re developing an application for a US-based company that requires employees to enter their name and a brief introduction. Here’s how you can create a text box to capture this information:

import tkinter as tk

window = tk.Tk()
window.title("Employee Introduction")

# Create a text box
text_box = tk.Text(window, height=5, width=40)
text_box.pack()

window.mainloop()

I executed the above example code you can refer to the screenshot below to see the output.

Create a Text Box in Python Tkinter

In this example:

  1. We import the Tkinter library using the alias tk.
  2. We create a new window using tk.Tk() and set its title to “Employee Introduction”.
  3. We create a Text widget using tk.Text() and specify the desired height and width in characters.
  4. We pack the text box into the window using the pack() method.
  5. Finally, we start the Tkinter event loop with window.mainloop() to display the window and text box.

Check out How to Create Buttons in Python with Tkinter?

Customize the Text Box in Python Tkinter

Tkinter provides several options to customize the appearance and behavior of the Text widget. Let’s explore some common customizations:

1. Text Box Font and Colors

You can set the font family, size, and style of the text using the font parameter. Additionally, you can control the text color and background color using the fg and bg parameters, respectively. Here’s an example:

text_box = tk.Text(window, height=5, width=40, font=("Arial", 12), fg="blue", bg="lightgray")

I executed the above example code you can refer to the screenshot below to see the output.

How to Create a Text Box in Python Tkinter

Read How to Create a Menu Bar in Tkinter?

2. Text Box Scrollbar

If you anticipate that the user might enter long text that exceeds the visible area of the text box, you can enable scrolling using the yscrollcommand parameter in conjunction with a Scrollbar widget. Here’s an example:

# Create a scrollbar
scrollbar = tk.Scrollbar(window)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# Create a text box with scrolling enabled
text_box = tk.Text(window, height=5, width=40, yscrollcommand=scrollbar.set)
text_box.pack()

# Configure the scrollbar to work with the text box
scrollbar.config(command=text_box.yview)

I executed the above example code you can refer to the screenshot below to see the output.

Create a Text Box in Python Tkinter Enable Scrolling

Check out How to Use Tkinter Entry Widget in Python?

3. Insert Text

To insert text into the text box programmatically, you can use the insert() method. Here’s an example:

# Insert initial text
text_box.insert(tk.END, "Enter your introduction here...")

# Retrieve the entered text
entered_text = text_box.get("1.0", tk.END)
print("Entered text:", entered_text)

I executed the above example code you can refer to the screenshot below to see the output.

Create a Text Box in Python Tkinter Insert and Retrieving Text

In this example, we insert an initial prompt text using text_box.insert(). The first argument specifies the position to insert the text (in this case, tk.END represents the end of the text box), and the second argument is the actual text to insert.

4. Text Box Not Editable

The text box widget in Python Tkinter provides a state option using which the Text box can be disabled. Once disabled, the user won’t be able to edit the the content of Text box in Python Tkinter.

# Message to insert into the text box
message = """Dear Reader,

    Thank you for giving your
    Love and Support to PythonGuides.
    PythonGuides is now available on 
    YouTube with the same name.

Thanks & Regards,
Team PythonGuides
"""

# Insert the initial message and make the text box non-editable
text_box.insert(tk.END, message)
text_box.config(state='disabled')

I executed the above example code you can refer to the screenshot below to see the output.

Create a Text Box in Python Tkinter text box not editable

Read How to Create Checkboxes in Python Tkinter?

5. Text Box Clear

The text box widget in Python Tkinter provides a delete() method using which we can clear the content of the text box widget.

delete() method accepts two arguments to clear the content of the Text box widget: starting point: accepts float value; starts from 1.0; it deletes the provided row. ending point: accepts float value; type ‘end’ to delete the entire data from the starting point.

text_box.delete(1.0, 5.0) # delete lines 1, 2, 3, 4
text_box.delete(5.0, 'end') # delete all lines except first four lines

I executed the above example code you can refer to the screenshot below to see the output.

Create a Text Box in Python Tkinter Text Box Clear

Check out How to Create and Customize Listboxes in Python Tkinter?

6. Text Box Get Value

The text box in Python Tkinter offers a method Get which allows fetching all the information stored in the Text box. The get method requires an Index as an argument that specifies the range of fetching the information.

text_box.get(1.0, 'end')

I executed the above example code you can refer to the screenshot below to see the output.

Create a Text Box in Python Tkinter get value

7. Text Box Word Wrap

The wrap is used to shift the word to the next line if the margin is reached to improve the readability. Python Tkinter Text box widget provides an option wrap using which we can wrap up the characters or words of the sentences inside Text box widget in Python Tkinter.

wrap='char', is used to wrap the sentence by character. Here the word breaks into sentences to cover the available space just before reaching the margin.

wrap=’word’, is used to wrap the sentence by the word. Here the words will jump to the next line if they don’t fit the space before reaching the margin.

text_box = Text(
    ws,
    height=13,
    width=40,
    wrap='word'
)

I executed the above example code you can refer to the screenshot below to see the output.

Create a Text Box in Python Tkinter wrap

Read How to Create Radio Buttons in Python with Tkinter?

8. Text Box Set Text

  • The set text option is to set the text on the widget but it is not applicable on the Text box widget.
  • In the Text box, we insert the data line by line similarly we delete the data line by line. The developer has to pass the argument about the start and end position of new data.
  • But while using set text we don’t need to pass any argument related to the position of data. This could be the possible reason why the Set text option or method is not available for the Text box.
  • If set text is used in Text Box then the following error will appear.
AttributeError: 'Text' object has no attribute 'set'

Handle Text Box Events

Python Tkinter allows you to handle various events associated with the Text widget, such as detecting when the text is modified or when the user interacts with the text box. Here are a couple of examples:

Check out How to use Tkinter Filedialog in Python

Detect Text Modification

You can use the <<Modified>> event to detect when the text in the text box is modified. Here’s an example:

def on_text_modified(event):
    print("Text modified!")

text_box.bind("<<Modified>>", on_text_modified)

In this example, we define a function on_text_modified() that will be called whenever the text in the text box is modified. We bind this function to the <<Modified>> event using text_box.bind().

Handle Key Press Events

You can handle specific key press events in the text box using the <Key> event. Here’s an example:

def on_enter_key(event):
    print("Enter key pressed!")

text_box.bind("<Return>", on_enter_key)

In this example, we define a function on_enter_key() that will be called whenever the Enter key is pressed within the text box. We bind this function to the <Return> event using text_box.bind().

Read Expense Tracking Application Using Python Tkinter

Example: Employee Feedback Form

Let’s put everything together and create a real-world example of a text box in a Python Tkinter application. Suppose you’re building an employee feedback form for a US-based company. Here’s how you can create a text box to capture employee feedback:

import tkinter as tk

def submit_feedback():
    feedback = text_box.get("1.0", tk.END)
    print("Submitted Feedback:")
    print(feedback)
    text_box.delete("1.0", tk.END)

window = tk.Tk()
window.title("Employee Feedback Form")

# Create a label
label = tk.Label(window, text="Please enter your feedback:")
label.pack()

# Create a text box
text_box = tk.Text(window, height=10, width=50, font=("Arial", 12))
text_box.pack()

# Create a submit button
submit_button = tk.Button(window, text="Submit", command=submit_feedback)
submit_button.pack()

window.mainloop()

In this example:

  1. We create a label using tk.Label() to provide instructions to the user.
  2. We create a text box using tk.Text() with a specified height and width to capture employee feedback.
  3. We create a submit button using tk.Button() and associate it with the submit_feedback() function.
  4. Inside the submit_feedback() function, we retrieve the entered feedback using text_box.get(), print it, and then clear the text box using text_box.delete().

When the user enters their feedback and clicks the submit button, the feedback will be printed, and the text box will be cleared, ready for the next feedback entry.

Check out Python Tkinter Separator + Examples

Conclusion

In this tutorial, I have explained how to create a text box in Python using the Tkinter library. I discussed how to create a simple text box, and how to customize the text box in Python Tkinter by setting the text box font and colors, Scrollbar, insert text, not editable, clear, get value, word wrap, and set text. I also covered how to handle text box events and a real-time example.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.