Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 40 ยท Widgets Basics

The Tkinter Text and ScrolledText Widgets

Work with the multi-line Tkinter Text widget: line.column indexes, reading and inserting text, tags for styling, search, undo, scrollbars and ScrolledText.

When one line is not enough, use Text. It is a full multi-line editor: it wraps, scrolls, undoes, searches and can show different fonts and colors in the same paragraph. It is also the most index-heavy widget in Tkinter, so the first job is to understand how it names positions.

Creating a Text widget

Python
import tkinter as tk

root = tk.Tk()
text = tk.Text(root, width=50, height=10, wrap="word", undo=True,
               font=("Consolas", 11), padx=6, pady=6)
text.pack(fill="both", expand=True)
text.insert("1.0", "First line\nSecond line\n")
root.mainloop()

Notable options: wrap ("none", "char" or "word"), undo=True (enables Ctrl+Z and Ctrl+Y), state ("normal" or "disabled"), spacing1/spacing2/spacing3 (line spacing), tabs, and width/height in characters and lines.

Indexes: "line.column"

A position in a Text is the string "line.column". Lines count from 1, columns from 0:

Index Meaning
"1.0" Very start (line 1, before the first character)
"2.5" Line 2, before the sixth character
"end" or tk.END After the final newline (always one past the last character)
"end-1c" The last real character position (subtract one character)
"insert" The cursor
"sel.first", "sel.last" The selection
"1.end" End of line 1
"insert linestart", "insert lineend" Modifiers: start or end of the cursor's line
"insert +3c", "insert -1l" Move by 3 characters or back one line
"mark" A named mark you create with mark_set

A Text always ends with an invisible newline, so get("1.0", "end") returns your content plus "\n". Use get("1.0", "end-1c") to get exactly what the user typed. This is the single most common Text bug.

An index parser you can run

The rules above are easy to implement over a Python string. The stand-in below parses "line.col", "end" and "end-1c" against a list of lines, which is a good way to check you have the model right.

Python Stand-in: Text indexes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading and changing text

Python
content = text.get("1.0", "end-1c")      # everything the user typed
first_line = text.get("1.0", "1.end")
text.insert("end", "appended\n")
text.insert("insert", "typed at the cursor")
text.delete("1.0", "end")                # clear
text.delete("1.0", "2.0")                # delete the first line
text.see("end")                          # scroll to the bottom
text.replace("1.0", "1.5", "New")        # replace a range (Tk 8.6)

If you set state="disabled" to make a read-only log, remember that code cannot edit it either. The pattern is:

Python
def log(message):
    text.config(state="normal")
    text.insert("end", message + "\n")
    text.see("end")
    text.config(state="disabled")

Scrollbars and ScrolledText

A Text does not show scrollbars on its own. Connect a Scrollbar in both directions, with yscrollcommand moving the bar and command moving the text:

Python
frame = tk.Frame(root)
frame.pack(fill="both", expand=True)

scroll = tk.Scrollbar(frame, orient="vertical")
text = tk.Text(frame, wrap="word", yscrollcommand=scroll.set)
scroll.config(command=text.yview)

scroll.pack(side="right", fill="y")
text.pack(side="left", fill="both", expand=True)

For the common case, the tkinter.scrolledtext module does this wiring for you:

Python
from tkinter.scrolledtext import ScrolledText

box = ScrolledText(root, width=60, height=15, wrap="word")
box.pack(fill="both", expand=True)

ScrolledText is a Text with a vertical scrollbar packed alongside; everything else works exactly as in Text. Horizontal scrolling still needs a manual scrollbar and wrap="none". Scrollbars are covered more fully in Listbox and Scrollbar.

Tags: styling parts of the text

A tag is a name attached to a range. You configure the tag's look once, then apply it to as many ranges as you like.

Python
text.tag_configure("title", font=("Georgia", 18, "bold"), foreground="#264653")
text.tag_configure("warn", background="#ffe8a1")
text.tag_configure("link", foreground="blue", underline=True)

text.insert("end", "Report\n", "title")             # insert with a tag
text.insert("end", "Normal text, then ")
text.insert("end", "a warning", "warn")
text.insert("end", "\n")
text.tag_add("link", "1.0", "1.3")                   # tag existing text
text.tag_remove("link", "1.0", "end")
text.tag_bind("link", "<Button-1>", lambda e: print("link clicked"))

Tags can set foreground, background, font, underline, overstrike, justify, lmargin1, lmargin2, spacing1 and more. When several tags cover the same text, the one created last (or raised with tag_raise) wins conflicting options. Tags are the basis of syntax highlighting, chat logs with colored names and clickable links.

The next stand-in finds words in a string and returns the "line.col" ranges to tag, which is the core of any highlighter.

Python Stand-in: find ranges to tag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Search, marks and undo

Python
start = "1.0"
count = tk.IntVar()
while True:
    pos = text.search("TODO", start, stopindex="end", count=count, nocase=True)
    if not pos:
        break
    end = f"{pos}+{count.get()}c"
    text.tag_add("warn", pos, end)
    start = end

text.search(pattern, start, ...) returns the index of the next match or an empty string. count receives the match length, which is needed for regular expressions (regexp=True). Marks are invisible bookmarks that move with the text (text.mark_set("here", "2.4")), and with undo=True you also get text.edit_undo(), edit_redo(), edit_reset() and edit_modified() for "unsaved changes" detection.

You can also embed widgets with window_create("end", window=button) and images with image_create, which is how rich text viewers add buttons inside a document.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the index '2.5' refer to?

    Text indexes are 'line.column', where lines start at 1 and columns at 0.
  2. 2. Which call returns exactly what the user typed, without an extra newline?

    Text keeps a hidden final newline, so 'end-1c' stops just before it.
  3. 3. How do you give part of a Text a different color?

    Configure a tag with tag_configure, then insert or tag_add that range.
  4. 4. Why does a read-only log Text need state to be switched back to 'normal' before insert()?

    Disabled widgets block all edits. Enable, insert, then disable again.

Summary

  • Text holds multi-line, styled text; indexes are "line.column" with lines from 1 and columns from 0.
  • Use get("1.0", "end-1c") for the real content; insert, delete, replace and see edit and navigate.
  • Wire a Scrollbar manually or use ScrolledText for a vertical bar.
  • Tags style ranges (fonts, colors, links) and can have their own event bindings.
  • search, marks and undo=True provide the editor features you expect.

Next: Checkbuttons and Radiobuttons