简体   繁体   中英

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()

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM