1

I'm trying to get the number of displayed lines in a Tkinter Text widget and I'm looking at this question: What's the most efficient way to get a Tkinter Text widget's total display lines after the insert?

The solution I'm interested in uses the widget's count method but on my Python 2.7.10 (Tk 8.5, Tcl 8.5) the text widget does not have that attribute.

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()

yields

AttributeError: Text instance has no attribute 'count'

From what documentation that I've found it should be there; have I missed something?

Community
  • 1
  • 1
E.Beach
  • 1,829
  • 2
  • 22
  • 34

1 Answers1

1

This appears to be a bug in Tkinter. You can use a monkeypatch to add the missing method:

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

Tkinter.Text.count = count_monkeypatch
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Thanks for the confirmation. I was going a little bit crazy trying to understand what was going on. – E.Beach Nov 18 '15 at 18:57