【问题标题】:TkInter Label Change Font Size by Text LengthTkInter 标签按文本长度更改字体大小
【发布时间】:2015-05-07 04:00:12
【问题描述】:

早上好,

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

【问题讨论】:

  • 您的问题是什么?你这样做有什么问题?
  • tkinter tkFonts 有一个 measure() 方法,它将返回字符串在字体中的宽度像素数,因此您可以使用它来确定是增加还是减少大小。
  • @martineau 谢谢
  • @BryanOakley 我需要以像素为单位获取字体宽度,或者设置像 wraplength 这样在大于标签宽度时调整字体大小的内容
  • 为什么有人拒绝我的问题?

标签: python user-interface tkinter


【解决方案1】:

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

使用自定义字体创建标签的简单方法如下所示(对于 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 2019-09-06
    • 2017-08-07
    • 2019-02-26
    • 1970-01-01
    • 2017-08-05
    • 2022-09-28
    相关资源
    最近更新 更多