Tkinter - 隐藏提示

Tkinter - Hide Hint

如何在我select用户名和密码部分自动删除这个提示? (点击后不显示)

from tkinter import *
root =Tk()
def save_fonc():
    kul=entry1.get()
    pas=entry2.get()
    print("Username:",kul,"Password:",pas)

#------------------
entry1=Entry(root)
entry1.insert(0,"Username")
entry1.pack()
#------------------
entry2=Entry(root)
entry2.insert(0,"Password")
#entry2.config(show="*")#and also I don't want to show password section.
entry2.pack()
#------------------
buton_kaydet=Button(root,text="Enter",command=save_fonc)
buton_kaydet.pack()

root.geometry("300x200")
root.mainloop()

点击标签即可删除文字。

示例:

from tkinter import *
root = Tk()

def clear_text(event):
    event.widget.delete(0, "end")

entry1=Entry(root)
entry1.insert(0,"Username")
entry1.pack()
entry1.bind("<FocusIn>", clear_text)

它的作用是将它绑定到函数 clear_textclear_text 清除标签中的文本。

完整代码:

from tkinter import *
root =Tk()
def save_fonc():
    kul=entry1.get()
    pas=entry2.get()
    print("Username:",kul,"Password:",pas)

def clear_text(event):
    event.widget.delete(0, "end")

#------------------
entry1=Entry(root)
entry1.insert(0,"Username")
entry1.pack()
entry1.bind("<FocusIn>", clear_text)
#------------------
entry2=Entry(root)
entry2.insert(0,"Password")
entry2.config(show="*")#and also I don't want to show password section.
entry2.pack()
entry2.bind("<FocusIn>", clear_text)
#------------------
buton_kaydet=Button(root,text="Enter",command=save_fonc)
buton_kaydet.pack()

root.geometry("300x200")
root.mainloop()

做一个清除输入框文字的函数,然后在函数中绑定。

def removeValue(event):
    event.widget.delete(0, 'end')
    

所以你去改进你的代码:

from tkinter import *
root = Tk()


def save_fonc():
    kul = entry1.get()
    pas = entry2.get()
    print("Username:", kul, "Password:", pas)


def pass_func(event):
    entry2.delete(0, 'end')
    entry2.config(show='*')

# ------------------
entry1 = Entry(root)
entry1.insert(0, "Username")
entry1.pack()
entry1.bind('<FocusIn>', lambda e: entry1.delete(0, 'end'))
# ------------------
entry2 = Entry(root)
entry2.insert(0, "Password")
entry2.pack()
entry2.bind('<FocusIn>', pass_func)
# ------------------
buton_kaydet = Button(root, text="Enter", command=save_fonc)
buton_kaydet.pack()

root.geometry("300x200")
root.mainloop()

所以基本上 .bind 在这种情况下将每个条目绑定到一个事件:'<FocusIn>' 当焦点切换到该小部件时触发。同样在第二种情况下,条目仅在事件触发后配置,以便 'Password' 正常可见