2011-09-03 55 views
1

我有一個標籤,我將放入不同大小的內容。我想知道我需要製作標籤的程度有多高,以便我可以調整窗口的大小,使其可以保持不同的內容大小。我有一個策略,但它應該是更復雜。Tkinter標籤的高度以適應內容

我希望將標籤設置爲指定寬度和wraplength:

l = Label(root) 
l['width'] = 30 
l['wraplength'] = 244 
l['text'] = "testing this" 

現在我要查詢的標籤找到多少行使用。 l ['height']保持爲0,所以我能夠想到的最好的方法是使用l.winfo_height()並將像素的高度轉換爲使用的行數。 dir(l)似乎沒有直接給我提供信息,但是這種策略對於字體變化和其他變化是脆弱的。

有什麼建議嗎?

更新:使用布賴恩·奧克利的建議(這是類似於我在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() 

回答

3

您確定height屬性未更改。該屬性不會告訴你實際的高度,只是它配置的高度。實際高度取決於諸如其中的文本數量,包裝長度,字體以及如何管理窗口小部件幾何體等因素。

tkinter字體對象有一個measure方法,可以讓您確定給定字體的字符串的高度和寬度。您可以獲取小部件的字體並使用該方法來確定字符串需要多少空間。