Skip to main content
 首页 » 编程设计

python之为什么不立即更新 Frame 的自然高度

2025年05月04日9del

我正在编写一个小部件来显示一些文本行(通过 Frame 中的 Label),一旦文本高度变大,我将需要调整字体大小比包含 Frame 的高度。

为此,我在 .winfo_reqheight() 中查询 Label 和 Frame 文本更新后,想减少它并重写文本 - 在一个循环中,直到它适合(热烈欢迎任何更好的想法)

无论如何,我编写了一个测试脚本来实现该功能,但我为 Frame 获得的高度与 Label 的高度相比是一次性的(在具有更新了文本)。

实际上:代码

import Tkinter as tk 
 
class App(): 
    def __init__(self): 
        self.root = tk.Tk() 
        self.root.geometry("200x200") 
        self.f = tk.Frame(self.root) 
        self.f.pack(expand=True, fill=tk.BOTH) 
        self.l = tk.Label(self.f) 
        self.l.pack(expand=True, fill=tk.BOTH) 
        self.root.bind("q", func=self.addline) 
        self.counter = 0 
 
    def addline(self, event): 
        mylist = list() 
        self.counter += 1 
        for _ in range(self.counter): 
            mylist.append("hello") 
        message = '\n'.join(mylist) 
        self.l.configure(text=message, font=('Arial', 30)) 
        print("frame: {0} label {1}".format(self.f.winfo_reqheight(), self.l.winfo_reqheight())) 
 
App().root.mainloop() 

按三下 q 显示

和输出

frame: 21 label 51 
frame: 51 label 96 
frame: 96 label 141 

看看 Frame 的大小是多少?尽管同时查询了两个小部件,但出现这种行为的原因是什么?

请您参考如下方法:

在事件处理程序返回之前,在那里所做的更改不会更新。

但您可以使用 update_idletasks 强制更新:

self.l.configure(text=message, font=('Arial', 30)) 
self.l.update_idletasks() 

更新

winfo_height() documentation还提到了 update_idletasks:

Get the height of this widget, in pixels. Note that if the window isn’t managed by a geometry manager, this method returns 1. To you get the real value, you may have to call update_idletasks first. You can also use winfo_reqheight to get the widget’s requested height (that is, the “natural” size as defined by the widget itself based on it’s contents).