简体   繁体   English

如何在Tkinter中获取文本结束位置的行和列?

[英]How do I get the line and column of the end position of text in Tkinter?

I have text area in my Tkinter GUI. 我的Tkinter GUI中有文本区域。 I want to implement an undo function which will delete the last line. 我想实现一个撤消功能,它将删除最后一行。 For that, I need to get the line and column of the last line. 为此,我需要获取最后一行的行和列。

How do I get the line and position of the last line? 如何获得最后一行的行和位置? And once I get the positions, how do I delete the line? 一旦获得职位,如何删除该行?

I have searched for this on google, but I am not getting any worthwhile links. 我已经在Google上搜索了此文件,但没有任何有价值的链接。

The index of the last line is "end" or the tkinter constant END . 最后一行的索引是"end"或tkinter常数END tkinter always inserts an invisible newline at the end, so this actually represents the index immediately after the last character entered by the user. tkinter总是在末尾插入一个不可见的换行符,因此它实际上表示用户输入的最后一个字符之后的索引。

You can get the line and column number by using the index method of the text widget. 您可以使用文本小部件的index方法获取行号和列号。 So, for example, to get the row/column of the last character with this: 因此,例如,使用以下命令获取最后一个字符的行/列:

pos = textwidget.index("end")

You can add modifiers to an index, to get a position relative to another position. 您可以向索引添加修饰符,以获得相对于另一个位置的位置。 For example, to get the index of the start of the line you can append linestart (eg: "3.5 linestart" will give you 3.0). 例如,要获取行首的索引,您可以附加linestart (例如:“ 3.5 linestart”将给您3.0)。 You can also subtract characters by appending "-n chars" or "-nc" (eg: "3.5-1c" will give you 3.4). 您还可以通过附加“ -n字符”或“ -nc”来减去字符(例如:“ 3.5-1c”将为3.4)。

These modifiers can be combined. 这些修饰符可以结合使用。 So, in the case of wanting to find the start of the last line of text you want to go from the end (which is actually after the extra newline that tkinter adds), back up one character to get to the end of the line, then use "linestart" to get to the beginning: 因此,如果要查找要从结尾开始的文本的最后一行的开始(实际上是在tkinter添加的额外换行符之后),请备份一个字符以到达该行的结尾,然后使用“ linestart”开始:

pos = textwidget.index("end-1c linestart")

For what it's worth, this is all documented and pretty easy to find. 值得一提的是,所有内容均已记录在案,而且非常容易找到。 At the time that I write this, the first result when I search google for "tkinter text widget" points to a page which documents the text widget index expressions: http://effbot.org/tkinterbook/text.htm . 在撰写本文时,当我在Google上搜索“ tkinter文本小部件”时的第一个结果指向一个页面,该页面记录了文本小部件索引表达式: http : //effbot.org/tkinterbook/text.htm Look for the section named "expressions". 查找名为“表达式”的部分。

To delete a line of text, you need to call the delete method with the starting and ending index of the text you want to delete. 要删除一行文本,您需要使用要删除的文本的开始和结束索引来调用delete方法。 To delete the last line, use this: 要删除最后一行,请使用以下命令:

textwidget.delete("end-1c linestart", "end")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM