0

I am trying to make a function which find the number of lines necessary in a Text box for a string "text"

something like this

import tkinter as tk

def get_lines(text):
    text_widget = tk.Text(None,  width=55, height = 10)
    text_widget.configure(font=("Helvetica "+str(12)))
    text_widget.insert(tk.END, text)

    return text_widget.index('end')

Seems simple enough, right? However, no matter how many lines contained in my text box it returns '2.0'. Can someone confirm that this is just my computer, or let me know what is going on? This seems to be the solution that works for other people.

J M
  • 31
  • 4
  • btw `font=('Helvetica', 12)` would work too, you don't necessarily convert it to a string – Matiiss Nov 03 '21 at 14:00
  • 1
    You string apparently contains no newlines, except maybe one at the very end. It's therefore one line long; text wrapping is purely a visual effect, and does not change the text indices. To determine the visual height of the text, the `.bbox()` or `.dlineinfo()` methods may be useful. – jasonharper Nov 03 '21 at 14:01
  • 1
    you may also want to use [`tkinter.font`](https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/fonts.html) to measure the text without even needing to create a text widget (using `.measure` you can get the width if that helps) – Matiiss Nov 03 '21 at 14:03
  • If `text` argument always contain "text", then the result is always '2.0'. – acw1668 Nov 03 '21 at 14:07
  • Does this answer your question? https://stackoverflow.com/q/46081798/7432 – Bryan Oakley Nov 03 '21 at 14:47
  • The tkinter font worked - just had to guess and check for my configuration and it came out to 492 pixels a line. Thanks for the help – J M Nov 03 '21 at 14:58

0 Answers0