Python / Tkinter - 在Entry验证期间奇怪的插入而不是替换

时间:2013-02-21 23:07:30

标签: python validation tkinter

这是一个简单的Python / Tkinter程序,带有单个Entry小部件,我想自动检查是否输入了数字。

from Tkinter import *

class MyClass:
    def __init__(self, parent):
        self.myParent = parent
        self.portVar = IntVar()
        self.portVar.set(111)

        port_validator = self.myParent.register(self._validate)

        self.myEntry = Entry(self.myParent, width=9, textvariable=self.portVar,
            validate='all', validatecommand=(port_validator,'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'))

        self.myEntry.pack(side=TOP)


    def _validate(self, d, i, P, s, S, v, V, W):
        print "OnValidate: d='%s' i='%s' P='%s' s='%s' S='%s' v='%s' V='%s' W='%s'" % (d, i, P, s, S, v, V, W)
        return P.isdigit()


root = Tk()
myclass = MyClass(root)
root.mainloop() 

在_validate()函数中的print语句仅用于调试。 问题是在这种情况下,Entry的可视化编辑是不正确的。 例如,我在做这些步骤:

  1. 启动计划。
  2. 请参阅条目
  3. 中的“111”值
  4. 用鼠标左键选择'111'
  5. 按键盘上的“9”
  6. 而不是完全替换'111'到'9'插入发生,我看到'9111'!
  7. 调试日志(我为了方便而计算了步骤):

    1. OnValidate:d =' - 1'i =' - 1'P ='111's =''S =''v ='all'V ='强制'W ='。37125736'
    2. OnValidate:d =' - 1'i =' - 1'P ='111's ='111'S =''v ='all'V ='focusin'W ='。37125736'
    3. OnValidate:d ='0'i ='0'P =''s ='111'S ='111'v ='all'V ='key'W ='。37125736'
    4. OnValidate:d ='1'i ='0' P ='9111' s = '111'S ='9'v ='all'V ='key'W =' 0.37125736'
    5. OnValidate:d ='0'i ='1'P ='9's ='9111'S ='111'v ='all'V ='key'W ='。37125736'
    6. OnValidate:d ='1'i ='1'P = '99's ='9'S ='9'v ='all'V ='key'W ='。37125736'
    7. OnValidate:d ='1'i ='2'P ='999's ='99'S ='9'v ='all'V ='key'W ='。37125736'
    8. 注意第4步。这是一个奇怪的附加步骤,带有不需要的输入文本状态('9111')

      但如果我改变

      return P.isdigit()
      

      return True
      

      一切都变好了!条目就像其他程序中的任何条目一样。

      1. OnValidate: d='-1' i='-1' P='111' s='' S='' v='all' V='forced' W='.37650024'
      2. OnValidate: d='-1' i='-1' P='111' s='111' S='' v='all' V='focusin' W='.37650024'
      3. OnValidate: d='0' i='0' P='' s='111' S='111' v='all' V='key' W='.37650024'
      4. OnValidate: d='1' i='0' P='9' s='' S='9' v='all' V='key' W='.37650024'
      5. OnValidate: d='1' i='1' P='99' s='9' S='9' v='all' V='key' W='.37650024'
      6. OnValidate: d='1' i='2' P='999' s='99' S='9' v='all' V='key' W='.37650024'
      

      为什么,伙计们?

1 个答案:

答案 0 :(得分:0)

那是因为P.isdigit()您将内容限制为数字。当您将111替换为9时,有一个步骤,其中条目的内容是空字符串。由于''.isdigit()为false,因此小部件始终将数字作为其内容。删除此约束,您允许任何字符串,然后您可以完全替换该值。