Reputation: 5
Python newbie here. I have an Entry widget and wish to operate a key binding upon it that allows me to place instructions such as 'Input Favourite Food' directly into the entry box and have it disappear on click to allow the user to fill in the field. I can do this easy enough with global variables by using Entry.get()
global favourite_food
favourite_food = Entry(window)
favourite_food.insert(0, 'Input Favourite Food')
fist_name.bind('<FocusIn>', food_click)
and
def food_click(event):
if favourite_food.get() == 'Input Favourite Food':
favourite_food.delete(0, "end")
favourite_food.insert(0, '')
I've been trying to figure out, for the sake of efficiency, a way to avoid using the global and instead use a lambda but haven't had much luck getting one to work.
Help is much appreciated.
Upvotes: 0
Views: 461
Reputation: 46688
You can use events <FocusIn>
and <FocusOut>
to do what you want. Below is a customized Entry
to achieve it:
class MyEntry(Entry):
def __init__(self, *args, **kwargs):
self.prompt = kwargs.pop('prompt') if 'prompt' in kwargs else None
super().__init__(*args, **kwargs)
if self.prompt:
self.bind('<FocusIn>', self.on_focus_in)
self.bind('<FocusOut>', self.on_focus_out)
self.on_focus_out()
def on_focus_in(self, event=None):
if self.get() == self.prompt:
self.delete(0, 'end')
self.config(fg='black')
def on_focus_out(self, event=None):
if self.get() == '':
self.insert('end', self.prompt)
self.config(fg='gray')
Then you can initialize an entry as usual with the keyword argument prompt
to show the message:
entry = MyEntry(prompt='Enter favorite food')
Upvotes: 1
Reputation: 385980
You don’t need to pass anything or use a global. The event object passed to the function has everything you need:
def food_click(event):
if event.widget.get() == 'Input Favourite Food':
event.widget.delete(0, "end")
event.widget.insert(0, '')
Upvotes: 0
Reputation: 141
It's hard to help you as we don't have much of your code, but this should work
favourite_food = Entry(window)
favourite_food.insert(0, 'Input Favourite Food')
fist_name.bind('<FocusIn>', lambda event: food_click(favourite_food))
def food_click(entry):
if entry.get() == 'Input Favourite Food':
entry.delete(0, "end")
entry.insert(0, '')
Upvotes: 0