我需要将Label
的高度固定为给定的像素数(根据屏幕尺寸计算)。为此,我想得出字体大小(对于字体系列),这将允许我的字符串适合该行。
.metrics()
方法允许我找到字体的平均高度(我认为这是字形0
的高度),但我不相信这有助于确定字体的高度任意字符串。
我可以使用哪种Tkinter
功能来实现这一目标?
答案 0 :(得分:0)
使用tkFont.Font
,您可以通过将其设为负数来设置字体大小:
tkFont.Font(..., size=-20)
因此,如果从屏幕尺寸(以像素为单位)得出每个Label的高度可变,则可以将字体设置为该变量:
tkFont.Font(..., size=-height)
这不是一个完美的解决方案,因为除非您的字体是完全正方形,否则像素高度通常会大于每个字符的像素宽度。也许固定宽度的字体有一个比例(即,如果字体的像素大小是6,高度是6 * 2),你可以利用,但我不认为你可以直接设置字体的高度
另一种选择是直接将Label的大小分配给像素大小,使用hack就像给它一个空白图像,使其将像素大小注册为宽度/高度值:
root = Tk()
# derived width and height
width = 400
height = 40
# blank photo image
image = PhotoImage()
Label(root, image=image, compound='center', text='Hello World',
width=width, height=height, bg='white').pack()
mainloop()
或者,两者的结合:
root = Tk()
# derived width and height
width = 400
height = 40
# add a font
font = tkFont.Font(size=-height)
# blank photo image
image = PhotoImage()
Label(root, image=image, compound='center', text='Hello World',
width=width, height=height, bg='white', font=font).pack()
mainloop()
希望我理解你正在努力完成的事情,这会有所帮助。