python - 如何在 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) 看起来好多了,但我相信应该有一个好的解决方案。无法理解我在这里缺少什么...
解决方案
如果您希望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
推荐阅读
- angular - 保存与本地银行支付网关集成的 Angular 表单中的数据
- swift - ClosedRange 第二个参数变小并返回 nil
- gradle - Gradle checkstyleTest 失败“CheckstyleException:属性‘allowMissingPropertyJavadoc’不存在”
- angular - 如何在 Ionic/Angular 中预加载指令 + 相应的 HTML?(Mapbox 指令)
- mysql - 在查询生成器中查询不同的行
- javascript - 知道为什么 adonis 迁移命令不起作用吗?
- arrays - 如何仅将文件中的必要行写入bash脚本中的数组?
- html - 使边距不可点击
- react-native - react-navigation :在屏幕之间正确传递状态
- python - 在 Pythons Scikit-Learn lib 中使用分类数据进行异常值预测