我有一个 ttk.Entry 的实例。用户点击它。我有事件绑定。根据某些条件,我要么希望输入光标出现并允许输入,要么我基本上想忽略单击并且不让输入光标出现在 ttk.Entry 中。我不想使用只读或禁用状态。
操纵焦点没有效果。
这是一个可以满足您要求的课程。
class MyEntry(Entry):
def disable(self):
self.__old_insertontime = self.cget('insertontime')
self.config(insertontime=0)
self.bind('<Key>', lambda e: 'break')
def enable(self):
self.unbind('<Key>')
if self.cget('insertontime') == 0:
self.config(insertontime=self.__old_insertontime)
但是,由于您真正关心的是您不希望禁用的条目看起来已禁用,因此只需设置 和 的颜色disabledbackground
以disabledforground
匹配 和 的background
颜色forground
。如果您需要将其整合到一个类中,请执行以下操作:
class MyEntry(Entry):
def __init__(self, *args, **kwds):
Entry.__init__(self, *args, **kwds)
self.config(disabledbackground=self.cget('background'))
self.config(disabledforeground=self.cget('foreground'))
并像这样使用它:
e = MyEntry(root)
e.config(state=DISABLED) # or state=NORMAL
笔记。 重新发明 gui 约定时要小心。让一些看起来启用的东西被禁用可能会让用户感到困惑。所以除非你有充分的理由,否则不要改变它。
在浏览了 ttk 文档之后,这可以解决问题:
ttk.Style().map("TEntry",
foreground=[('disabled', 'black')],
fieldbackground=[('disabled','white')]
)
widget['state'] = 'disabled'