Python tkinter 文本框里面的提示信息实现方法

以登录界面为例:

代码:

import tkinter as tk


class Entry(tk.Entry):
    def __init__(self, master, placeholder):
        super().__init__(master)

        self.placeholder = placeholder
        self._is_password = True if placeholder == "password" else False

        self.bind("<FocusIn>", self.on_focus_in)
        self.bind("<FocusOut>", self.on_focus_out)

        self._state = 'placeholder'
        self.insert(0, self.placeholder)

    def on_focus_in(self, event):
        if self._is_password:
          self.configure(show='*')

        if self._state == 'placeholder':
            self._state = ''
            self.delete('0', 'end')

    def on_focus_out(self, event):
        if not self.get():
          if self._is_password:
            self.configure(show='')

          self._state = 'placeholder'
          self.insert(0, self.placeholder)

使用:

if __name__ == "__main__":
    root = tk.Tk()
    root.geometry("300x200+600+250")

    username = Entry(root, "username")
    username.pack()

    password = Entry(root, "password")
    password.pack()

    root.mainloop()

运行结果:

效果:

  • 鼠标进入后“username”没了,可以用get()获取内容

但是:

这个子类虽然继承了tk.Entry但是并不能使用width,以及其他关键字。

把它改成这样试试

    def __init__(self, master, placeholder,**kw):
        super().__init__(master,  **kw)

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值