将Tkinter Widget重置为其默认值

时间:2015-06-10 13:11:55

标签: python tkinter

需要创建一个泛型函数,在事件上它会将聚焦小部件返回到其默认值。有没有办法实现这个目标?

示例:

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 个答案:

答案 0 :(得分:4)

您可以继承Entry小部件以添加属性以存储默认值,并在事件处理程序中引用该属性。但是,没有什么能阻止您直接将自己的属性直接添加到每个Entry窗口小部件,例如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()