以下腳本使用TkInter文本小部件打開文本文件。 get_location
功能讓用戶點擊文本編輯器,它會顯示光標的位置。這使用索引CURRENT
,它對應於最接近鼠標指針的字符。使用TkInter文本小部件訪問與光標位置相關的line.end
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.0
,並且在16.11
位置是線16中,字符串的第十一索引。
如何訪問line.end
?當用戶點擊一個段落,並輸出位置(例如16.11
),我想知道,第(16.0
)和段結束的開始(16.len(number of characters in paragraph)
)
的目標是保存之間的串該段落的開頭和結尾,根據用戶點擊的位置。
你可能要檢查這個答案覆蓋[文本的結束位置(HTTP:// stackoverflow.com/questions/19477106/how-do-i-get-the-line-and-column-of-the-end-position-of-text-in-tkinter)或者effbot的[The Tkinter Text Widget](http ://effbot.org/tkinterbook/text.htm)頁面 – Lafexlos
@Lafexlos我注意到了。但是,我希望我點擊段落的'.index(「end」)'。如果我在位置「16.75」處點擊段落(「行」)16,則結束索引應該是「16」的結束索引。 – ShanZhengYang
@Lafexlos我也不完全確定如何使用effbot頁面上列出的索引方法來訪問'16.0'。不知何故,你必須從'%d。%d'中去掉第一個整數,然後將它放在'%d.0'中。 – ShanZhengYang