<p>我正在尝试制作一个程序,它将根据文本、字体和字体大小将文本放入一个矩形(x x y)</p>
<p>这是密码</p>
<pre><code>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.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(" ".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")
</code></pre>
<p>问题是不管标签中的文本是什么,<code>measure.winfo_width()</code>的结果总是1。<a href="https://stackoverflow.com/questions/3950687/how-to-find-out-the-current-widget-size-in-tkinter">Here is where I found this from</a>但这对我似乎不起作用</p>