为什么帧的自然高度没有立即更新?

2024-04-26 06:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

为了做到这一点,我在文本更新后查询.winfo_reqheight()和{},我的想法是减少它并在循环中重写文本,直到它适合为止(任何更好的想法都是热烈欢迎的)

无论如何,我编写了一个测试脚本来实现这个特性,但是我得到的Frame的高度与{}的高度相比是一次性的(在更新了文本之后)。在

在实践中:准则

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显示后

enter image description here

和输出

^{pr2}$

看看Frame的大小是如何一次完成的?尽管两个小部件同时被查询,但这种行为的原因是什么?在


Tags: 文本selfapp高度部件defcounterroot
1条回答
网友
1楼 · 发布于 2024-04-26 06:29:35

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

但您可以使用^{}强制更新:

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

enter image description here

更新

^{} 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).

相关问题 更多 >