Cut, Copy and Paste Text in Tkinter Text Widgets

To select text in a Tkinter Text widget, use tag_add("sel", ...). You can then use the built-in <<Copy>> and <<Paste>> events to transfer the selection between two Text widgets. Replace Copy with <<Cut>> to remove the selection after copying.

e1.tag_add("sel", "1.0", "end-1c")   # Select source text
e1.event_generate("<<Copy>>")        # Copy to clipboard
e2.event_generate("<<Paste>>")       # Paste into second Text widget

These commands assume the application already has two Text widgets named e1 and e2. See the complete runnable example below. The main program also demonstrates the explicit system clipboard methods for reliable button actions.

Tkinter Text widgets with Select All, Cut, Copy and Paste buttons for transferring multiline text
Select text in the first Text box, then cut or copy it and paste into the second Text box.

What this Tkinter example does

The application has a source Text widget and a destination Text widget. Four buttons let you select text, cut it, copy it or paste it. The clipboard method stores copied text on the operating system clipboard, so the text can also be pasted into other compatible applications.

ButtonActionResult
Select Alltag_add("sel", ...)Selects the source text
Cutclipboard_append() and delete()Copies and removes the selection
Copyclipboard_append()Copies without deleting
Pasteclipboard_get() and insert()Adds text to the destination

Select All or Part of the Text Widget

A tk.Text widget can store multiple lines. Its indexes use the line.character format: "1.0" is the first character of the first line. The sel tag represents selected text. The end-1c index excludes Tkinter's final automatically maintained newline.

def select_all():
    e1.tag_add("sel", "1.0", "end-1c")
    e1.mark_set("insert", "1.0")
    e1.focus_set()

The optional focus_set() moves keyboard focus back to the source box after selecting all its text. In the full application we set exportselection=False on the source Text widget, so pressing a separate Copy or Cut button does not unexpectedly lose access to the selection on some platforms.

Read only the selected text

Unlike an Entry widget, a Text widget uses its sel tag to identify a selection. Check tag_ranges("sel") before reading it to avoid an error when the user has selected nothing.

selected = e1.tag_ranges("sel")
if selected:
    data = e1.get(selected[0], selected[1])
    print(data)
else:
    print("Select text first")

Select a specific range

To select a known range rather than all text, pass two Text indexes to tag_add(). You can also select text by dragging with the mouse.

# Selecting part of the text by line and character
# "1.0" is the first character of line 1
# "1.5" is the sixth character of line 1
e1.tag_add("sel", "1.0", "1.5")

Cut and Copy the Selected Text

Use clipboard_clear() before adding the new clipboard value, then call clipboard_append() with the selected text. With Copy, the original text stays in the first Text widget. With Cut, remove it only after successfully placing the selection on the clipboard.

Copy selected text

def copy_select():
    selected = e1.tag_ranges("sel")
    if not selected:
        return
    data = e1.get(selected[0], selected[1])
    my_w.clipboard_clear()
    my_w.clipboard_append(data)

Cut selected text

Cut performs the same clipboard operation as Copy, and then removes the selected characters using the Text widget's delete() method.

def cut_select():
    selected = e1.tag_ranges("sel")
    if not selected:
        return
    data = e1.get(selected[0], selected[1])
    my_w.clipboard_clear()
    my_w.clipboard_append(data)
    e1.delete(selected[0], selected[1])

Both functions avoid selection_get() without a guard. In the original example, the copied value was kept in a Python variable named data. Here it is placed in the system clipboard, making it available to other applications as well.

Paste Clipboard Data into Another Text Widget

The second Text widget, e2, displays the pasted text. In this example "end-1c" appends the text after existing content instead of inserting it at a possibly different cursor position. An empty or non-text clipboard can raise tk.TclError; catch it so the application keeps running.

def paste_select():
    try:
        data = my_w.clipboard_get()
    except tk.TclError:
        return
    e2.insert("end-1c", data)

If you prefer to paste at the current cursor position, use e2.insert(tk.INSERT, data). To replace all existing content before pasting, see the additional example below.

Complete Working Tkinter Text Cut, Copy and Paste Program

Save the following Python code as text_clipboard.py and run it on a computer with a graphical desktop and Tkinter installed. The first Text box begins with sample text. Select part of it, or choose Select All, then press Copy or Cut and Paste. The status label reports the action.

import tkinter as tk

my_w = tk.Tk()
my_w.title("plus2net.com - Tkinter Text Clipboard")
my_w.geometry("650x390")

