如何在 Tkinter 中获取文本结束位置的行和列? [英] How do I get the line and column of the end position of text in Tkinter?

查看:30
本文介绍了如何在 Tkinter 中获取文本结束位置的行和列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Tkinter GUI 中有文本区域.我想实现一个撤消功能,它将删除最后一行.为此,我需要获取最后一行的行和列.

I have text area in my 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.

推荐答案

最后一行的索引为 "end" 或 tkinter 常量 END.tkinter 总是在末尾插入一个不可见的换行符,所以这实际上代表了用户输入的最后一个字符之后的索引.

The index of the last line is "end" or the tkinter constant 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.

您可以使用文本小部件的index 方法获取行号和列号.因此,例如,要获取最后一个字符的行/列:

You can get the line and column number by using the index method of the text widget. So, for example, to get the row/column of the last character with this:

pos = textwidget.index("end")

您可以向索引添加修饰符,以获取相对于另一个位置的位置.例如,要获取行首的索引,您可以附加 linestart(例如:3.5 linestart"将为您提供 3.0).您还可以通过附加-n 字符"或-nc"来减去字符(例如:3.5-1c"将为您提供 3.4).

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). You can also subtract characters by appending "-n chars" or "-nc" (eg: "3.5-1c" will give you 3.4).

这些修饰符可以组合使用.因此,如果想要找到要从末尾开始的最后一行文本的开头(实际上是在 tkinter 添加的额外换行符之后),请备份一个字符以到达该行的末尾,然后使用linestart"开始:

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:

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

就其价值而言,这一切都有记录并且很容易找到.在我写这篇文章的时候,当我在谷歌搜索tkinter 文本小部件"时,第一个结果指向一个记录文本小部件索引表达式的页面:http://effbot.org/tkinterbook/text.htm.查找名为表达式"的部分.

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. Look for the section named "expressions".

要删除一行文本,您需要使用要删除的文本的开始和结束索引调用 delete 方法.要删除最后一行,请使用:

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. To delete the last line, use this:

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

这篇关于如何在 Tkinter 中获取文本结束位置的行和列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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