0

In this short program I would like to know how many lines the messages needs to be displayed. The problem is that rather than to answer me that it needs 3 lines here, it gives me 1. Why ? I tried different solutions found about this topic, but no one was working, each of them had som issues (it was not counting the number of lines as here).

I use Python 3.9.2 on Windows 10

Thanks for the help !!!

from tkinter import *

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

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

root.mainloop()

1 Answers1

0

Adapted from here:

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

# Note `text.count("0.0", "end", "displaylines")` returns a tuple like this: `(3, )`
result = text.count("0.0", "end", "displaylines")[0]
print(result)

root.mainloop()
TheLizzard
  • 7,248
  • 2
  • 11
  • 31
  • The `"0.0"` should be `"1.0"` - the first part of that is the line, and lines start counting with 1. The second part is the character and characters start counting with 0. – Bryan Oakley Feb 24 '21 at 15:41
  • @BryanOakley according to the tcl docs `"1.0"` and `"0.0"` do the same thing and I prefer `"0.0"`. – TheLizzard Feb 24 '21 at 15:42
  • @BryanOakley the tcl docs on indices are [here](https://www.tcl.tk/man/tcl8.6/TkCmd/text.htm#M24). It says: *Lines are numbered from 1 for consistency with other UNIX programs that use this numbering scheme.* and illegal ranges are ignored. So `"0.0"` would always have the same affect as `"1.0"`. – TheLizzard Feb 24 '21 at 15:45
  • @TheLizzard: yes, `"0.0"` has the same effect, but it's better to use the proper index, especially if you're trying to teach someone else how to do something. – Bryan Oakley Feb 24 '21 at 15:49
  • Why don't just call `text.count("1.0", "end", "displaylines")`? – acw1668 Feb 24 '21 at 15:53
  • @acw1668 That is actually better - I edited my answer. – TheLizzard Feb 24 '21 at 16:06