Calculating the pixel size of a string with Python
        Posted  
        
            by Aristide
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Aristide
        
        
        
        Published on 2010-05-27T15:05:39Z
        Indexed on 
            2010/05/27
            15:11 UTC
        
        
        Read the original article
        Hit count: 337
        
I have a Python script which needs to calculate the exact size of arbitrary strings displayed in arbitrary fonts in order to generate simple diagrams. I can easily do it with Tkinter. The problem is the results seem to depend on the version of Python and/or the system.
import Tkinter as tk
import tkFont
root = tk.Tk()
times12 = tkFont.Font(family="times",size=12)
print times12.metrics("linespace"),
print times12.measure("Hello world")
times24 = tkFont.Font(family="times",size=24)
print times24.metrics("linespace"),
print times24.measure("Hello world")
Python 2.5 on Mac OS X gives the actual pixel measurements:
12 57
24 116
Python 2.6.1 on Mac OS X gives:
14 58
27 115
Python 2.6.3 on Windows XP gives:
19 71
36 154
Such a need being quite common, I suspect I did something wrong. Any idea?
© Stack Overflow or respective owner