Showing a greyed out default text in a tk.Entry

半城伤御伤魂 提交于 2020-06-10 02:06:14

问题


I was wondering how I would add some sort of background text in the input box defined in the code attached here under:

The box could say "Example: Joe Bloggs" but greyed out and then remove when the user clicks inside the box? Hope this isn't too tricky.

        # ************ Retrieve user's Full name ************
    tk.Label(self, text='First and last name:').grid(sticky='e') # Label

    self.full_name_entry = tk.Entry(self, bg='white', width=30) # Entry box
    self.full_name_entry.grid(row=1, column=1, pady=15, columnspan=2) # Entry box placement

回答1:


You need to:

  • use tk.Entry.insert to add the default text to an Entry widget
  • set the foreground color to 'grey'
  • upon the entry getting focus, the default is deleted, and the foreground set to 'black'.
  • you type in the text.
  • upon pressing return, the value of the entry is extracted, then the entry is reset with the default text in grey.
  • exiting the focus also resets the entry to default grey (you may want to choose avoid this as a partial entry will then be deleted if you make the entry lose focus; by clicking outside the box, for instance)

Here is what the code look like

import tkinter as tk

def handle_focus_in(_):
    full_name_entry.delete(0, tk.END)
    full_name_entry.config(fg='black')

def handle_focus_out(_):
    full_name_entry.delete(0, tk.END)
    full_name_entry.config(fg='grey')
    full_name_entry.insert(0, "Example: Joe Bloggs")

def handle_enter(txt):
    print(full_name_entry.get())
    handle_focus_out('dummy')

root = tk.Tk()

label = tk.Label(root, text='First and last name:')
label.grid(sticky='e')

full_name_entry = tk.Entry(root, bg='white', width=30, fg='grey')
full_name_entry.grid(row=1, column=1, pady=15, columnspan=2)

full_name_entry.insert(0, "Example: Joe Bloggs")

full_name_entry.bind("<FocusIn>", handle_focus_in)
full_name_entry.bind("<FocusOut>", handle_focus_out)
full_name_entry.bind("<Return>", handle_enter)


root.mainloop()

Here is what it looks upon opening the window:

Upon giving focus to the Entry widget, the example text is deleted, and the font color changed to black; after filling the entry, the aspect is:



来源:https://stackoverflow.com/questions/51781651/showing-a-greyed-out-default-text-in-a-tk-entry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!