在Tkinter标签文本的末尾显示三个点

时间:2018-07-02 21:11:05

标签: python python-2.7 tkinter

有什么办法在CSS的文本溢出属性中显示三个点,例如省略号吗?

这是一个示例标签:

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

enter image description here

另外一个具有width属性的

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

enter image description here

2 个答案:

答案 0 :(得分:2)

不,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()

答案 1 :(得分:0)

没有内置方法,但是您可以轻松地自己制作:

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

在创建标签或使用文本变量后,这对更新标签没有反应,但是如果需要,可以添加这些功能。