Tkinter 标签高度自适应内容
我有一个标签,里面要放不同大小的内容。我想知道这个标签需要多高,这样我就可以调整窗口的大小,让它在不同内容大小下保持一致。我有一个方法,但感觉比应该的要复杂。
我想把标签设置为一个固定的宽度和换行长度:
l = Label(root)
l['width'] = 30
l['wraplength'] = 244
l['text'] = "testing this"
现在我想查询这个标签,看看用了多少行。可是 l['height'] 一直是 0,所以我能想到的最好办法就是用 l.winfo_height(),然后把得到的像素高度转换成使用的行数。可是在 dir(l) 里没有什么能直接给我这个信息的东西,而且这个方法对字体变化和其他变化很脆弱。
有没有什么建议?
更新:根据 Brian Oakley 的建议(这和我在 usenet 上得到的类似),我有了一个大致的解决方案(还需要改进,比如没有考虑到标签在空白处换行):
import Tkinter as Tk
import tkFont
import random
import sys
def genstr (j):
rno = random.randint(4,50)
ret_val = str(j) + ":"
for i in range (0, rno):
ret_val += "hello" + str(i)
return ret_val
def gendata (lh):
ret_val = []
for i in range(0,lh):
ret_val.append (genstr (i))
return ret_val
data = gendata (100)
root = Tk.Tk()
font = tkFont.Font(family='times', size=13)
class lines:
def __init__ (self):
self.lastct = 1 # remember where the cutoff was last work from there
def count (self, text, cutoff = 400):
global font
no_lines = 1
start_idx = 0
idx = self.lastct
while True:
if idx > len (text):
idx = len (text)
# shrink from guessed value
while font.measure (text[start_idx:idx - 1]) > cutoff:
if idx <= start_idx:
print "error"
sys.exit ()
else:
idx -= 1
self.lastct = idx - start_idx # adjust since was too big
# increase from guessed value (note: if first shrunk then done)
while (idx < len (text)
and font.measure (text[start_idx:idx]) < cutoff):
idx += 1
self.lastct = idx - start_idx # adjust since was too small
# next line has been determined
print "*" + text[start_idx:idx-1] + "*"
if idx == len(text) and font.measure (text[start_idx:]) < cutoff:
return no_lines
elif idx == len(text):
return no_lines + 1
else:
no_lines += 1
start_idx = idx - 1
idx = start_idx + self.lastct
lin = lines()
for i in range(0,len(data)):
lin.count(data[i], 450)
for i in range(0,min(len(data),10)):
l = Tk.Label(root)
l.pack()
l['text'] = data[i]
print i
no = lin.count (data[i], 450)
print "computed lines", no
l['width'] = 50
l['justify'] = Tk.LEFT
l['anchor'] = 'w'
l['wraplength'] = 450
l['padx']=10
l['pady'] = 5
l['height'] = no
l['font'] = font
if i % 2 == 0:
l['background'] = 'grey80'
else:
l['background'] = 'grey70'
root.mainloop()
1 个回答
3
你说得对,height
属性并不会改变。这个属性只是告诉你设置的高度,并不代表实际的高度。实际的高度会受到一些因素的影响,比如里面有多少文字、文字的换行长度、字体的大小,以及这个小部件的布局管理方式。
在tkinter中,Font对象有一个measure
方法,可以让你知道用某种字体显示一段文字的高度和宽度。你可以获取这个小部件的字体,然后用这个方法来计算你的文字需要多少空间。