status = tk.StringVar(value="Select some text to get started")

def select_all():
    e1.tag_add("sel", "1.0", "end-1c")
    e1.mark_set("insert", "1.0")
    e1.focus_set()
    status.set("Source text selected")

def get_selection():
    selected = e1.tag_ranges("sel")
    if not selected:
        status.set("Select text in the first box")
        return None
    return selected

def copy_select():
    selected = get_selection()
    if not selected:
        return
    data = e1.get(selected[0], selected[1])
    my_w.clipboard_clear()
    my_w.clipboard_append(data)
    status.set("Copied to clipboard")

def cut_select():
    selected = get_selection()
    if not selected:
        return
    data = e1.get(selected[0], selected[1])
    my_w.clipboard_clear()
    my_w.clipboard_append(data)
    e1.delete(selected[0], selected[1])
    status.set("Cut to clipboard")

def paste_select():
    try:
        data = my_w.clipboard_get()
    except tk.TclError:
        status.set("No text available on the clipboard")
        return
    e2.insert("end-1c", data)
    status.set("Pasted into the second box")

tk.Label(my_w, text="Source Text").grid(
    row=0, column=0, padx=8, pady=8, sticky="nw")
e1 = tk.Text(my_w, height=5, width=48, bg="lightyellow",
             wrap="word", exportselection=False)
e1.grid(row=0, column=1, columnspan=4, pady=8, sticky="ew")
e1.insert("1.0", "Select all or part of this text, then Copy or Cut.")

tk.Button(my_w, text="Select All", command=select_all).grid(
    row=1, column=1, padx=3, pady=8)
tk.Button(my_w, text="Cut", command=cut_select).grid(
    row=1, column=2, padx=3)
tk.Button(my_w, text="Copy", command=copy_select).grid(
    row=1, column=3, padx=3)
tk.Button(my_w, text="Paste", command=paste_select).grid(
    row=1, column=4, padx=3)

tk.Label(my_w, text="Destination").grid(
    row=2, column=0, padx=8, sticky="nw")
e2 = tk.Text(my_w, height=5, width=48, bg="lightcyan", wrap="word")
e2.grid(row=2, column=1, columnspan=4, pady=8, sticky="ew")
tk.Label(my_w, textvariable=status, fg="navy").grid(
    row=3, column=0, columnspan=5, padx=8, pady=8)
my_w.mainloop()

Expected behavior: Select All highlights the source text. Copy leaves that text untouched; Cut removes the selection. Paste appends the clipboard text to the destination box. You can also paste the copied text into another desktop application while Tkinter is running.

Compatibility: Tkinter programs require a desktop GUI environment; they are not intended to run directly inside browser-based Google Colab notebooks.

Video: Select, Cut, Copy and Paste in Tkinter Text Widgets

This tutorial video demonstrates selecting text in the source Text widget, cutting or copying it and pasting it into the destination. The four main buttons follow the same workflow used in the code above.

Tkinter select all data from text box and copy or cut to clipboard to paste in another text box

Use Tkinter's Built-In Cut, Copy and Paste Events

Tkinter provides virtual events for the standard editing commands: <<Cut>>, <<Copy>> and <<Paste>>. They are a convenient alternative to implementing clipboard operations manually. The source Text widget must have a selection for Cut or Copy to act on.

e1.tag_add("sel", "1.0", "end-1c")
e1.event_generate("<<Copy>>")
e1.event_generate("<<Cut>>")   # Use instead of Copy to remove text
e2.event_generate("<<Paste>>")

With these events, Tk supplies its normal text editing behavior. Use manual clipboard methods when you want to validate selections, show a status message, append pasted content instead of inserting it at the cursor, or handle clipboard errors explicitly. You do not need to call Copy and Cut together: choose the action required.

How the Tkinter System Clipboard Works

Copying is not the same as keeping a Python string in a global variable. The operating system clipboard can be shared with other programs; a normal Python variable is available only to your running application. Tkinter has built-in clipboard methods, so you do not need an additional package for this GUI example.

MethodPurpose
clipboard_clear()Clears the existing clipboard content owned by the application
clipboard_append(text)Places text onto the clipboard
clipboard_get()Retrieves text from the clipboard if available
Text.get(start, end)Reads characters from a Text widget
Text.delete(start, end)Removes a range of characters from the widget
Text.insert(index, text)Inserts characters at a selected position

Copy a string and read it back

