python统计字符串长度,用Python计算字符串的像素大小

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值