【问题标题】:Display three dots in the end of a Tkinter Label text在 Tkinter 标签文本的末尾显示三个点
【发布时间】:2018-12-11 03:07:51
【问题描述】:

有没有办法在 CSS 的 text-overflow 属性中显示三个点,如省略号?

这是一个示例标签:

Label(root, text = "This is some very long text!").pack()

还有一个有宽度属性的:

Label(root, text = "This is some very long text!", width = 15).pack()

【问题讨论】:

    标签: python python-2.7 tkinter


    【解决方案1】:

    不,tkinter 没有任何内置功能可以做到这一点。您可以通过绑定<Configure> 事件来获得相同的效果,该事件会在小部件改变大小时触发(例如,当它添加到窗口时,或者当用户调整窗口大小时)。

    在绑定函数中获取字体和文本,使用字体的measure 属性,然后开始截断字符,直到标签适合为止。

    示例

    import Tkinter as tk           # py2
    import tkFont                  # py2
    #import tkinter as tk           # py3
    #import tkinter.font as tkFont  # py3
    
    root = tk.Tk()
    
    def fitLabel(event):
        label = event.widget
        if not hasattr(label, "original_text"):
            # preserve the original text so we can restore
            # it if the widget grows.
            label.original_text = label.cget("text")
    
        font = tkFont.nametofont(label.cget("font"))
        text = label.original_text
        max_width = event.width
        actual_width = font.measure(text)
        if actual_width <= max_width:
            # the original text fits; no need to add ellipsis
            label.configure(text=text)
        else:
            # the original text won't fit. Keep shrinking
            # until it does
            while actual_width > max_width and len(text) > 1:
                text = text[:-1]
                actual_width = font.measure(text + "...")
            label.configure(text=text+"...")
    
    label = tk.Label(root, text="This is some very long text!", width=15)
    label.pack(fill="both", expand=True, padx=2, pady=2)
    label.bind("<Configure>", fitLabel)
    
    tk.mainloop()
    

    【讨论】:

    • 非常感谢您的回复,这对我有用(不幸的是,Novel 最先回答了)
    • 对我不起作用:nametofont() 方法引发了这个异常:TclError: named font TkTextFont does not already exist
    • @LRMAAX:知道更多细节我无能为力。这是标准 tkinter 字体的名称,并且已经使用了很多年。
    • @BryanOakley 我相信你,因为我没有直接输入字体名称:它是通过cget() 方法从正确呈现的小部件中检索的。唯一的区别是我试图将此解决方案应用于ttk.Entry 而不是Label
    【解决方案2】:

    没有内置方式,但您可以轻松制作自己的:

    import tkinter as tk
    
    class AyoubLabel(tk.Label):
        '''A type of Label that adds an ellipsis to overlong text'''
        def __init__(self, master=None, text=None, width=None, **kwargs):
            if text and width and len(text) > width:
                text = text[:width-3] + '...'
            tk.Label.__init__(self, master, text=text, width=width, **kwargs)
    

    现在只需使用AyoubLabel 而不是Label

    这不会对创建标签或使用文本变量后更新标签做出反应,但如果需要,您可以添加这些功能。

    【讨论】:

    • 此解决方案仅适用于标签大小在使用packplacegrid 放置在窗口中时不变的情况。它假定小部件将完全是指定的宽度。可变宽度字体也有点不精确。例如,如果宽度为 15,如果有几个字符很窄(小写 i 或 l、逗号、句点等),则可能有 20 个或更多字符的空间。不过,很多时候“足够好”就足够了。
    猜你喜欢
    • 2019-12-22
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多