Zingo
Zingo

Reputation: 650

manipulating entry text value in tkinter

I want to add the word "Search Here !" inside the entry which will be disappeared once the user starts typing in the entry!

same like what we see in facebook web page "What's on ur mind"

from tkinter import *


class Application(Frame):
    def __init__(self, master=NONE):
        Frame.__init__(self, master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.frame = Frame(self)
        self.entry = Entry(self.frame)
        self.entry.pack()
        self.frame.pack()    

if __name__ == "__main__":
    root = Tk()
    app = Application(master=root)
    app.mainloop()

Upvotes: 1

Views: 283

Answers (2)

mhawke
mhawke

Reputation: 87054

You can handle key events for the Entry widget and erase the contents when the first key event occurs:

from tkinter import *

class Application(Frame):
    def __init__(self, master=NONE):
        Frame.__init__(self, master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.frame = Frame(self)
        self.entry = Entry(self.frame)
        self.entry.modified = False
        self.entry.insert(0, "Search Here!")
        self.entry.bind("<Key>", self.entry_key)
        self.entry.pack()
        self.frame.pack()

    def entry_key(self, event):
        if not self.entry.modified:
            self.entry.delete(0, END)
            self.entry.modified = True

if __name__ == "__main__":
    root = Tk()
    app = Application(master=root)
    app.mainloop()

To detect the first change I have bound and initialised to False an attribute named modified to the Entry widget instance. When the first key event occurs the content of the entry box is deleted and the modified attribute is set to True, which prevents clearing of the content on subsequent key events.

Upvotes: 2

Clodion
Clodion

Reputation: 1017

You've got to use "StringVar" to set or get the text:

from tkinter import *


class Application(Frame):
    def __init__(self, master=NONE):
        Frame.__init__(self, master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.frame = Frame(self)
        my_entry = StringVar()
        my_entry.set("Search here")
        self.entry = Entry(self.frame, text=my_entry)
        self.entry.pack()
        self.frame.pack()    

if __name__ == "__main__":
    root = Tk()
    app = Application(master=root)
    app.mainloop()

Upvotes: 0

Related Questions