我想在条目内添加单词"Search Here !",一旦用户开始输入条目,它将消失!
就像我们在facebook网页上看到的" what 's on our 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()
您可以处理Entry
小部件的键事件,并在第一个键事件发生时擦除内容:
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()
为了检测第一个更改,我已经将名为modified
的属性绑定并初始化到False
到Entry
小部件实例。当第一个键事件发生时,将删除输入框的内容,并将modified
属性设置为True
,从而防止在后续的键事件中清除内容。
你必须使用"StringVar"来设置或获取文本:
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()