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

标签 python python-2.7 tkinter

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

这是一个示例标签:

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

enter image description here

还有一个具有宽度属性的:

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

enter image description here

最佳答案

不,tkinter 没有内置的东西可以做到这一点。您可以通过绑定(bind)到 <Configure> 来获得相同的效果。事件,每当小部件更改大小时(例如将其添加到窗口或用户调整窗口大小时)都会触发。

在获得字体和文本的绑定(bind)函数中,使用 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()

关于python - 在 Tkinter 标签文本的末尾显示三个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51143777/

相关文章:

python - 在切片中,为什么我不能反转列表,跳过单个括号中的最后一项?

python - 如何用 Mock 给 OS.mkdir 打补丁?

python - 如何使用字典中的重复键生成列表?

python - 如何使用 SQLAlchemy 在 Postgres 数据库中创建包含 UUID 列的表?

django - 有没有办法使用 Django REST 框架中的可浏览 API 上传文件?

python - 即使满足条件,循环也会继续(使用 Python)

Python Tkinter canvas.delete 失败

python - 动画 Tkinter

python - 每个 TKinter 小部件可用的序列列表

python - 什么 tensorflow 分布来表示分类数据列表