Find Visible Region in a Text Widget

April 29, 1999 | Fredrik Lundh

To get the index of the first visible character, use text.index(“@0,0”).

To get the index of the last visible character (the end of the last visible line), use text.index(“@0,%d” % text.winfo_height()).

Example:

 
from Tkinter import *

root = Tk()

# create a scrolled text widget

frame = Frame(root, bd=2, relief=SUNKEN)

scrollbar = Scrollbar(frame, orient=VERTICAL)
scrollbar.pack(fill=Y, side=RIGHT)

text = Text(frame, bd=0)
text.pack()

for i in range(1, 1000):
    text.insert(END, "line %s\n" % i)

# attach scrollbar
text.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=text.yview)

frame.pack()

label = Label(root)
label.pack()

def report_position():

    # get (beginning of) first visible line
    top = text.index("@0,0")

    # get (end of) last visible line
    bottom = text.index("@0,%d" % text.winfo_height())

    # update the label
    label.config(text="top:    %s\nbottom: %s" % (top, bottom))
    root.after(100, report_position) # update 10 times a second

report_position()

mainloop()

A Django site. rendered by a django application. hosted by webfaction.