How can I highlight the pre-entered text in tkinter ENTRY so User can just type over ( without selecting, deleting)

Viewed 1803

noob here trying to create a simple entry with tkinter , so the pre-entered text "Enter your name here" is highlighted. The user can then just types their name ( or hit delete to remove the content...) is there any simple argument / method to use with ENTRY ?

from tkinter import *
root = Tk()

lbl1 = Label ( root, text = "Let's Play together")
lbl2 = Label ( root, text = "What's your Name ? ")
lbl1.grid( row=0, column=0)
lbl2.grid (row=1, column=0)


nameplayer = Entry(root, width=25, )
nameplayer.insert(0,"Enter your name here ")
nameplayer.grid(row=2, column=0)
root.mainloop()

thanks !!

3 Answers

Auto-Select text can be done with Entry.selection_range

class Focus(event):
    nameplayer.selection_range(0, END)

nameplayer.bind("<FocusIn>", Focus)

This will select all text when the user clicks in the Entry Widget. Hope this works :)

I suggest you write a function and create a place holder for your Entry. Then the user just clicks and writes his/her name. no need to delete the pre-text and then write name.
use this function click() for defining a hint or actually a place holder:

from tkinter import *
root = Tk()

lbl1 = Label(root, text = "Let's Play together")
lbl2 = Label(root, text = "What's your Name?")
lbl1.grid(row=0, column=0)
lbl2.grid(row=1, column=0)

nameplayer = Entry(root, width=25, )
nameplayer.insert(0, 'Enter your name here')
nameplayer.grid(row=2, column=0)
def click(event):
    nameplayer.configure(state=NORMAL)
    nameplayer.delete(0, END)
    nameplayer.unbind('<Button-1>', clicked)
    
clicked = nameplayer.bind('<Button-1>', click)
root.mainloop()

LAMBDA

nameplayer.bind('<FocusIn>', lambda x: nameplayer.selection_range(0, END))
Related