我正在尝试制作一个程序,它将根据文本、字体和字体大小将文本放入一个矩形(x 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但这对我似乎不起作用
事实上,我偶然发现了一种通过反复试验来做到这一点的方法
通过使用
measure.update_idletasks()
它可以正确地计算宽度并且可以工作!布莱恩·奥克利肯定有一个更有效的方法来做这件事,但我认为这种方法在其他情况下也会有用另外,我也不介意投票来获得一个漂亮、闪亮、青铜色、自学成才的徽章;)
小部件在打包之前没有宽度。你需要把标签放进镜框里,然后打包,然后忘掉它。在
你的代码的问题是你使用的是一个小部件的宽度,但是在这个小部件真正在屏幕上显示出来之前,它的宽度是1,因为实际的宽度取决于很多因素,而这些因素在这之前是不存在的。在
你不需要把文本放在一个小部件中来测量它。您可以向
font.measure()
传递一个字符串,它将返回以给定字体呈现该字符串所需的空间量。在对于python 3.x,可以导入
Font
类,如下所示:对于python 2.x,您可以从
^{pr2}$tkFont
模块导入它:然后,您可以创建
Font
的实例,以便获得有关该字体的信息:您还可以使用
font.metrics()
方法获得给定字体中一行的高度,给它一个参数“linespace”:相关问题 更多 >
编程相关推荐