The simplest way to do this is to disable backspace by binding and returning 'break' when the text matches your text and unbind it when it doesn't.
Here try this:
from tkinter import *
def check(*args):
if entry.index(INSERT) <= len("Enter message: "):
entry.bind('<BackSpace>', lambda _:'break')
else:
entry.unbind('<BackSpace>')
root = Tk()
root.geometry("500x500")
var = StringVar()
var.trace('w', check)
entry = Entry(root, textvariable=var)
entry.pack(side="top", fill="x")
entry.insert(END, "Enter message: ")
mainloop()
Update
The above code would fail if the user uses mouse selection and deletes it. So you must clear the selection.
Here use this
from tkinter import *
def check(*args):
if entry.index(INSERT) <= len("Enter message: "):
entry.bind('<BackSpace>', lambda _:'break')
entry.bind('<Delete>', lambda _:'break')
entry.bind('<Shift-.>', lambda _:'break')
if entry.select_present():
entry.select_clear()
else:
entry.unbind('<BackSpace>')
entry.unbind('<Delete>')
entry.unbind('<Shift-.>')
root = Tk()
root.geometry("500x500")
var = StringVar()
var.trace('w', check)
entry = Entry(root, textvariable=var)
entry.pack(side="top", fill="x")
entry.insert(END, "Enter message: ")
entry.bind('<ButtonRelease>', check)
mainloop()
Ok, I found another fool-proof workaround:
from tkinter import *
def check(*args):
global old_var
if var.get()[:15] != check_string:
var.set(old_var)
else:
old_var=var.get()
root = Tk()
root.geometry("500x500")
check_string = "Enter message: "
var = StringVar()
var.set(check_string)
var.trace('w', check)
old_var = check_string
entry = Entry(root, textvariable=var)
entry.pack(side="top", fill="x")
mainloop()
working:
create a temporary variable. say old_var
. Assign both var
and old_var
to the same string initially. Use the trace
method to detect changes in the text. Now Compare if the newly changed text contains the string. If it doesn't contain the string, set it to the old string, and if it does set the old_var
to var.get()
You may use any of the above code, whichever suits you