简体   繁体   English

tkinter python:如何从ttk.Entry中删除输入光标?

[英]tkinter python: How do remove the input cursor from a ttk.Entry?

I have an instance of ttk.Entry. 我有一个ttk.Entry的实例。 The user clicks it. 用户单击它。 I have the event bound. 我有这个事件。 Depending on some condition, I either want the input cursor to appear and allow typing or I essentially want to ignore the click and not have the input cursor appear in the ttk.Entry. 根据某些条件,我要么希望输入光标出现并允许键入, 要么本质上是想忽略单击,而又不让输入光标出现在ttk.Entry中。 I don't want to have to use the readonly or disabled states. 希望有使用只读或禁用状态。

Manipulating focus has not effect. 操纵焦点没有效果。

Here is a class that does what you ask. 这是一门满足您要求的课程。

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)

However, since your real concern is that you don't want a disabled Entry to look disabled, just set the colors of disabledbackground and disabledforground to match the colors of background and forground . 但是,由于您真正担心的是您不希望禁用的Entry看起来是禁用的,因此只需将disabledbackgrounddisabledforground的颜色设置为匹配backgroundforground的颜色即可。 If you need this rolled into a class, do it like this: 如果您需要将其转入类,请按以下步骤进行:

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'))

And use it like this: 并像这样使用它:

e = MyEntry(root)
e.config(state=DISABLED) # or state=NORMAL

Note. 注意。 Be careful when reinventing gui conventions. 重新发明gui约定时要小心。 Having something that looks enabled act disabled can be confusing for users. 禁用某些看起来已启用的行为会使用户感到困惑。 So don't change this unless you have good reason. 因此,除非您有充分的理由,否则请勿更改此设置。

After trawling the ttk documentation, this does the trick: 拖曳ttk文档后,就可以了:

    ttk.Style().map("TEntry",
                    foreground=[('disabled', 'black')],
                    fieldbackground=[('disabled','white')]
                    )
    widget['state'] = 'disabled'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM