Search code examples
pythontkintertkinter-entry

Is there a config option for non-editable prefixes in entry field


I am trying to make my own console using Tkinter, and I want to be able to display a prefix in the entry field and also use console.prefix("prefix_goes_here") to set said prefix. But when I use entry.set("prefix_goes_here") the user has the ability to delete the prefix.

example of what I mean can be found in CMD

C:\Users\Nathan>command_goes_here

everything before the ">" is what I would class as the prefix (but I do not know if it has an official name so I am just clarifying).

I also would preferably like to still be able to grab this prefix using entry.get(), but I could store the prefix in a variable and just add it later on.


Solution

  • There is no configuration option.

    One technique is to use the validation feature of an Entry widget. In the validation function, you can check that the entry contains the prefix and reject the edit if it does not.

    For more example on entry validation see Interactively validating Entry widget content in tkinter

    Example

    import tkinter as tk
    
    class Example():
        def __init__(self):
            root = tk.Tk()
    
            self.prefix = r'C:\Users\Nathan> '
            vcmd = (root.register(self.onValidate), '%P')
            self.entry = tk.Entry(root, validate="key", validatecommand=vcmd)
            self.entry.pack(padx=20, pady=20)
            self.entry.insert(0, self.prefix)
    
        def onValidate(self, P):
            return P.startswith(self.prefix)
    
    e = Example()
    tk.mainloop()