How to erase everything from the tkinter text widget?

匿名 (未验证) 提交于 2019-12-03 08:39:56

问题:

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.

Here is my code for this part:

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

looking forward for offers)

回答1:

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.

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.



回答2:

With a string you can remove last character with:

msg = msg[:-2] 

You could also remove all whitespace from the end of the string (including newlines) with:

msg = msg.rstrip() 

OK. After reading your comment, I think you should check this page: The Tkinter Text Widget

where it is explained:

"If you insert or delete text before a mark, the mark is moved along with the other text. To remove a mark, you must use the *mark_unset* method. Deleting text around a mark doesn’t remove the mark itself."

----EDIT----

My mistake, disregard the above paragraph. Marks have nothing to do with the newline. As Bryan explains in his answer: The tkinter text widget guarantees that there is always a newline following the last character in the widget.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!