I want to put a temporary text in more than 1 entry with tkinter, but my func is not working. I have this situation:
def temp_text_entry_delete(e):
self.id_entry.delete(0, 'end')
self.id_entry = tk.Entry(borderwidth=2, width=10)
self.id_entry.insert(0, "ex:001")
self.id_entry.pack()
self.id_entry.bind("<FocusIn>", temp_text_entry_delete)
Its working, but...
I wan't to use the same func for other entrys, like this one:
self.type_entry = tk.Entry(borderwidth=2, width=10)
self.type_entry.insert(0, "metal")
self.type_entry.pack()
self.type_entry.bind("<FocusIn>", temp_text_entry_delete)
Any ideas on how to make it universal?
CodePudding user response:
The event
object will have a reference to the widget that received the event. You can use that to insert or delete text:
def temp_text_entry_delete(e):
e.widget.delete(0, 'end')
CodePudding user response:
Here's a PlaceholderEntry
widget that should to what you want
import tkinter as tk
from tkinter import ttk
class PlaceholderEntry(ttk.Entry):
"""Entry widget with placeholder text"""
def __init__(
self, parent, placeholder='', color='#888', *args, **kwargs
) -> None:
super().__init__(parent, *args, **kwargs)
self.placeholder = placeholder
self._ph_color = color
self._default_fg = self._get_fg_string()
# focus bindings
self.bind('<FocusIn>', self.clear_placeholder)
self.bind('<FocusOut>', self.set_placeholder)
# initialize the placeholder
self.set_placeholder()
def clear_placeholder(self, *args) -> None: # on focus in
if self._get_fg_string() == self._ph_color:
self.delete(0, tk.END) # clear the placeholder text
self.configure(foreground=self._default_fg) # set 'normal' text color
def set_placeholder(self, *args) -> None: # on focus out
if not self.get(): # if Entry has no text...
self.insert(0, self.placeholder) # insert placeholder text
self.configure(foreground=self._ph_color) # set placeholder text color
def _get_fg_string(self) -> str:
return str(self.cget('foreground')
You can use this class like any other widget, for example:
root = tk.Tk()
self.id_entry = PlaceholderEntry(
parent=root,
placeholder='Type Here',
borderwidth=2,
width=10
)
self.id_entry.pack()