Python: How to get an updated Entry text to use in a command binded to it?

后端 未结 2 536
情话喂你
情话喂你 2021-01-24 22:05

Consider the following code:

text = Entry(); text.pack()
def show(e):
    print text.get()
text.bind(\'\', show)

Let\'s say I put th

2条回答
  •  清歌不尽
    2021-01-24 22:50

    The reason for this has to do with Tk "bindtags". Bindings are associated with tags, and the bindings are processed in tag order. Both widget names and widget classes are tags, and they are processed in that order (widget-specific bindings first, class bindings second).

    For that reason, any time you press a key your widget specific binding will fire before the class binding has a chance to modify the widget.

    There are many workarounds. The simplest is to bind to since the class bindings happen on the key press. There are other solutions that involve either adding or rearranging bind tags, or using the built-in data validation features of the entry widget. Which is best depends on what you're really trying to accomplish.

    For more information on the data validation functions, see this question: Interactively validating Entry widget content in tkinter

    For a more comprehensive answer, see Tkinter: set StringVar after event, including the key pressed

提交回复
热议问题