Last active
August 29, 2015 14:03
-
-
Save dj-foxxy/9a5d0b5ce391b82a4422 to your computer and use it in GitHub Desktop.
Fill a bounding box with text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import absolute_import | |
from __future__ import division | |
from __future__ import print_function | |
from collections import namedtuple | |
from itertools import count | |
import Tkinter as tk | |
import tkFont as tkfont | |
BoundingBox = namedtuple('BoundingBox', ['max_width', 'max_height']) | |
class TextFitter(object): | |
def __init__(self, font): | |
self._font = font | |
def fit(self, text, bbox): | |
self._set_size(self._find_largest_size(text, bbox)) | |
def _find_largest_size(self, text, bbox): | |
for fits, size in self._try_sizes(text, bbox): | |
if not fits: | |
return size - 1 | |
def _try_sizes(self, text, bbox): | |
return ((self._try_size(text, bbox, size), size) | |
for size in count(start=1)) | |
def _try_size(self, text, bbox, size): | |
self._set_size(size) | |
return self._within_bbox(text, bbox) | |
def _set_size(self, size): | |
self._font.configure(size=size) | |
def _within_bbox(self, text, bbox): | |
return self._within_max_width(text, bbox.max_width) and \ | |
self._within_max_height(bbox.max_height) | |
def _within_max_width(self, text, max_width): | |
return self._measure_width(text) < max_width | |
def _measure_width(self, text): | |
return self._font.measure(text) | |
def _within_max_height(self, max_height): | |
return self._measure_height() < max_height | |
def _measure_height(self): | |
return self._font.metrics('linespace') | |
if __name__ == '__main__': | |
tk.NoDefaultRoot() | |
root = tk.Tk() | |
font = tkfont.Font(root=root) | |
text = 'Hello, World!' | |
bbox = BoundingBox(max_width=200, max_height=60000) | |
fitter = TextFitter(font) | |
fitter.fit(text, bbox) | |
label = tk.Label(master=root, font=font, text=text) | |
label.pack() | |
root.mainloop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment