所以我终于找到了解决问题的办法。通过测量字体高度(以像素为单位)并除以Text的高度,可以找到Text中可以显示的大致行数。它不是绝对准确的(我认为这个值也会受到行间距和/或文本开头/结尾的间距或类似的东西的影响),但是我没有深入研究它,因为这个简单的解决方案非常适合我的需要。在
下面是一个示例代码,以防将来有人需要解决类似的问题。只需运行它,然后调整窗口的大小,您将看到可见线计数将如何变化。在# Text widget lines (rows) count example - tested in Python 3.3.2
from tkinter import Text, font as f
class ExampleApp:
def __init__(self, parent):
font = f.Font(family="courier", size=12)
self.line_height = font.metrics("linespace")
self.text = Text(parent, width=70, height=20, font=font)
self.text.pack(fill=BOTH, expand=Y)
self.text.bind("", self.linecount)
def linecount(self, *args):
num_lines = int(self.text.winfo_height() / self.line_height)
self.text.delete(0.0, END)
self.text.insert(0.0,
"Approximate number of visible lines: %d" % num_lines)
root = Tk()
root.title("Text widget line count example")
app = ExampleApp(root)
root.mainloop()
|