【问题标题】:Tkinter widget Text : count linesTkinter 小部件文本:计算行数
【发布时间】:2021-02-24 15:24:46
【问题描述】:

在这个简短的程序中,我想知道消息需要显示多少行。 问题是,与其回答我这里需要 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()

【问题讨论】:

  • @TheLizzard 是的,刚刚意识到
  • 是的!我知道,因为我需要在主程序中的小部件文本大小之后调整这个数字
  • 我用一个函数试过,用int转换的值不是pb,我无法计算wrap的次数:/
  • 回答下面的作品。

标签: tkinter text count widget line


【解决方案1】:

改编自here

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()

【讨论】:

  • "0.0" 应该是 "1.0" - 第一部分是行,行从 1 开始计数。第二部分是字符,字符从 0 开始计数。
  • @BryanOakley 根据 tcl 文档 "1.0""0.0" 做同样的事情,我更喜欢 "0.0"
  • @BryanOakley 关于索引的 tcl 文档是 here。它说:为了与使用此编号方案的其他 UNIX 程序保持一致,行从 1 开始编号。 并且忽略非法范围。所以"0.0" 总是会产生与"1.0" 相同的影响。
  • @TheLizzard:是的,"0.0" 具有相同的效果,但最好使用正确的索引,尤其是在您试图教别人如何做某事时。
  • 为什么不直接打电话给text.count("1.0", "end", "displaylines")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-04
  • 2012-02-14
  • 1970-01-01
  • 2019-06-14
  • 2014-03-19
相关资源
最近更新 更多