Reset Tkinter Widget to its default value

2.4k Views Asked by At

In need to make a generic function that on event it would return the focused-out widget to its default value. Is there a way to accomplish this?

Example:

entry1 = Tkinter.Entry()
entry1.grid(..)
entry1.insert(0,"hello")
entry1.bind("<FocusIn>", EntryFocusedIn)
entry1.bind("<FocusOut>", EntryFocusedOut)

entry2 = Tkinter.Entry()
entry2.grid(..)
entry2.insert(0,"again")
entry2.bind("<FocusIn>", EntryFocusedIn)
entry2.bind("<FocusOut>", EntryFocusedOut)  

def EntryFocusedIn(params):
     params.widget.delete(0, Tkinter.END)

def EntryFocusedOut(params):
     # return widget to its default value
     # which in case of entry1 its "hello"
     # and in case of entry2 its "again"
1

There are 1 best solutions below

0
On BEST ANSWER

You could subclass the Entry widget to add an attribute to store a default value, and reference that attribute in the event handler. However, there's nothing stopping you from simply adding your own attribute to each Entry widget directly, e.g. entry1.default_value = 'hello', entry1.default_value = 'again':

import Tkinter

def EntryFocusedIn(params):
    params.widget.delete(0, Tkinter.END)

def EntryFocusedOut(params):
    # restore default value
    params.widget.delete(0, Tkinter.END)
    params.widget.insert(0, params.widget.default_value)

root = Tkinter.Tk()

entry1 = Tkinter.Entry()
entry1.default_value = 'hello'
entry1.pack()
entry1.insert(0, entry1.default_value)
entry1.bind("<FocusIn>", EntryFocusedIn)
entry1.bind("<FocusOut>", EntryFocusedOut)

entry2 = Tkinter.Entry()
entry2.default_value = 'again'
entry2.pack()
entry2.insert(0, entry2.default_value)
entry2.bind("<FocusIn>", EntryFocusedIn)
entry2.bind("<FocusOut>", EntryFocusedOut)

root.mainloop()