Ayo*_*azi 3 python tkinter python-2.7
有没有办法在CSS的text-overflow属性中显示省略号之类的三个点?
这是一个示例标签:
Label(root, text = "This is some very long text!").pack()
Run Code Online (Sandbox Code Playgroud)
另一种具有宽度属性:
Label(root, text = "This is some very long text!", width = 15).pack()
Run Code Online (Sandbox Code Playgroud)
不,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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1996 次 |
| 最近记录: |