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.
import Tkinter as tk
import tkFont
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=200)
canvas.pack()
(x,y) = (5,5)
text = "yellow world"
fonts = []
for (family,size) in [("times",12),("times",24)]:
font = tkFont.Font(family=family, size=size)
(w,h) = (font.measure(text),font.metrics("linespace"))
print "%s %s: (%s,%s)" % (family,size,w,h)
canvas.create_rectangle(x,y,x+w,y+h)
canvas.create_text(x,y,text=text,font=font,anchor=tk.NW)
fonts.append(font) # save object from garbage collecting
y += h+5
tk.mainloop()
The results seem to depend on the version of Python and/or the system:
After Ned Batchelder mentioned it, I discovered that the size of fonts differs from platform to platform. It may not be a deal breaker as long as you stick with Tkinter, which remains consistent with itself. But my complete program does not use Tkinter to perform the actual drawing: it just relies on its font size calculations to generate an output (in SVG or as a Python script to be sent to Nodebox). And it's there that things go really wrong:
(Please look at the image in real size. Note that the main font used for these outputs is not Times, but Trebuchet MS.)
I now suspect that such discrepancies can't be avoided with Tkinter. Which other cross-platform solution would you recommend?