要在小部件处于非活动状态(不在焦点上)时更改 foreground 和 background,然后在 和 绑定的帮助下,我们可以在这样他们就会在失去焦点和重新获得焦点时改变他们的foreground和background。
实际上,我们可以先保存该小部件的原始foreground 和background 值,然后使用它 和 回调。
在这里,我创建了一个完全符合您要求的类条目。我添加了inactivebackground 和inactiveforeground 配置选项。
class Entry(tk.Entry):
def __init__(self, master=None, **kw):
self.inactivebackground = kw.pop('inactivebackground', 'white')
self.inactiveforeground = kw.pop('inactiveforeground', 'black')
super().__init__(master=master, **kw)
self.org_bg = self['background']
self.org_fg = self['foreground']
self.bind('<FocusIn>', self._focusin, '+')
self.bind('<FocusOut>', self._focusout, '+')
self._focusout()
def _focusout(self, evt=None):
self['background'] = self.inactivebackground
self['foreground'] = self.inactiveforeground
def _focusin(self, evt=None):
self['background'] = self.org_bg
self['foreground'] = self.org_fg
看看这个例子:-
import tkinter as tk
root = tk.Tk()
var = tk.StringVar(value="Hello! How are you doing! :)")
Entry(root, textvariable=var, inactivebackground='pink',
inactiveforeground='blue').pack()
Entry(root, textvariable=var, inactivebackground='orange',
inactiveforeground='red').pack()
root.mainloop()
同样,您可以修改Spinbox 来做同样的事情。同样,只需将继承的类 tk.Entry 替换为 ttk.Entry 也可以与 ttk 样式小部件一起使用,但请记住并非所有内容都可以直接使用 ttk 样式小部件进行配置。
继承的力量
您可以采取一个技巧来节省时间和空间,通过创建一个可以与所需小部件一起继承的支持类以具有相同的功能。
class supportinactive(object):
def __init__(self, inactivebackground, inactiveforeground):
self.inactivebackground = inactivebackground
self.inactiveforeground = inactiveforeground
self.org_bg = self['background']
self.org_fg = self['foreground']
self.bind('<FocusIn>', self._focusin, '+')
self.bind('<FocusOut>', self._focusout, '+')
self._focusout()
def _focusout(self, evt=None):
self['background'] = self.inactivebackground
self['foreground'] = self.inactiveforeground
def _focusin(self, evt=None):
self['background'] = self.org_bg
self['foreground'] = self.org_fg
怎么用?
从上面的supportinactive 类中,我们可以像这样将这个功能添加到小部件中
class Entry(tk.Entry, supportinactive):
def __init__(self, master=None, **kw):
inactivebg = kw.pop('inactivebackground', 'white')
inactivefg = kw.pop('inactiveforeground', 'black')
tk.Entry.__init__(self, master=master, **kw)
supportinactive.__init__(self, inactivebg, inactivefg)
# Spinbox will have the same functionality too.
class Spinbox(tk.Spinbox, supportinactive):
def __init__(self, master=None, **kw):
inactivebg = kw.pop('inactivebackground', 'white')
inactivefg = kw.pop('inactiveforeground', 'black')
tk.Spinbox.__init__(self, master=master, **kw)
supportinactive.__init__(self, inactivebg, inactivefg)
如果您想了解这种继承是如何工作的,请查看以下答案:-