如何在tkinter的条目小部件上放置默认文本

时间:2017-12-22 14:16:15

标签: python tkinter tkinter-entry

所以,我昨天开了一个关于它的问题,但它已经关闭说它是一个骗局,让我更具体地解释我的问题,希望我不会在这里通过任何法律..

我试图设置一个默认消息,该消息将在tkinter上的条目小部件中设置为灰色和低不透明度,在聚焦之后将消失。

我设法做到了,但我遇到了一个问题。

默认文本是“输入用户名”,例如,但是如果有人试图做这个用户名,则表示用户名条目为空,这不是我想做的事情。

我希望你理解我的问题。

编辑:我的问题是如何设置占位符文字,同时允许用户输入与占位符相同的文字。

提前感谢,这是我的代码:

    from tkinter import *
from tkinter import messagebox


main = Tk()
main.title("ani gever")
checkbox_var = IntVar()


def delete_user_default(event):
    if User_entry.get()!="enter username":
        pass
    else:
        User_entry.delete(0, END)

def delete_password_default(event):
    if password_entry.get() !="insert password":
        pass
    else:
        password_entry.delete(0, END)
        password_entry.config(show="*")

def return_user_default(event):
    if User_entry.get()=="":
        User_entry.insert(0, "enter username")
        emptyuser=1
    else:
        pass

def return_password_default(event):
    if password_entry.get()=="":
        password_entry.insert(0,"insert password")
        password_entry.config(show="")
    else:
        pass

def details(event):
    if ((User_entry.get() == "enter username") or (password_entry.get() == "insert password")):
        errorLabel.config(text="Username or password is empty!",fg="red")
    elif ((" " in User_entry.get()) or " " in password_entry.get()):
        errorLabel.config(text="dont use spaces in your password or username!", fg="red")
    else:
        print ("username:" + User_entry.get() + "\npassword:" + password_entry.get())
        errorLabel.config(text="")


#============== define texts=======================
User_label= Label(main,text="Username:")
password_label= Label(main,text="Password:")
User_entry = Entry(main)
password_entry= Entry(main,show="*")
enterButton= Button(main,text="Log in")
errorLabel= Label(main,text="")
#=============default text on entry's=============
password_entry.config(show="")
User_entry.insert(0,"enter username")
password_entry.insert(0,"insert password")
User_entry.bind("<FocusIn>",delete_user_default)
password_entry.bind("<FocusIn>",delete_password_default)
User_entry.bind("<FocusOut>",return_user_default)
password_entry.bind("<FocusOut>",return_password_default)

#=============return user details ===========
User_entry.bind("<Return>",details)
password_entry.bind("<Return>",details)
enterButton.bind("<Button-1>",details)



#=============place everything on screen===========
User_label.grid(row=0,sticky= W)
User_entry.grid(row=0,column=1,sticky= W)
password_label.grid(row=1,sticky= W)
password_entry.grid(row=1,column=1,sticky= W)
enterButton.grid(row=2,sticky=W)
errorLabel.grid(row=3,columnspan=10,sticky= W)

main.mainloop()

1 个答案:

答案 0 :(得分:1)

使用this answer可以创建is_empty功能。如果经过验证的条目为“空白”,则会打印True。如果没有,则False

import tkinter as tk

class EntryWithPlaceholder(tk.Entry):
    def __init__(self, master=None, placeholder="PLACEHOLDER", color='grey'):
        super().__init__(master)

        self.placeholder = placeholder
        self.placeholder_color = color
        self.default_fg_color = self['fg']

        self.bind("<FocusIn>", self.foc_in)
        self.bind("<FocusOut>", self.foc_out)

        self.put_placeholder()

    def put_placeholder(self):
        self.insert(0, self.placeholder)
        self['fg'] = self.placeholder_color

    def foc_in(self, *args):
        if self['fg'] == self.placeholder_color:
            self.delete('0', 'end')
            self['fg'] = self.default_fg_color

    def foc_out(self, *args):
        if not self.get():
            self.put_placeholder()

def is_empty(widget, empty_color):

    if widget.get():
        if widget['fg'] == empty_color:
            print (True)
        else:
            print (False)
    else:
        print (True)


if __name__ == "__main__":
    root = tk.Tk()

    username = EntryWithPlaceholder(root, "username")
    password = EntryWithPlaceholder(root, "password", 'blue')
    username.pack()
    password.pack()

    tk.Button(root, text="Validate",
                    command=lambda wid=username, clr=username.placeholder_color:
                                                    is_empty(wid, clr)).pack()

    root.mainloop()