TkInter 标签按文本长度更改字体大小

TkInter Label Change Font Size by Text Length

早上好,

我有一个固定宽度的 Tkinter 标签。在这个标签中,我设置了一个动态文本。当文本宽度长于标签宽度时,我需要更改字体大小(减小或增大)。 这是一个例子:

为此,您需要为标签指定一种独特的字体,然后使用该字体的 measure 方法来计算该字体中的给定字符串需要多少 space。然后你只需要不断增加或减少字体大小,直到它适合标签。

使用自定义字体创建标签的简单方法如下所示(对于 python 2.x;对于 3.x,导入会略有不同):

import Tkinter as tk
import tkFont

label = tk.Label(...)
original_font = tkFont.nametofont(label.cget("font"))
custom_font = tkFont.Font()
custom_font.configure(**original_font.configure())
label.configure(font=custom_font)

现在您可以使用 custom_font.measure(...) 计算出在当前字体大小下标签需要多少像素。如果像素数太大,请更改字体大小并重新测量。重复,直到字体大到足以容纳文本。

当您更改字体大小时,标签会自动以新的字体大小重新绘制文本。

这里有一个完整的工作示例来说明该技术:

import Tkinter as tk
import tkFont

class DynamicLabel(tk.Label):
    def __init__(self, *args, **kwargs):
        tk.Label.__init__(self, *args, **kwargs)

        # clone the font, so we can dynamically change
        # it to fit the label width
        font = self.cget("font")
        base_font = tkFont.nametofont(self.cget("font"))
        self.font = tkFont.Font()
        self.font.configure(**base_font.configure())
        self.configure(font=self.font)

        self.bind("<Configure>", self._on_configure)

    def _on_configure(self, event):
        text = self.cget("text")

        # first, grow the font until the text is too big,
        size = self.font.actual("size")
        while size < event.width:
            size += 1
            self.font.configure(size=size)

        # ... then shrink it until it fits
        while size > 1 and self.font.measure(text) > event.width:
            size -= 1
            self.font.configure(size=size)

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.label = DynamicLabel(self, text="Resize the window to see the font change", width=20)
        self.label.pack(fill="both", expand=True, padx=20, pady=20)

        parent.geometry("300x200")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()