Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从高度约束导出字体大小?_Python_Fonts_Tkinter - Fatal编程技术网

Python 如何从高度约束导出字体大小?

Python 如何从高度约束导出字体大小?,python,fonts,tkinter,Python,Fonts,Tkinter,我需要将标签的高度固定为给定的像素数(根据屏幕尺寸计算)。为此,我想导出字体大小(对于字体系列),它将允许我的字符串适合该行 .metrics()方法允许我找到字体的平均高度(我认为这是字形0的高度),但我认为这无助于确定任意字符串的高度 我可以使用哪个Tkinter功能来实现这一点?使用tkFont.Font,您可以将字体大小设置为负数,以像素为单位: tkFont.Font(..., size=-20) 因此,如果从屏幕尺寸(以像素为单位)导出的每个标签的高度可变,则可以将字体设置为该变量

我需要将
标签的高度固定为给定的像素数(根据屏幕尺寸计算)。为此,我想导出字体大小(对于字体系列),它将允许我的字符串适合该行

.metrics()
方法允许我找到字体的平均高度(我认为这是字形
0
的高度),但我认为这无助于确定任意字符串的高度


我可以使用哪个
Tkinter
功能来实现这一点?

使用
tkFont.Font
,您可以将字体大小设置为负数,以像素为单位:

tkFont.Font(..., size=-20)
因此,如果从屏幕尺寸(以像素为单位)导出的每个标签的高度可变,则可以将字体设置为该变量:

tkFont.Font(..., size=-height)
这不是一个完美的解决方案,因为除非您的字体是完全方形的,否则每个字符的像素高度通常会大于像素宽度。也许固定宽度字体有一个比例(即,如果字体的像素大小为6,高度为6*2),你可以利用这个比例,但我认为你不能直接设置字体的高度

另一种选择是直接将标签的大小分配给像素大小,使用一种类似于给标签一张空白图像的技巧,使其将像素大小注册为宽度/高度值:

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()
希望我正确地理解了您要完成的任务,这会有所帮助