有没有办法在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()
最佳答案
不,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/