Tkinter: How to get Label wraplength functionality in Text Box

Guilherme Polo ggpolo at gmail.com
Thu Oct 30 10:19:33 EDT 2008


On 10/30/08, Mudcat <mnations at gmail.com> wrote:
> I'm not sure why my tkinter would not be compiled against 8.5 since I
>  have the latest version. I assumed that Python 2.6 would have it
>  without requiring me to do an extra compile.

It is not really python's fault if tkinter is compiled against tcl/tk
8.5 or not. The windows installer for python 2.6 happens to include
tcl/tk 8.5 and tkinter compiled against them, but ubuntu for example
doesn't distribute tkinter compiled against tcl/tk 8.5 at the moment.

>
>  However I was able to get it working using the code you gave me.
>  Thanks for that. The only problem is that it seems to simply be
>  counting newlines (or number of \n). When I use the following:
>
>         numlines = widget.count("1.0", "end", "displaylines", "lines")
>         print "Number of lines is ", numlines
>
>  I get this:
>
>  Number of lines is  (153, 1)

The first is the number of displaylines, the second is the number of lines.

>
>  So that's not actually the number of lines displayed in the box, just
>  the number of newline chars it finds.

Not really. displaylines returns the number of lines displayed in the
text widget, and lines returns the number of newlines found.
Note that it is important to call "count" only after the text widget
is being displayed, otherwise displaylines won't work correctly (not
with tk 8.5.3 at least).

> I couldn't find anything in the
>  tk documentation that would give me any other options to count lines
>  differently, or number of lines displayed after wrapping.

Try this and check what you get:


import Tkinter

root = Tkinter.Tk()
text = Tkinter.Text()
text.pack()

def test(event):
    print "displaylines:", text.count("1.0", "end", "displaylines")
    print "lines:", text.count("1.0", "end", "lines")

text.insert("1.0", "a" * 81)
text.insert("2.0", "b\n")
text.bind('<Map>', test)

root.mainloop()


You should have 3 lines displayed but only 2 "real" lines.


-- 
-- Guilherme H. Polo Goncalves



More information about the Python-list mailing list