首页 文章

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

提问于
浏览
0

我在根窗口中有一个 Frame (根窗口大小是通过 .geometry() 设置的),其中我有两个填充 FrameLabel . 我想知道 Label 的当前大小,以便调整其文本的字体大小 .

I tried .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(空文本字符串)

enter image description here

和输出

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

所有小部件都设置为展开,所以 how come their total height is 66+29=95 while the window is 200 px high?

How can I get the height 的i)空,ii)填充两种方式和iii)扩展 Label - 我将保留作为参考(如果 Label 增长我将知道它不得超过该参考)?

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

enter image description here

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

Why has the top Label crushed the bottom one? 有没有一种机制可以说'expand as much as you can but be vary of the other widgets?'

1 回答

  • 0

    reqheight是请求高度 - 标签想要的高度,无论它放在窗口中的方式如何 . 它是几何管理器询问"how much space do you need?"时它请求的大小 . 此值不会根据您使用包,地点或网格的方式或包含窗口的大小而更改 .

    如果您想要实际高度,请使用winfo_height .

相关问题