How to insert a temporary text in a tkinter Entry widget?
Asked Answered
D

4

7

How to insert a temporary text in a tkinter Entry widget?

For example, I have a Label User and next to it I have an Entry widget which should have some text "Enter your username..." at the beginning of the application, and while putting cursor on the Entry widget, it should remove "Enter your username..." and allow user to enter data.

This is my current code:

import tkinter as tk

root = tk.Tk()

label = tk.Label(root, text="User:")
label.pack()
entry = tk.Entry(root, bd=1, show="Enter your user name...")
entry.pack()

root.mainloop()

How can I do that?

I didn't find any option or method to delete data on putting cursor on the Entry widget.

Deprivation answered 27/5, 2015 at 19:42 Comment(2)
Duplicate #27820678 ?Underslung
You didn't find any option or method to delete data or put cursor in the textbox? Where did you look? It's documented in many places (eg: effbot.org/tkinterbook/entry.htm#Tkinter.Entry.insert-method, effbot.org/tkinterbook/entry.htm#Tkinter.Entry.delete-method)Nashua
M
14

I would like to add something to the responses that has not been said. As 9jera said, we can make the Entry widget clear only when it sees the default text instead of the "firstclick" method used by Leo Tenenbaum.

We could also add a second function to refill the Entry widget if the user has turned the focus to another widget without typing in anything.

This can be achieved as follows:

import Tkinter as tk


def on_entry_click(event):
    """function that gets called whenever entry is clicked"""
    if entry.get() == 'Enter your user name...':
       entry.delete(0, "end") # delete all the text in the entry
       entry.insert(0, '') #Insert blank for user input
       entry.config(fg = 'black')
def on_focusout(event):
    if entry.get() == '':
        entry.insert(0, 'Enter your username...')
        entry.config(fg = 'grey')


root = tk.Tk()

label = tk.Label(root, text="User: ")
label.pack(side="left")

entry = tk.Entry(root, bd=1)
entry.insert(0, 'Enter your user name...')
entry.bind('<FocusIn>', on_entry_click)
entry.bind('<FocusOut>', on_focusout)
entry.config(fg = 'grey')
entry.pack(side="left")

root.mainloop()

Finally, I also added grey color to the default text and black to the one written by the user, just for anyone that was wondering about that. The only issue I see here is, if the user actually manually types in there Enter your user name..., focuses out and in again, the text will be deleted even though it was written by the user himself. One solution I thought of is to change the if statement so it gets the color instead of the default text before deleting anything. If the color is grey, it can go ahead and delete it. Else, it will not. Yet, I have not found a way to get the text color. If anyone knows about this, please let me know!

EDIT: Apparently, as Olivier Samson has pointed out, it is possible to get the color of the entry by using entry.cget('fg'). I guess, after 2 years, I finally figure out how to do this.

Therefore, we can now change the line if entry.get() == 'Enter your user name...': to if entry.cget('fg') == 'grey':. That way, whenever the entry is clicked for the first time and anything is typed inside, the color is changed to black, so next time the user focuses in, it will not delete any text (even if that text is Enter your user name...).

Melodize answered 24/9, 2016 at 13:42 Comment(3)
To get the entry text color, you can use cget as such: entry.cget('fg')Craigcraighead
if entry.get() == ''" #this condition is dangerous, it should've been like this =>if len(entry.get()) - entry.get().count(' ') < 1 #aware of space only characterInterpellant
To account for dark mode (white text), you should first take entry.cget('fg') to get the default foreground color, then use that instead of "black".Whole
S
4

I think this should work:

import Tkinter as tk


firstclick = True

def on_entry_click(event):
    """function that gets called whenever entry1 is clicked"""        
    global firstclick

    if firstclick: # if this is the first time they clicked it
        firstclick = False
        entry.delete(0, "end") # delete all the text in the entry


root = tk.Tk()

label = tk.Label(root, text="User: ")
label.pack(side="left")

entry = tk.Entry(root, bd=1)
entry.insert(0, 'Enter your user name...')
entry.bind('<FocusIn>', on_entry_click)
entry.pack(side="left")

root.mainloop()

This will delete Enter your user name... when the user clicks on the Entry entry.

Slowpoke answered 27/5, 2015 at 21:5 Comment(1)
This won't work if they use the tab key to move focus to the entrt. It would be better to bind on <FocusIn>Nashua
H
2

This works for me.

import tkinter  

window = tkinter.Tk()
NameVar = tkinter.StringVar(value="")

################ Enter name ################
FillName = tkinter.Entry(textvariable=NameVar)
FillName.insert(0, "Enter your name here.")
FillName.pack()
FillName.bind("<FocusIn>", lambda event: FillName.delete(0,"end") if NameVar.get() == "Enter your name here." else None)
FillName.bind("<FocusOut>", lambda event: FillName.insert(0, "Enter your name here.") if NameVar.get() == "" else None)


window.mainloop()
Highhanded answered 22/3, 2022 at 9:26 Comment(0)
B
1

From Leo's Code entry1.delete should be changed to entry.delete.

Also the Entry widget from his code clears only on first click, but you can make the Entry widget clear only when it is set to the default text. This could be helpful if your code has to repeat itself.

Try this:

import Tkinter as tk


def on_entry_click(event):
    """function that gets called whenever entry is clicked"""
    if entry.get() == 'Enter your user name...':
       entry.delete(0, "end") # delete all the text in the entry
       entry.insert(0, '') #Insert blank for user input


root = tk.Tk()

label = tk.Label(root, text="User: ")
label.pack(side="left")

entry = tk.Entry(root, bd=1)
entry.insert(0, 'Enter your user name...')
entry.bind('<FocusIn>', on_entry_click)
entry.pack(side="left")

root.mainloop()
Bobbybobbye answered 22/6, 2015 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.