且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 tkinter 文本小部件中删除所有内容?

更新时间:2023-11-14 16:28:34

您的问题很可能是您的绑定发生在插入换行符之前.您删除了所有内容,但随后插入了换行符.这是由于文本小部件工作方式的性质造成的——小部件绑定发生在类绑定之前,而类绑定是用户输入实际插入小部件的地方.

Most likely your problem is that your binding is happening before the newline is inserted. You delete everything, but then the newline is inserted. This is due to the nature of how the text widget works -- widget bindings happen before class bindings, and class bindings are where user input is actually inserted into the widget.

解决方案可能会在类绑定之后调整您的绑定(例如,通过绑定到 或调整绑定标签).但是,如果没有看到您如何进行绑定,我就无法确定这是您的问题.

The solution is likely to adjust your bindings to happen after the class bindings (for example, by binding to <KeyRelease> or adjusting the bindtags). Without seeing how you are doing the binding, though, it's impossible for me to say for sure that this is your problem.

另一个问题是,当您获得文本(使用 Tex2.get("1.0",END))时,您可能会获得比预期更多的文本.tkinter 文本小部件保证小部件中的最后一个字符后面总是有一个换行符.要获取用户在没有换行的情况下输入的内容,请使用 Tex2.get("1.0","end-1c").或者,您可能希望在将文本小部件发送到客户端之前从文本小部件中的内容中去除所有尾随空格.

Another problem is that when you get the text (with Tex2.get("1.0",END)), you are possibly getting more text than you expect. The tkinter text widget guarantees that there is always a newline following the last character in the widget. To get just what the user entered without this newline, use Tex2.get("1.0","end-1c"). Optionally, you may want to strip all trailing whitespace from what is in the text widget before sending it to the client.