在 tk.Entry 中显示灰色的默认文本 [英] Showing a greyed out default text in a tk.Entry

查看:72
本文介绍了在 tk.Entry 中显示灰色的默认文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在此处附加的代码中定义的输入框中添加某种背景文本:

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

该框可能会显示示例:Joe Bloggs",但会显示为灰色,然后在用户在框内单击时将其移除?希望这不会太棘手.

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

推荐答案

您需要:

  • 使用 tk.Entry.insert 将默认文本添加到 Entry 小部件
  • 将前景色设置为灰色"
  • 当条目获得焦点时,默认值被删除,前景设置为黑色".
  • 您输入文本.
  • 按下回车键后,将提取条目的值,然后将条目重置为灰色的默认文本.
  • 退出焦点也会将条目重置为默认灰色(您可能希望选择避免这种情况,因为如果您使条目失去焦点,部分条目将被删除;例如,通过在框外单击)
  • 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)

代码如下

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:

将焦点放在 Entry 小部件上后,示例文本被删除,字体颜色变为黑色;填写后,aspect为:

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:

这篇关于在 tk.Entry 中显示灰色的默认文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