my_w.clipboard_clear()
my_w.clipboard_append("Sample text from Tkinter")
print(my_w.clipboard_get())

Handle an empty or non-text clipboard

try:
    data = my_w.clipboard_get()
    print("Clipboard text:", data)
except tk.TclError:
    print("Clipboard is empty or does not contain text")

Important: Clipboard content availability can depend on the operating system, session and other applications. The GUI event loop should remain running when you want Tk to continue serving clipboard data.

More Useful Text Clipboard Examples

Replace all destination text with the clipboard

The main program appends text to e2. To replace its full contents instead, delete from "1.0" to tk.END before inserting the clipboard value.

try:
    data = my_w.clipboard_get()
except tk.TclError:
    data = None
if data is not None:
    e2.delete("1.0", tk.END)
    e2.insert("1.0", data)

Paste at the current insertion cursor

If a user has positioned the cursor inside the destination Text widget, tk.INSERT identifies that insertion point.

try:
    data = my_w.clipboard_get()
except tk.TclError:
    pass
else:
    e2.insert(tk.INSERT, data)

Support Ctrl+A for Select All

Desktop users often expect Ctrl+A to select all contents. Bind that keyboard shortcut to a function; returning "break" prevents further processing of the same event. On macOS, users may also expect Command+A, which can be bound separately.

def select_all_shortcut(event):
    event.widget.tag_add("sel", "1.0", "end-1c")
    return "break"

e1.bind("<Control-a>", select_all_shortcut)

Check selection before accessing sel.first

When no selection exists, directly accessing "sel.first" raises tk.TclError. Inspect the selection first.

selected = e1.tag_ranges("sel")
if selected:
    text = e1.get("sel.first", "sel.last")
    print(text)
else:
    print("Nothing selected")

Optional: Copy Text with the pyperclip Library

The original tutorial introduced pyperclip. It is still useful for Python scripts that need to copy or paste text without using Tkinter's widget methods. For the complete Tkinter example on this page, no external clipboard package is required.

Install the optional package in a local terminal:

pip install pyperclip

Then import it before using its copy and paste functions:

import pyperclip

data = "Copy text from a Python script"
pyperclip.copy(data)
print(pyperclip.paste())

See managing the clipboard in Tkinter for additional examples and clipboard-related tasks.

Common Errors and Troubleshooting

ProblemWhy it happensHow to fix it
tk.TclError: text doesn't contain any characters tagged with "sel"The Cut or Copy command tries to read sel.first with nothing selectedCheck tag_ranges("sel") first
Copy button does nothingThe source has no selected characters, or the selection was lostUse Select All or highlight text; use exportselection=False for the source widget where appropriate
Paste does nothingThe clipboard is empty or does not contain textCatch tk.TclError and display a helpful message
Unexpected extra newlineThe Text widget maintains a newline at the endUse "end-1c" to exclude the final newline
Copied text cannot be pasted into another applicationText was stored only in a Python variable instead of the system clipboardUse clipboard_clear() and clipboard_append()
Cut removes text without storing itThe content was deleted before being copiedCopy to the clipboard first, then delete the selected range
Tk window does not open in a hosted notebookGUI display support is unavailableRun the script locally with a desktop Python installation

Frequently Asked Questions

How do I select all text in a Tkinter Text widget?

Use e1.tag_add("sel", "1.0", "end-1c"). The sel tag identifies the selected characters.

How is Text selection different from Entry selection?

A Tkinter Entry widget is a single-line field and uses methods such as selection_range(). A multiline Text widget uses a sel tag and line.character indexes.

What is the difference between Copy and Cut?

Both place selected text on the clipboard. Cut also removes those characters from the source Text widget.

Can copied text be pasted into another application?

Yes. Use Tkinter's clipboard methods or standard virtual events so the selected text is placed on the system clipboard. A Python variable by itself does not provide system-wide clipboard access.

Do I need pyperclip for Tkinter Cut, Copy and Paste?

No. Tkinter has built-in clipboard methods and virtual events. pyperclip is optional for applications that benefit from its separate API.

How can I paste text without removing what is already in the second Text widget?

Call e2.insert("end-1c", data) to append, or e2.insert(tk.INSERT, data) to paste at the cursor. Neither method clears the destination first.

Can I use this program in Google Colab?

The full program creates a desktop Tkinter window and needs a graphical display. Run it on your own computer rather than in a browser-based Colab runtime.

Back to top ↑




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer