Fitting Text Into A Rectangle (width X By Height Y) With Tkinter
Solution 1:
The problem with your code is that you're using the width of a widget, but the width will be 1 until the widget is actually laid out on the screen and made visible, since the actual width depends on a number of factors that aren't present until that happens.
You don't need to put the text in a widget in order to measure it. You can pass a string to font.measure() and it will return the amount of space required to render that string in the given font.
For python 3.x you can import the Font class like this:
from tkinter.font import FontFor python 2.x you import it from the tkFont module:
from tkFont import FontYou can then create an instance of Font so that you can get information about that font:
font = Font(family="Purisa", size=18)
length = font.measure("Hello, world")
print"result:", lengthYou can also get the height of a line in a given font with the font.metrics() method, giving it the argument "linespace":
height = font.metrics("linespace")
Solution 2:
The widget will not have a width until it is packed. You need to put the label into the frame, then pack it, then forget it.
Solution 3:
I've actually stumbled across a way of doing this through trial and error
By using measure.update_idletasks() 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.S. I wouldn't mind some votes to get a nice, shiny, bronze, self-learner badge ;)
Post a Comment for "Fitting Text Into A Rectangle (width X By Height Y) With Tkinter"