gpt4 book ai didi

python - 将 Tkinter 小部件重置为其默认值

转载 作者:太空宇宙 更新时间:2023-11-04 10:23:41 29 4
gpt4 key购买 nike

需要创建一个通用函数,在发生事件时它将聚焦的小部件返回到其默认值。有办法实现吗?

例子:

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"

最佳答案

您可以子类化 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()

关于python - 将 Tkinter 小部件重置为其默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30757396/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com