Search code examples
pythontkinterdefault-valuetkinter-entry

How to make an unchangeable default text for a Tkinter Entry?


I've managed to find a post on SO on how to create a Tkinter entry with a default value (referring to this one). The code below demonstrates my use of it:

comCurrent_Label = tk.Entry(root, font = (16), bg = "black", fg = "white", bd = 3, relief = "sunken")
comCurrent_Label.insert(0, ">>> ")
comCurrent_Label.grid(row = 2, column = 0, ipady = 15, ipadx = 175)

But I'd want for the user to be unable to delete >>> by backspacing too far.

My question is: How to make that entry's default text unchangeable/undeletable?


Solution

  • You can use the entry widget's validation feature to prevent the user from deleting the leading characters. Simply require that any new value begin with the string ">>> ", and the entry will prevent the user from deleting those characters.

    Here's an example:

    import tkinter as tk
    
    def validate(new_value):
        return new_value.startswith(">>> ")
    
    root = tk.Tk()
    vcmd = root.register(validate)
    entry = tk.Entry(root, validate="key", validatecommand=(vcmd, "%P"))
    entry.pack(side="top", fill="x", padx=20, pady=20)
    entry.insert(0, ">>> ")
    
    root.mainloop()
    

    For a more in-depth explanation of entry validation see Interactively validating Entry widget content in tkinter