Skip to content Skip to sidebar Skip to footer

Help With Event In Python Entry Widget

I'm writing some code in python and I'm having trouble when trying to retrieve content of an Entry widget. The thing is: I want to limit the characters that can be typed, so I'm tr

Solution 1:

At first, after you do the deletion, the event goes on with its normal processing, i.e. the character gets inserted. You need to signal to Tkinter that the event should be ignored.

So in your code above, add the marked line:

if len(self.__value) > 2:
    widgetName.delete(2,4)
    return"break" # add this line

On the other hand, why do you go through the lambda? An event has a .widget attribute which you can use. So you can change your code into:

    self.__aEntry.bind('<Key>', self.callback) # ※ here!
    self.__aEntry.pack(side=LEFT)

defcallback(self, event):
    self.__value = event.widget.get()+event.char # ※ here!print self.__value
    iflen(self.__value)>2:
        event.widget.delete(2,4) # ※ here!return"break"

All the changed lines are marked with "here!"

Solution 2:

To be a bit more specific, Tk widgets have what are called "bindtags". When an event is processed, each bindtag on the widget is considered in order to see if it has a binding. A widget by default will have as its bindtags the widget, the widget class, the root widget, and "all". Thus, bindings to the widget will occur before the default bindings. Once your binding has been processed you can prevent any further bindtags from being considered by returning a "break".

The ramifications are this: if you make a binding on the widget, the class, root window and "all" bindings may fire as well. In addition, any binding you attach to the widget fires before the class binding which is where the default behavior (eg: the insertion of a character) happens. It is important to be aware of that in situations where you may want to handle the event after the default behavior rather than before.

Post a Comment for "Help With Event In Python Entry Widget"