我有一个标签,我将把不同大小的内容放入其中。我想知道我需要制作标签的高度,以便我可以调整窗口的大小,以便它可以保持不同内容大小的相同。我有一个策略,但它似乎应该更复杂。
我想将标签设置为给定的宽度和强度:
l = Label(root)
l['width'] = 30
l['wraplength'] = 244
l['text'] = "testing this"
现在我想查询标签以查找使用了多少行。 l ['height']保持为0,所以我能想到的最好的是使用l.winfo_height()并将以像素为单位的高度转换为使用的行数。 dir(l)中的任何内容似乎都没有直接提供给我信息,但这种策略对字体更改和其他更改都很脆弱。
有什么建议吗?
更新:使用Brian Oakley的建议(类似于我在usenet上获得的建议)我对解决方案有以下近似(需要抛光,例如没有考虑到Label在空白处断开):
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()
答案 0 :(得分:3)
您是正确的height
属性不会更改。该属性不会告诉您实际高度,只会告诉您配置的高度。实际高度取决于多少因素,例如文本的大小,包装长度,字体以及窗口小部件几何体的管理方式。
tkinter字体对象具有measure
方法,可让您确定字符串对于给定字体的高度和宽度。您可以获取窗口小部件的字体并使用该方法确定字符串需要多少空间。