首页 > 解决方案 > 如何在 tkinter 中设置文本小部件的宽度以使文本小部件等于行长

问题描述

这个问题让我发疯,因为它看起来微不足道,但我已经浪费了很多时间来寻找解决方案,但仍然没有成功。我需要帮助。

假设行是'HelloHelloHelloHelloHello',字体是Georgia 17。如何找到正确的宽度值以使文本小部件的宽度等于行的长度?“小部件的字符宽度(不是像素!),根据当前字体大小测量。” 我的发现表明,提出类似问题的人会得到有关使用字体测量方法的答案,但它不起作用......

import tkinter
import tkinter.font as tkFont

txt='HelloHelloHelloHelloHello'

root=tkinter.Tk()

t_Font = tkFont.Font(family='Georgia', size=17)
width=t_Font.measure(txt)

t=tkinter.Text(root,width=width,font=('Georgia',17))
t.insert(1.0,txt)
t.pack()

结果是荒谬的http://joxi.net/E2p1NJlT7NgjvA.jpg(宽度= 280)。实证研究表明 20 是一个正确的值..但是如何得到呢?使用 len(txt) 看起来好多了,但我相信应该有一个好的解决方案。无法理解我在这里缺少什么...

标签: pythontkintertextwidgetwidth

解决方案


如果您希望Text小部件在文本宽度周围具有以像素为单位的宽度,您可以将Text小部件放在框架内并将框架的大小(以像素为单位)设置为所需的值,然后.place()Text小部件上使用以填充框架:

t_Font = tkFont.Font(family='Georgia', size=17)
width, height = t_Font.measure(txt), t_Font.metrics('linespace')
print(width, height)

lines = 20
# +4 to include the width of the border (default 1) and padding (default 1)
frame = tkinter.Frame(root, width=width+4, height=lines*height+4)
frame.pack()

# put text box inside the frame
t = tkinter.Text(frame, font=t_Font)
t.insert(1.0, txt)
t.place(relwidth=1, relheight=1) # fill the available space of the frame

推荐阅读