ShanZhengYang
ShanZhengYang

Reputation: 17631

Accessing line.end with TkInter text widget, relative to cursor location

The following script opens a text file with the TkInter text widget. The get_location function lets users click on the text editor, and it will show the location of the cursor. This uses the index CURRENT, which corresponds to the character closest to the mouse pointer.

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()

The output location is in the form line.column, i.e. the beginning location is 1.0, and the location at 16.11 is line 16, eleventh index of the string.

How can I access line.end? When the user clicks on a paragraph and outputs a location (e.g. 16.11), I would like to know the beginning of that paragraph (16.0) and the end of that paragraph (16.len(number of characters in paragraph))

The goal is to save the string between the beginning and end of the paragraph, based on where the user clicks.

Upvotes: 0

Views: 3064

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385900

Given a an existing index (eg: 16.11, CURRENT, "insert", etc), the first character of that line can be referenced with "16.11 linestart", and the last character is "16.11 lineend"

If you want the start of the line that contains the CURRENT index, you can use the literal word "current", as in "current linestart" and current lineend. If you prefer to use the constant, use string concatenation: CURRENT + " lineend".

The definitive description of text widget indices can be found on the tcl/tk man page for the text widget: http://tcl.tk/man/tcl8.5/TkCmd/text.htm#M7

Upvotes: 1

Related Questions