kiran_raj_r
kiran_raj_r

Reputation: 116

Is there any way to delete the default text entered into the entry widget when the user click on the entry widget

I need a help, i set a default text in the tkinter entry widget. What i need is, the default text need to be cleared automatically once the user click on the entry widget to enter the input.

Upvotes: 2

Views: 2746

Answers (2)

Pythonista
Pythonista

Reputation: 11645

Every time the entry is clicked it will clear the previous contents. Whether it be from the default stringvar value or the previous text the user entered.

import tkinter as tk

root = tk.Tk()

myvar = tk.StringVar()
myvar.set("A test")

def on_click(event):

    event.widget.delete(0, tk.END)

entry = tk.Entry(root, textvariable=myvar)
entry.bind("<Button-1>", on_click)
entry.pack()
root.mainloop()

Upvotes: 3

Luther
Luther

Reputation: 574

This solution takes care of both focus in and click events and tests for default text so no other text is deleted on click or focus in.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

def on_click(event):
    ent2.config(foreground='black')
    if ent2.get() == "Click & type...":
        event.widget.delete(0, tk.END)
    else:
        ent2.config(foreground='black')

myvar = tk.StringVar()
myvar.set("Click & type...")

ent1 = ttk.Entry(root)
ent1.grid()

ent2 = ttk.Entry(root, textvariable=myvar)
ent2.config(foreground='gray')
ent2.bind("<Button-1>", on_click)
ent2.bind("<FocusIn>", on_click)
ent2.grid()

root.mainloop()

Upvotes: 0

Related Questions