Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter - Counting lines in a Text widget with word wrapping

Tags:

python

tkinter

I'd like to know how to get the number of lines in a Tkinter Text widget that has word wrap enabled.

In this example, there are 3 lines in the text widget :

from Tkinter import *

root = Tk()
text = Text(root, width = 12, height = 5, wrap = WORD)
text.insert(END, 'This is an example text.')
text.pack()

root.mainloop()

But methods that work for non-wrapped text, like :

int(text_widget.index('end-1c').split('.')[0]) 

will return 1 instead of 3. Is there another method that would properly count wrapped lines (and return 3 in my example) ?

Thanks for your help !

like image 581
Xoot Avatar asked Oct 19 '22 22:10

Xoot


1 Answers

Working example using "missing count method"

It prints

displaylines: 3
lines: 1

from Tkinter import *

def count_monkeypatch(self, index1, index2, *args):
    args = [self._w, "count"] + ["-" + arg for arg in args] + [index1, index2]

    result = self.tk.call(*args)
    return result

Text.count = count_monkeypatch


root = Tk()
text = Text(root, width = 12, height = 5, wrap = WORD)
text.insert(END, 'This is an example text.')
text.pack()

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

text.bind('<Map>', test)

root.mainloop()

or with Button in place of bind

from Tkinter import *

#-------------------------------------------

def count_monkeypatch(self, index1, index2, *args):
    args = [self._w, "count"] + ["-" + arg for arg in args] + [index1, index2]

    result = self.tk.call(*args)
    return result

Text.count = count_monkeypatch

#-------------------------------------------

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

#-------------------------------------------

root = Tk()
text = Text(root, width = 12, height = 5, wrap = WORD)
text.insert(END, 'This is an example text.')
text.pack()

Button(root, text="Count", command=test).pack()

root.mainloop()
like image 153
furas Avatar answered Oct 22 '22 10:10

furas