2016-09-03 28 views
0

我正在試圖製作一個程序,該程序可以根據文本,字體和字體大小將文本合併到矩形中(x乘y)使用tkinter將文本擬合爲矩形(寬x高y)

下面是代碼

def fit_text(screen, width, height, text, font): 
    measure_frame = Frame(screen) # frame 
    measure_frame.pack() 
    measure_frame.pack_forget() 
    measure = Label(measure_frame, font = font) # make a blank label 
    measure.grid(row = 0, column = 0) # put it in the frame 

    ########################################################## 
    # make a certain number of lines 
    ########################################################## 

    words = text.split(" ") 
    lines = [] 
    num = 0 
    previous = 0 
    while num <= len(words):     
     measure.config(text = " ".join(words[previous:num])) # change text 
     line_width = measure.winfo_width() # get the width 
     print(line_width) 
     if line_width >= width: # if the line is now too long 
      lines.append(" ".join(words[previous:num - 1])) # add the last vsion which wasn't too long 
      previous = num - 1 # previous is now different 
     num = num + 1 # next word 
    lines.append(" ".join(words[previous:])) # add the rest of it 
    return "\n".join(lines) 

from tkinter import *  
window = Tk() 
screen = Canvas(window) 
screen.pack() 
text = fit_text(screen, 200, 80, "i want to fit this text into a rectangle which is 200 pixels by 80 pixels", ("Purisa", 12)) 
screen.create_rectangle(100, 100, 300, 180) 
screen.create_text(105, 105, text = text, font = ("Purisa", 12), anchor = "nw") 

的問題,這是無論什麼文本在標籤從measure.winfo_width()結果始終是1 Here is where I found this from但它似乎並沒有爲我

回答

1

您的代碼的問題在於您使用了窗口小部件的寬度,但寬度將爲1,直到窗口小部件實際佈置在屏幕上並變得可見爲止,因爲實際寬度取決於在這種情況發生之前不存在的因素。

您無需將文本置於小部件中即可進行測量。您可以將字符串傳遞給font.measure(),它將返回呈現給定字體中該字符串所需的空間量。

對於Python 3.x,然後可以導入Font類是這樣的:

from tkinter.font import Font 

對於Python 2.x的,你從tkFont模塊導入:

from tkFont import Font 

然後,您可以創建一個Font的實例,以便您可以獲取有關該字體的信息:

font = Font(family="Purisa", size=18) 
length = font.measure("Hello, world") 
print "result:", length 

您還可以得到一個線的高度與font.metrics()方法給定的字體,給它的參數「linespace」:其實我已經跨越通過試錯這樣做的方式跌跌撞撞

height = font.metrics("linespace") 
+0

我使用python 3.4.1,你知道我在哪裏可以找到Font()函數嗎? –

+0

謝謝,我喜歡你的幫助 –

1

工作小部件在打包之前不會有寬度。您需要將標籤放入框架中,然後將其包裝,然後將其忘掉。

+0

沒有什麼改變,無論我是否打包它仍然說line_width是1,標籤也已經在框架中 –

1

通過使用measure.update_idletasks()它正確計算寬度,它的工作原理!布萊恩奧克利肯定有一個更有效的方式做到這一點,但我認爲這種方法將在其他情況下有用

P.S.我不會介意一些選票,以獲得一個不錯的,有光澤的,銅牌,自學者徽章;)

相關問題