如何获取Label的真实当前大小?

0 投票
1 回答
1380 浏览
提问于 2025-04-18 14:56

我在根窗口里有一个Frame(根窗口的大小是通过.geometry()设置的),里面放了两个Label,它们填满了这个Frame。我想知道这两个Label的当前大小,以便调整它们文本的字体大小。

我试过.winfo_reqheight(),但是返回的值让我搞不懂。下面的例子展示了我遇到的问题(三个问题用粗体标出):

import Tkinter as tk

root = tk.Tk()
root.geometry("200x200")
# top level frame, containing both labels below. Expands to fill root
f = tk.Frame(root)
f.pack(expand=True, fill=tk.BOTH)
# the condition for the two cases mentioned in the text below
if True:
    text = ""
else:
    text = "hello\nhello\nhello\nhello"
# two labels, the top one's txt will be changed
l1 = tk.Label(f, text=text, font=('Arial', 40), background="green")
l1.pack(expand=True, fill=tk.BOTH)
l2 = tk.Label(f, text="hello", font=('Arial', 15), background="blue")
l2.pack(expand=True, fill=tk.BOTH)
# just in case, thank you https://stackoverflow.com/users/2225682/falsetru
for i in [f, l1, l2]:
    i.update_idletasks()
print("top label: reqheight = {0} height = {1}, bottom label: reqheight = {2} height = {3}".format(
    l1.winfo_reqheight(), l1.winfo_height(),
    l2.winfo_reqheight(), l2.winfo_height()
))
root.mainloop()

案例 1:条件设置为True(空文本字符串)

这里输入图片描述

输出结果是

top label: reqheight = 66 height = 1, bottom label: reqheight = 29 height = 1

所有的控件都设置为可以扩展,所以为什么它们的总高度是66+29=95,而窗口的高度是200像素呢?

我该如何获取 i) 空的,ii) 填充了文本的,和 iii) 扩展的Label的高度——我想把这个高度作为参考(如果Label变大了,我就知道它不能超过这个参考值)?

案例 2:条件为False(多行文本字符串)

这里输入图片描述

以及

top label: reqheight = 246 height = 1, bottom label: reqheight = 29 height = 1

为什么上面的Label挤压了下面的那个? 有没有什么机制可以让它们说'尽量扩展,但要注意其他控件?'

1 个回答

0

reqheight 是一个“请求”的高度——也就是这个标签希望的高度,不管它在窗口里怎么放置。当布局管理器问“你需要多大空间?”时,它会给出这个大小。这个值不会因为你使用 pack、place 或 grid 的方式,或者包含窗口的大小而改变。

如果你想知道实际的高度,可以使用 winfo_height

撰写回答