0

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.

NaNdy
  • 99
  • 8

2 Answers2

1

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()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • I want a fixed prefix, so the back button does not work when it hits the ">" of the prefix (I will automatically put a ">" in font of all prefixes that the user will enter), could I use an if statement to check if there is a ">", and if there isn't then execute a normal backspace? – NaNdy Mar 28 '20 at 18:09
  • 1
    @NaNdy: I don't know what you mean. This won't won't let you backspace over the > or any other character in the prefix. It will let you enter any characters you want after the prompt. – Bryan Oakley Mar 28 '20 at 18:58
1

Although i didnt find exactly what you are asking, i would suggest using 2 entry widgets one next to the other without borders.

import tkinter as tk
root = tk.Tk()
e = tk.Entry(root)
e.configure(state="normal",borderwidth=0,highlightthickness=0)
e.insert(tk.END, "C:\\Users\\Nathan>")
e.configure(bg='white')
e.place(x=0,y=0)
e2 = tk.Entry(root)
e2.configure(bg='white',borderwidth=0,highlightthickness=0)
e2.place(x=97,y=0)
e2.config(state="normal")
root.mainloop()

enter image description here

Jordan
  • 525
  • 1
  • 4
  • 19