使用TkInter文本小部件访问line.end,相对于光标位置

时间:2016-01-13 14:12:40

标签: python text tkinter

以下脚本使用TkInter文本小部件打开文本文件。 get_location函数允许用户单击文本编辑器,它将显示光标的位置。这使用索引CURRENT,它对应于最接近鼠标指针的字符。

from tkinter import *
from tkinter.ttk import *

filename = "textfile1.txt"

with open(filename, "rt", encoding='latin1') as in_file:
    readable_file = in_file.read()

def get_location(event):
    print(textPad.index(CURRENT))

root = Tk()
text = Text(root)
text.insert(1.0, readable_file)
text.bind('<Button-1>', get_location)
text.pack(expand=YES, fill=BOTH)
scroll=Scrollbar(text)
text.configure(yscrollcommand=scroll.set)
scroll.config(command=text.yview)
scroll.pack(side=RIGHT, fill=Y)
root.mainloop()

输出位置的格式为line.column,即起始位置为1.016.11的位置为第16行,即字符串的第11个索引。

如何访问line.end?当用户点击某个段落并输出一个位置(例如16.11)时,我想知道该段落的开头(16.0)和该段落的结尾(16.len(number of characters in paragraph)

目标是根据用户点击的位置将字符串保存在段落的开头和结尾之间。

1 个答案:

答案 0 :(得分:1)

给定一个现有索引(例如:16.11,CURRENT,“insert”等),该行的第一个字符可以用"16.11 linestart"引用,最后一个字符是{{1 }}

如果您想要包含"16.11 lineend"索引的行的开头,则可以使用文字CURRENT,如"current""current linestart"。如果您更喜欢使用常量,请使用字符串连接:current lineend

文本小部件索引的权威性描述可以在文本小部件的tcl / tk手册页中找到:http://tcl.tk/man/tcl8.5/TkCmd/text.htm#M7