Tip Placeholder Text in Tkinter.Entry

Topics relating to tips and helpful hints for users.

Techlord

Member
Member
1
Jun 12, 2023
33
0
10
Pronouns
He/Him
Shell
  1. Bash
Editor
  1. Nano
  2. VSCode/Code
Desktop
  1. KDE
Python:
import tkinter as tk

class CustomEntry(tk.Entry):
    def placeholderText(self, text) -> None:
        set_by_user = False
        def removeText(_) -> None:
            if self.get().strip() == text and not set_by_user:
                self.delete(0, 'end')
                self.configure(foreground='#000000')


        def setText(_) -> None:
            nonlocal set_by_user
            if not len(self.get().strip()) > 0:
                self.insert(0, text)
                self.configure(foreground='#626262')
                set_by_user = False
            elif self.get() == text:
                set_by_user = True


        self.bind('<FocusIn>', removeText, add='+')
        self.bind('<FocusOut>', setText, add='+')
        setText(None)


root = tk.Tk()


root.geometry('200x200')


entry = CustomEntry(root)
entry.pack()
entry.placeholderText('foo')


root.mainloop()
this will create a place holder text in the Entry widget
can be also done by:
though this can be also done by
Python:
def placeholderText(self, text) -> None:
    set_by_user = False
    def removeText(_) -> None:
        if self.get().strip() == text and not set_by_user:
            self.delete(0, 'end')
            self.configure(foreground='#000000')


    def setText(_) -> None:
        nonlocal set_by_user
        if not len(self.get().strip()) > 0:
            self.insert(0, text)
            self.configure(foreground='#626262')
            set_by_user = False
        elif self.get() == text:
            set_by_user = True


    self.bind('<FocusIn>', removeText, add='+')
    self.bind('<FocusOut>', setText, add='+')
    setbgText(None)
setattr(tkinter.Entry, 'placeholderText', placeholderText)

entry = tkinter.Entry(root)
entry.pack()
entry.placeholderText('foo')
this is helpful in many cases
 

Attachments

  • 2023-06-14 00-23-59.mov
    1.9 MB

About Us

  • The Linux.Chat community is a multi-platform community for general Linux® support. We provide help and support for any Linux® distribution and aim to answer any questions you might have about Linux®. Discussion about the various aspects of Linux® and Free/Open Source software is also encouraged.

    Visit our communities website at Linux.Chat.
  • Linux® is the registered trademark of Linus Torvalds in the U.S. and other countries.

Quick Navigation

User Menu