tags:

views:

481

answers:

2

Playing around with Python - tkInter - Entry widget - when I use validatecommand (below), the check happens the first time the string > Max, but when I continue to enter text the check steps - there's no delete or insert after the first time? Any advice? (outside of not building a desktop app via python)


#!/usr/bin/env python
from Tkinter import *

class MyEntry(Entry):

    def __init__(self, master, maxchars):
        Entry.__init__(self, master, validate = "key",    validatecommand=self.validatecommand)
        self.MAX = maxchars

    def validatecommand(self, *args):
        if len(self.get()) >= self.MAX:
            self.delete(0,3)
            self.insert(0, "no")
        return True

if __name__ == '__main__':
    tkmain = Tk()
    e = MyEntry(tkmain, 5)
    e.grid()
    tkmain.mainloop()
+1  A: 

I'm sure exactly what the reason is, but I have a hunch. The validation check is done every time the entry is edited. I did some testing and found that it does indeed execute, and can do all sorts of things during the validation every time. What causes it to stop working correctly is when you edit it from within the validatecommand function. This causes it to stop calling the validate function any further. I guess it no longer recognizes further edits to the entry value or something.

lgal Serban seems to have the behind the scenes info on why this occurs.

Tofystedeth
+3  A: 

From the Tk man:

The validate option will also set itself to none when you edit the entry widget from within either the validateCommand or the invalidCommand. Such editions will override the one that was being validated. If you wish to edit the entry widget (for example set it to {}) during validation and still have the validate option set, you should include the command

after idle {%W config -validate %v}

don't know how to translate that to python.

Igal Serban