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 singleline text.

You can customize these widgets and add additional functionality using built-in library functions and methods. To validate the input in an Entry widget, you can use the register() method. This method returns a string that can be used to call the function at later stages.

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

  • validate − It signifies when the callback function has to be called for validating the input in a given Entry or Text widget. For example, "key" is the value specifying that whenever a user presses a key (from the keyboard), the callback function will be called. You can also use other options as well such as focus, focusin, focusout, none, all, etc.

  • validatecommand − It specifies the value that depends on the value returned by the callback function. To specify the value in the validatecommand='f', you can use various Callback substitution code that tells how and what values are returned by the callback functions.

To validate input in an Entry widget, you have to register the callback function and configure the Entry widget by passing the arguments that check the condition defined in the callback function.


Let us now consider an example where we want to validate an Entry widget such that a specific text cannot be removed by the user. Additionally, we can make it non-removable by checking the string with the startswith("string") function.

# Import required libraries
from tkinter import *

# Create an instance of tkinter window
win = Tk()

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

# Create an entry widget
entry=Entry(win, bg="black", fg="white")
entry.pack(side="top", fill="x")

# Add a default text
entry.insert(END, "Enter your Email Id:")
validate_entry=(win.register(make_non_removable), '%P')
entry.config(validate='key', validatecommand=validate_entry)



On execution, it will display an Entry widget in a window with a default nonremovable text "Enter your Email Id:".

Updated on 22-Dec-2021 10:49:40