首页 > 解决方案 > Tkinter 小部件文本:计算行数

问题描述

在这个简短的程序中,我想知道需要显示多少行消息。问题是,它没有回答我这里需要 3 行,而是给了我 1。为什么?我尝试了有关该主题的不同解决方案,但没有人在工作,每个人都有一些问题(这里没有计算行数)。

我在 Windows 10 上使用 Python 3.9.2

谢谢您的帮助 !!!

from tkinter import *

root = Tk()
text = Text(root, width = 12, height = 5, wrap = WORD)
text.insert(END, 'This is an example text.')
text.pack()

print(int(text.index('end-1c').split('.')[0]))

root.mainloop()

标签: tkintertextcountwidgetline

解决方案


改编自这里

from tkinter import *

root = Tk()
text = Text(root, width = 12, height = 5, wrap = WORD)
text.insert(END, 'This is an example text.')
text.pack()

root.update()

# Note `text.count("0.0", "end", "displaylines")` returns a tuple like this: `(3, )`
result = text.count("0.0", "end", "displaylines")[0]
print(result)

root.mainloop()

推荐阅读