0

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?

peki
  • 669
  • 7
  • 24

2 Answers2

1

The easiest solution to this is to just put the >>> in a different widget, like a Label:

import tkinter as tk

root = tk.Tk()
subframe = tk.Frame(root, bd = 3, relief = "sunken")
lbl = tk.Label(subframe, text=">>> ", font = (16), bg = "black", fg = "white", bd=0, highlightthickness=0)
lbl.pack(side=tk.LEFT)
comCurrent_Label = tk.Entry(subframe, font = (16), bg = "black", fg = "white", bd=0, highlightthickness=0)
comCurrent_Label.pack(side=tk.LEFT)
subframe.grid(row = 2, column = 0, pady = 15, padx = 175)

root.mainloop()

You should probably wrap that up in a neat little subclass.

Novel
  • 13,406
  • 2
  • 25
  • 41
1

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

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685