How to make specific text non-removable in tkinter?

In Tkinter, users can input text using two basic text input widgets − the Text widget and the Entry widget. The Text widget is generally used to accept multiline user input, whereas in an Entry widget, the user can type only single-line text.

You can customize these widgets and add additional functionality using built-in library functions and methods. To make specific text non-removable, you can use input validation with the register() method and validation commands.

Understanding Validation Parameters

To validate input in an Entry widget, use the config(**options) method and pass the validate and validatecommand arguments ?

  • validate − Specifies when the callback function should be called for validating input. For example, "key" means the validation occurs whenever a user presses a key. Other options include focus, focusin, focusout, none, all.

  • validatecommand − Specifies the callback function and passes validation data using substitution codes like %P (proposed text) or %S (inserted/deleted text).

Method 1: Using startswith() Validation

This approach validates that the text always starts with a specific non-removable prefix ?

# Import required libraries
from tkinter import *

# Create an instance of tkinter window
win = Tk()
win.geometry("700x350")
win.title("Non-removable Text Example")

# Define a function to make a text non-removable
def make_non_removable(proposed_text):
    return proposed_text.startswith("Enter your Email Id: ")

# Create an entry widget
entry = Entry(win, bg="black", fg="white", font=("Arial", 12))
entry.pack(side="top", fill="x", padx=10, pady=20)

# Add a default text
entry.insert(0, "Enter your Email Id: ")

# Register the validation function
validate_entry = (win.register(make_non_removable), '%P')
entry.config(validate='key', validatecommand=validate_entry)

win.mainloop()

Method 2: Using Text Widget with Read-only Sections

For more complex scenarios, you can use a Text widget with tags to make specific portions read-only ?

from tkinter import *

def on_key_press(event):
    # Get cursor position
    cursor_pos = text.index(INSERT)
    
    # Check if cursor is in the protected area (first 19 characters)
    if text.compare(cursor_pos, "<=", "1.19"):
        if event.keysym in ['BackSpace', 'Delete']:
            return "break"  # Prevent deletion
    return None

# Create window
win = Tk()
win.geometry("700x350")
win.title("Protected Text Example")

# Create text widget
text = Text(win, bg="lightgray", fg="black", font=("Arial", 12))
text.pack(fill="both", expand=True, padx=10, pady=20)

# Insert protected text
protected_text = "Enter your Email Id: "
text.insert("1.0", protected_text)

# Bind key events
text.bind("<KeyPress>", on_key_press)

# Position cursor after protected text
text.mark_set(INSERT, "1.19")

win.mainloop()

How It Works

The validation approach works by:

  • Registration − The callback function is registered using win.register()

  • Validation − On each keystroke, the function checks if the proposed text starts with the required prefix

  • Return Value − If validation passes, it returns True; otherwise False, preventing the change

Comparison

Method Widget Type Complexity Best For
startswith() validation Entry Simple Fixed prefix text
Text widget protection Text Medium Complex formatting needs

Conclusion

Use startswith() validation for simple non-removable prefixes in Entry widgets. For more complex scenarios with formatting or multiline text, use Text widgets with event binding to protect specific regions.

Updated on: 2026-03-26T18:54:19+05:30

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements