Tkinter Text widget - how to find out number of rows and columns? Tkinter Text widget - how to find out number of rows and columns? tkinter tkinter

Tkinter Text widget - how to find out number of rows and columns?


So finally I've found a solution to my problem. The approximate number of lines that can be displayed in Text can be found by measuring the font height in pixels and dividing it by the height of Text. It is not absolutely accurate (I think the value is also affected by spacing between the lines and/or spacing at the beginning/end of the text or somethig like that) but I haven't dug into it more because just this simple solution works perfectly for my needs.

Here's a sample code, just in case someone needs to solve similar problem in the future. Just run it and then resize the window and you will see how the visible lines count will change.

# Text widget lines (rows) count example - tested in Python 3.3.2from tkinter import Text, font as fclass ExampleApp:    def __init__(self, parent):        font = f.Font(family="courier", size=12)        self.line_height = font.metrics("linespace")        self.text = Text(parent, width=70, height=20, font=font)        self.text.pack(fill=BOTH, expand=Y)        self.text.bind("<Configure>", self.linecount)    def linecount(self, *args):        num_lines = int(self.text.winfo_height() / self.line_height)        self.text.delete(0.0, END)        self.text.insert(0.0,                         "Approximate number of visible lines: %d" % num_lines)root = Tk()root.title("Text widget line count example")app = ExampleApp(root)root.mainloop() 


Use the index method of the text widget like:

endline, endcolumn = text.index('end').split('.')

This function returns a tuple in the form line.charnumber.