Skip to content Skip to sidebar Skip to footer

Passing Entry Widget Input To Binding/event Handler Function

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 bo

Solution 1:

You can use events <FocusIn> and <FocusOut> to do what you want. Below is a customized Entry to achieve it:

classMyEntry(Entry):
    def__init__(self, *args, **kwargs):
        self.prompt = kwargs.pop('prompt') if'prompt'in kwargs elseNonesuper().__init__(*args, **kwargs)
        if self.prompt:
            self.bind('<FocusIn>', self.on_focus_in)
            self.bind('<FocusOut>', self.on_focus_out)
            self.on_focus_out()

    defon_focus_in(self, event=None):
        if self.get() == self.prompt:
            self.delete(0, 'end')
            self.config(fg='black')

    defon_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')

Solution 2:

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):
    ifevent.widget.get() == 'Input Favourite Food':
        event.widget.delete(0, "end")
        event.widget.insert(0, '')

Solution 3:

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, '')

Post a Comment for "Passing Entry Widget Input To Binding/event Handler Function"