Determining word wraps in Tkinter text widget

Matthew Dixon Cowles matt at mondoinfo.com
Wed Nov 28 15:53:21 EST 2001


On 28 Nov 2001 12:24:46 -0800, David Wangerin <dwangeri at uci.edu> wrote:

>By floating, I mean that I have a frame on the side of the textbox
>(it's filled so it is the same size as the textbox) that will contain
>the widgets.  There will be a set of widgets corresponding to each
>line in the textbox.  To keep the appearance of the text consistent, I
>would like to keep the controls outside of the textbox.  As the text
>is scrolled up or down, the frame with the widgets gets redrawn to
>reflect the new viewable text.  If I lock the size of the textbox, I
>can always know how many lines are being displayed, but whenever a
>line wraps, I need to lower that number by one (I can't have two sets
>of controls, one for the start of the line and another for the end of
>the line).  Horizontal scrollbars would solve this problem, but I will
>only use them as a last resort.

Dear David,

You can do that but the only technique I can think of is something of
a nuisance. You'll need to figure out how many dots tall a line is
(the tkFont module may help here) and then step down the widget one
line-height at a time and use the widget's index() method with
argument of the form @x,y to see if you've gone on to the next line of
text when you've gone down one line-height.

Here's a small example:

>>> from Tkinter import *
>>> r=Tk()
>>> t=Text(r,width=10)
>>> t.pack()
>>> t.insert(END,"one\ntwo\n")
>>> t.index("@0,5")
'1.0'
>>> t.index("@0,25")
'2.0'
>>> t.delete("1.0",END)
>>> t.insert("1.0","one two three four five six")
>>> t.index("@0,5")
'1.0'
>>> t.index("@0,25")
'1.10'

In the first case, going down 25 dots puts us at the beginning of line
two but in the second case, we're at the tenth character of line one.

Regards,
Matt



More information about the Python-list mailing list