- Jun 12, 2023
- 33
- 0
- 10
- Pronouns
- He/Him
- Shell
- Bash
- Editor
- Nano
- VSCode/Code
- Desktop
- 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()
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')