Fitting text into a rectangle (width x by height y) with tkinter
<p>I'm trying to make a program which will fit text into a rectangle (x by y) depending on the text, the font and the font size</p>

<p>Here is the code</p>

<pre><code>def fit_text(screen, width, height, text, font):
    measure_frame = Frame(screen) # frame
    measure_frame.pack()
    measure_frame.pack_forget()
    measure = Label(measure_frame, font = font) # make a blank label
    measure.grid(row = 0, column = 0) # put it in the frame

    ##########################################################
    # make a certain number of lines
    ##########################################################

    words = text.split(" ")
    lines = []
    num = 0
    previous = 0
    while num &lt;= len(words):                
        measure.config(text = " ".join(words[previous:num])) # change text
        line_width = measure.winfo_width() # get the width
        print(line_width)
        if line_width &gt;= width: # if the line is now too long
            lines.append(" ".join(words[previous:num - 1])) # add the last vsion which wasn't too long
            previous = num - 1 # previous is now different
        num = num + 1 # next word
    lines.append(" ".join(words[previous:])) # add the rest of it
    return "\n".join(lines)

from tkinter import *    
window = Tk()
screen = Canvas(window)
screen.pack()
text = fit_text(screen, 200, 80, "i want to fit this text into a rectangle which is 200 pixels by 80 pixels", ("Purisa", 12))
screen.create_rectangle(100, 100, 300, 180)
screen.create_text(105, 105, text = text, font = ("Purisa", 12), anchor = "nw")
</code></pre>

<p>The problem with this is no matter what text is in the label the result from <code>measure.winfo_width()</code> is always 1. <a href="http://stackoverflow.com/questions/3950687/how-to-find-out-the-current-widget-size-in-tkinter">Here is where I found this from</a> but it doesn't seem to work for me</p>

<p>I've actually stumbled across a way of doing this through trial and error</p>

<p>By using <code>measure.update_idletasks()</code> it calculates the width properly and it works! Bryan Oakley definitely has a more efficient way of doing it though but I think this method will be useful in other situations</p>

<p>P.S. I wouldn't mind some votes to get a nice, shiny, bronze, self-learner badge ;)</p>

python fonts tkinter widget pixels