gpt4 book ai didi

python - 如何将占位符添加到 tkinter 中的条目?

转载 作者:太空狗 更新时间:2023-10-29 17:58:37 24 4
gpt4 key购买 nike

我在 tkinter 中创建了一个登录窗口,它有两个输入字段,第一个是用户名,第二个是密码。
代码

from tkinter import *

ui = Tk()

e1 = Entry(ui)
#i need a placeholder "Username" in the above entry field
e1.pack()

ui.mainloop()

我想要在 Entry 中有一个名为“Username”的占位符,但是如果您在输入框内单击,文本应该会消失。

最佳答案

您可以创建一个继承自 Entry 的类,如下所示:

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()

if __name__ == "__main__":
root = tk.Tk()
username = EntryWithPlaceholder(root, "username")
password = EntryWithPlaceholder(root, "password", 'blue')
username.pack()
password.pack()
root.mainloop()

关于python - 如何将占位符添加到 tkinter 中的条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27820178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com