如何从 tkinter 文本小部件中删除所有内容? [英] How to erase everything from the tkinter text widget?

查看:58
本文介绍了如何从 tkinter 文本小部件中删除所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一些聊天程序开发 GUI.对于用户的输入,我有 Text() 小部件,消息通过返回"发送,然后我清理 Text().但尽管我尝试过,但我无法删除 Return 按钮创建的最后一个\n".

Im working on a GUI for some chat programme. For user's input I have Text() widget, messages are sent via "Return" and after that I clean the Text(). But as hard as I tried I cant remove the last "\n" which Return button creates.

这是我的这部分代码:

def Send(Event):
   MSG_to_send=Tex2.get("1.0",END)
   client.send(MSG_to_send)
   Tex2.delete("1.0",END)

期待优惠)

推荐答案

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

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.

这篇关于如何从 tkinter 文本小部件中删除所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