Tkinter Label 文字的多行顯示
阿新 • • 發佈:2018-10-31
在 Tk004 中,使用 width 和 heigth 來指定控制元件的大小,如果指定的大小無法滿足文字的要求
是,會出現什麼現象呢?如下程式碼:
Label(root,text = 'welcome to jcodeer.cublog.cn',width = 10,height = 3).pack()
執行程式,超出 Label 的那部分文字被截斷了,常用的方法是:使用自動換行功能,及當文
本長度大於控制元件的寬度時,文字應該換到下一行顯示,Tk 不會自動處理,但提供了屬性:
wraplength: 指定多少單位後開始換行
justify: 指定多行的對齊方式
ahchor: 指定文字(text)或影象(bitmap/image)在 Label 中的顯示位置
可用的值:
e/w/n/s/ne/se/sw/sn/center
佈局如下圖
nw n ne
w center e
sw s se
'''
from Tkinter import *
root = Tk()
#左對齊,文字居中
Label(root,
text = 'welcome to jcodeer.cublog.cn',
bg = 'yellow',
width = 40,
height = 3,
wraplength = 80,
justify = 'left'
).pack()
#居中對齊,文字居左
Label(root,
text = 'welcome to jcodeer.cublog.cn',
bg = 'red',
width = 40,
height = 3,
wraplength = 80,
anchor = 'w'
).pack()
#居中對齊,文字居右
Label(root, text = 'welcome to jcodeer.cublog.cn', bg = 'blue', width = 40, height = 3, wraplength = 80, anchor = 'e' ).pack() root.mainloop()