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 coll

这篇博客探讨了如何使用Python的Tkinter库来计算字符串在不同字体下的精确尺寸,以及在不同Python版本和操作系统中遇到的问题。作者发现不同Python版本和平台上字体尺寸存在差异,并提出可能的解决方案,包括使用像素而不是点来指定字体大小,以及检查`font.actual()`以了解实际使用的字体。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



