为此,您需要为标签指定唯一的字体,然后使用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()